From logiplexsoftware at earthlink.net Mon Mar 25 15:51:31 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Mon, 25 Mar 2002 12:51:31 -0800 Subject: Replacing excel: but with what ? In-Reply-To: <3C9CF7A6.51F112EC@olen.to> References: <3C9CCF6C.F1099089@vip.fi> <3C9CF7A6.51F112EC@olen.to> Message-ID: <20020325125131.094736ff.logiplexsoftware@earthlink.net> On Sat, 23 Mar 2002 23:46:14 +0200 Joonas Paalasmaa wrote: > Does Tkinter meet your needs? You can create a spreadsheet by griddinng > Entry widgets. There is an example in Lutz's Programming Python 2'nd > Edition, if you happen to owe it. Doing this was exactly what moved me to wxPython a couple of years ago. This approach will work, but it will be extremely slow for even a moderately large spreadsheet. I even tried writing a spreadsheet widget from scratch using Tkinter and although it was much faster, it was still too slow (unfortunately I no longer have the code or I'd send it to you =P). Something like this needs be written in a compiled language. The wxGrid control is certainly one of the least stable of the wxPython widgets, but I think if you build your wxWindows and wxPython from CVS you'll find that many of the problems have been fixed. Hopefully a release is in the works that includes these fixes in the near future. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From martin at v.loewis.de Sat Mar 30 15:48:04 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 21:48:04 +0100 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> <3CA5F90F.BF37B528@engcorp.com> Message-ID: Peter Hansen writes: > So does this change proposes to change the readability so that > it is clear at a glance (at the source, not the documentation, which > seems an odd thing to base this on) that those functions return > boolean conditions rather than integers? The documentation should change as all, documenting that certain functions return bool. > If that is _all_ this change does, I suppose it would be okay. > If it in _any way_ changes the functionality one can currently > expect for those return values, such as the ability to use as > indices into a sequence, then I'm still very -1. Their type changes, and their repr. Apart from that, nothing changes. > Furthermore, there will be code breakage, and that should always > rate very high on the list of reasons to leave well enough alone. Can you show examples of (real!) code that will break? Preferably code you've written yourself. Regards, Martin From webmaster at greich.co.uk Fri Mar 1 00:29:14 2002 From: webmaster at greich.co.uk (David Russell) Date: Fri, 1 Mar 2002 05:29:14 -0000 Subject: Python's Syntax References: Message-ID: Thanks, I think I get it now. From NO_SPAM_jmpurser2 at attbi.com Tue Mar 12 20:45:44 2002 From: NO_SPAM_jmpurser2 at attbi.com (John Purser) Date: Wed, 13 Mar 2002 01:45:44 GMT Subject: struct.calcsize() giving odd results - Solved References: <3Rvj8.27781$af7.23161@rwcrnsc53> Message-ID: Grant, That got it. Thanks it was driving me nuts. Time to go back and RTFM some more. John Purser "Grant Edwards" wrote in message news:W_vj8.20309$N7.4753798 at ruti.visi.com... > In article <3Rvj8.27781$af7.23161 at rwcrnsc53>, John Purser wrote: > > [regarding struct size that isn't what he wants] > > > And that's it. I tucked this into a variable (fmt) and ran it through > > struct.calcsize(fmt) and got 190. I assumed I'd made a typo so I went over > > my string. No problems there. So I assumed I added it up wrong in the > > first place. Nope, 180 bytes. > > By default, struct will use the alignment/packing conventions > used by the native C compiler. If you want something else, > you've got to specify it. > > Try adding a "=" to the front of your format string. > > -- > Grant Edwards grante Yow! ALFRED JARRY! Say > at something about th' DEATH > visi.com of DISCO!! From logstx at bellatlantic.net Tue Mar 12 22:05:02 2002 From: logstx at bellatlantic.net (logistix) Date: Wed, 13 Mar 2002 03:05:02 GMT Subject: fun codeop hack Message-ID: Replace the Compile class with the following: class Compile: """Instances of this class behave much like the built-in compile function, but if one is used to compile text containing a future statement, it "remembers" and compiles all subsequent program texts with the statement in force.""" macros = [] def __init__(self): self.flags = 0 def __call__(self, source, filename, symbol): for macro in Compile.macros: source = macro(source) codeob = compile(source, filename, symbol, self.flags, 1) for feature in _features: if codeob.co_flags & feature.compiler_flag: self.flags |= feature.compiler_flag return codeob ============================ Now you can do all kinds of fun stuff like this in IDLE and PythonWin ============================ PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import re >>> forRe = re.compile(r'for\s+(\w+)\s*=\s*(\d+)\s+to\s+(\d+)\s*:') >>> def newFor(string): ... return forRe.sub(r'for \1 in range(\2, 1 + \3):',string) ... >>> import codeop >>> codeop.Compile.macros.append(newFor) >>> >>> for i = 1 to 6: ... print i, i*i ... 1 1 2 4 3 9 4 16 5 25 6 36 >>> PS. For the record I'm perfectly happy with current for loop syntax. Just thought it was a good example From gimbo at ftech.net Wed Mar 20 06:58:51 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 20 Mar 2002 11:58:51 +0000 Subject: module for accessing dBase (.dbf) files? In-Reply-To: References: <3C725F2C.2020406@gncz.cz> Message-ID: <20020320115851.GB18197@andy.tynant.ftech.net> On Wed, Mar 20, 2002 at 11:51:40AM +0100, Harald Schneider wrote: > > "Ondrej Martinek" schrieb im Newsbeitrag > news:3C725F2C.2020406 at gncz.cz... > > Hi, > > > > anyone knows a python module for accessing dBase .dbf files. All > > modules I've found so far didn't support index files. This dismayed me too until I realised I probably didn't really need index files. Of course, it depends on the size of the table in question, but for my purposes (tables < 10Mb) I got away with just reading the whole table into memory and sorting it however I wanted using python's standard .sort() mechanism (using comparison functions as appropriate). I used this DBF module: http://www.vex.net/parnassus/apyllo.py?i=96891420 Of course, YMMV, if you've got 100Mb tables this might well be less attractive... Just a thought. -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From jdgorman at ieee.org Wed Mar 13 03:06:05 2002 From: jdgorman at ieee.org (John Gorman) Date: Wed, 13 Mar 2002 08:06:05 GMT Subject: Newbie Import two coloums of floating point data into python HOWTO References: <7eb201fc.0203110422.1e9c7dec@posting.google.com> Message-ID: <3C8F089A.7090108@ieee.org> Andy, There are also several python scripts/utilities that people have posted for loading tabular data into python and numpy arrays. These might be overkill for what you're doing, but could be helpful for large arrays. Check out the following: ASV, csv, DataHandlers (see Parnassus link below) http://www.vex.net/parnassus/apyllo.py/973100124 or TableIO http://php.iupui.edu/~mmiller3/python/ TableIO has hooks to convert ascii/csv data into Numerical Python arrays. This is quite useful and I've used it in the past to migrate arrays between Matlab, NumPy, Gnumeric and MS Excel. This'll even work for importing ascii formatted images into Python, although I wouldn't recommend it for that purpose ;^). Cheers, John Gorman Andy Gimblett wrote: > On Mon, Mar 11, 2002 at 04:22:48AM -0800, Andybee wrote: > > >>Can some one tell me how to import two coloumns of data in a ascii >>text file,into two arrays in python? I cant seem to work it out. The >>data is genereated in matlab and I want to import it into python >> > > Let's say you data looks something like this: > > 1.0 5.0 > 2.0 10.2 > 3.1 13.4 > > etc. > > Then here's one answer... There are probably cleverer and more > efficient ways of doing this, but this one's pretty easy to understand > and so hopefully more suited to a newbie... :-) > > I'm also not _quite_ answering your question, because you asked how to > get two seperate lists, one per column, whereas what this does is > return a list of tuples (one tuple per data line), which is how _I'd_ > do it. ;-) Easy to change to your way, anyway. > > def foobar(filename): > > # We'll return a single list, consisting of 2-element tuples, one > # per line in the data file. > > results = [] > > # Open the input file and read the lines. Note that this reads > # them all in before continuing, and so would be unsuitable for a > # large file. Possible alternatives would involve using > # readline() or xreadlines(), the investigation of which is left > # as an exercise to the reader. :-) > > input = open(filename) > lines = input.readlines() > > # Now iterate over the lines, populating the result > > for line in lines: > > if not line.strip(): > # Skip blank line > continue > > # Split the line up, convert the values to floats, add it to > # the result set. > > (first, second) = line.split() > row = (float(first), float(second)) > results.append(row) > > return results > > BTW, if you haven't seen it yet, I'd heartily recommend that you work > through the python tutorial at: > > http://www.python.org/doc/current/tut/tut.html > > This contains everything you'd need to answer your question/understand > the above, and a whole lot more. > > HTH, > > Andy > > From skip at pobox.com Thu Mar 28 11:37:40 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 28 Mar 2002 10:37:40 -0600 Subject: Extension Modules in C In-Reply-To: <3CA34211.5D367EAB@amtec.com> References: <3CA34211.5D367EAB@amtec.com> Message-ID: <15523.18132.97741.188602@beluga.mojam.com> Michael> Some of the functions have parameters that are both input and Michael> output.... Does Python support this notion of a passed Michael> parameter being modified? Nope. You'll have to adjust your call interface to return the modified values. Michael> int GetSomeInfo(char **Title, int *count, int *size); Michael> where it would be called as follows: Michael> int isOk, count, size; Michael> isOk = GetSomeInfo(NULL, &count, &size); Your wrapper would probably return a tuple containing the modified values of count and size if the method succeeded, and raise an exception or return an empty tuple if not. (The latter case is problematic. I'd raise an exception.) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From tejarex at yahoo.com Fri Mar 29 03:03:55 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 29 Mar 2002 08:03:55 GMT Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> <3CA3768B.32BB6AC9@ccvcorp.com> Message-ID: "phil hunt" wrote in message news:slrnaa7e6a.eau.philh at comuno.freeserve.co.uk... > On Thu, 28 Mar 2002 12:01:15 -0800, Jeff Shannon wrote: > >I disagree. I'm just as happy that Python doesn't try to guess what would be a > >suitable "default" value for non-existent keys. > > The default value should always be None. > > None should act like 0 or "" or [] or {} where appropriate, i.e.: > > None + 1 --> 1 > None + "x" --> "x" > None * 4 --> 0 > None + ['x'] --> ['x'] > None + {2:3} --> {2:3} Please no!. A missing value is missing, and should not be used for any further analysis! Having a 'no value' built into the language is one of the nice things about Python. Terry J. Reedy (sometime statistical consultant) From barry at zope.com Mon Mar 18 12:26:49 2002 From: barry at zope.com (Barry A. Warsaw) Date: Mon, 18 Mar 2002 12:26:49 -0500 Subject: RELEASED email package version 1.2 Message-ID: <15510.9049.480183.273456@anthem.wooz.org> I've released the standalone email package version 1.2. This version has much better support RFC 2047, especially when using multibyte character sets (much thanks go to Ben Gertzfield). A NEWS file excerpt is included below. I will eventually be merging this code into the Python distro, but there are a few new features I want to look at first. One of them includes RFC 2231 support (written by Oleg Broytmann). You can get the standalone email package from SourceForge: http://sourceforge.net/projects/mimelib/ Bug reports to this project please, not to the Python bug tracker (until this code is merged into the Python distro). Enjoy, -Barry -------------------- snip snip -------------------- 1.2 (18-Mar-2002) - In the MIMEText class's constructor, the _encoder argument is deprecated. You will get a DeprecationWarning if you try to use it. This is because there is a fundamental conflict between _encoder and the fact that _charset is passed to the underlying set_payload() method. _encoder really makes no sense any more. - When Message.set_type() is used to set the Content-Type: header, the MIME-Version: header is always set (overriding any existing MIME-Version: header). - More liberal acceptance of parameter formatting, e.g. this is now accepted: Content-Type: multipart/mixed; boundary = "FOO" I.e. spaces around the = sign. - Bug fix in Generator related to splitting long lines in a multiline header. - In class Charset, __str__() method added, as were __eq__() and __ne__(). - Charset.get_body_encoding() may now return a function as well as a string character set name. The function takes a single argument, which is a Message instance, and may change the Content-Transfer-Encoding: header (or do any other manipulations on the message). - Charset.from_splittable() added argument to_output which is used to specify whether the input_codec or the output_codec is used for the conversion (by default, the output codec is used). 1.1 (unreleased) - No changes since 0.97. Only the version number has changed. 0.97 (unreleased) - Message.set_charset() can now take a string naming a character set in addition to a Charset instance. In the former case, a Charset is instantiated by passing the string to its constructor. - The MIMEText constructor now passes the _charset argument to the underlying set_charset() method. This makes things consistent at the cost of a minor semantic change: the resulting instance will have a Content-Transfer-Encoding: header where previously it did not. - A fix for a crash when quopriMIME.encode() tried to encode a multiline string containing a blank line. - New module Header.py which provides a higher level interface for encoded email headers, such as Subject:, From:, and To:. This module provides an abstraction for composing such headers out of charset encoded parts, and for decoding such headers. It properly splits lines on character boundaries even for multibyte character sets. - New RFC compliant base64 and quoted-printable modules, called base64MIME.py and quopriMIME.py. These are intended to replace the Python standard base64.py and quopri.py modules, but are geared toward their use conformant to the various MIME email standards. - The Message class is much more character set aware and RFC compliant: + set_payload() now takes a new optional charset argument + New methods set_charset(), get_charset(), set_param(), del_param(), set_type() + Header parameter quoting is more RFC compliant + get_param() and get_params() now take a new optional unquote argument - The Charset module now knows about utf-8, gb2132, and big5 codecs, the latter two of which are available independently of Python (see the comments in this module for downloading Chinese, Japanese, and Korean codecs). New Charset methods get_body_encoding(), get_output_charset(), encoded_header_len(), header_encode(), and body_encode(). - The Generator now handles encoding the body, if the message object has a character set. - The Utils module has new functions fix_eols() and make_msgid(). It also includes a workaround for bugs in parseaddr() when used with Python versions before 2.2. - A fix for a Parser bug when parsing multipart/* parts that contain only a single subpart. From gh_pythonlist at gmx.de Thu Mar 7 14:16:08 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 7 Mar 2002 20:16:08 +0100 Subject: 'The Goat and the Car' puzzle solved in Python -- was: [GERMAN] "ziegenproblem" In-Reply-To: <20020308002819.GA1571@blackscarab> References: <20020308002819.GA1571@blackscarab> Message-ID: <20020307191607.GB1748@lilith.hqd-internal> Le 07/03/02 ? 19:28, stefan antoni ?crivit: > sorry that i won't be able to explain this in english, i don't know the > name of this problem in english, and the website which is about this > problem is also in german. > > i want to write this basic code in python: > http://www.google.de/search?q=cache:Uugc3CH9SOQC:home.spektracom.de/ellrich/Ziegen.htm+ziegenproblem+basic+programm&hl=de > > i am still going to school, and we talked about this problem in a math > lesson. since i haven't got a basic-interpreter, i'd like to translate > this code into python, but i don't understand the code. The BASIC code hurts my eyes. I've hacked a Pythonic solution: import random prices = ["goat", "goat", "car"] iterations = 2000 times_won = 0 for i in range(iterations): random.shuffle(prices) mypick = random.randrange(3) # Moderator chooses a 'goat door' randomly while 1: goat_chosen_by_moderator = random.randrange(3) if prices[goat_chosen_by_moderator] != "car" and \ goat_chosen_by_moderator != mypick: break # We take the other door! door_numbers = range(3) door_numbers.remove(mypick) door_numbers.remove(goat_chosen_by_moderator) mypick = door_numbers[0] # Is there a a car? if prices[mypick] == "car": times_won += 1 print float(times_won) / iterations Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 9.7 ?C Wind: 4.9 m/s From sam_collett at lycos.co.uk Thu Mar 7 04:26:57 2002 From: sam_collett at lycos.co.uk (Sam Collett) Date: 7 Mar 2002 01:26:57 -0800 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> Message-ID: <2030665d.0203070126.55addc33@posting.google.com> > Actually, I usually use a few more cases so that I always get two > significant digits: 1.2k, 23k, 840k, 2.4M, etc. How would you do that then (maybe even to 2 decimal places, e.g. 24.52kb)? From metaliu at yahoo.com Thu Mar 7 20:22:54 2002 From: metaliu at yahoo.com (Bill) Date: Thu, 7 Mar 2002 17:22:54 -0800 Subject: quick Tkinter Label question Message-ID: I have a label widget with an image being displayed. The image changes. Now how do I update the label widget? assuming I have a ImageTk PhotoImage called tkim: root = Tk() l = Label(root, image=tkim, bd=0) l.pack() .... tkim changes... calling l.pack() doesnt update the label widget with the new image. neither does calling l.update(). The Intro to Tkinter doc says "The label widget uses double buffering, so you can update the contents at any time, without annoying flicker." Can someone help me on how to do that? Thanks in advance, Bill From sam_collett at lycos.co.uk Fri Mar 8 07:06:42 2002 From: sam_collett at lycos.co.uk (Sam Collett) Date: 8 Mar 2002 04:06:42 -0800 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> <2030665d.0203070126.55addc33@posting.google.com> <3C87A28B.549D9B1C@noaa.gov> Message-ID: <2030665d.0203080406.5b1b008b@posting.google.com> How would you remove trailing 0's? e.g. Instead of 12.20kb it would be 12.2kb 23kb instead of 23.00 etc Chris Barker wrote in message news:<3C87A28B.549D9B1C at noaa.gov>... > Sam Collett wrote: > > > > > Actually, I usually use a few more cases so that I always get two > > > significant digits: 1.2k, 23k, 840k, 2.4M, etc. > > How would you do that then (maybe even to 2 decimal places, e.g. 24.52kb)? > > You make sure the result of your division is a Float (Ah, how I long for > the "new division" to be standard!) and you use %f instead of %d > > #!/usr/bin/env python > > > def ShowSize(raw): > if raw < 3000: > return "%db" % raw > elif raw < 2000000: > return "%.2fkb" % (raw / 1000.) > elif raw < 2000000000L: > return "%.2fMb" % (raw / 1000000.) > else: > return "%.2fGb" % (raw / 1000000000.) > > > print ShowSize(2567L) > print ShowSize(2567000L) > print ShowSize(256700000L) > print ShowSize(2567000000L) > print ShowSize(256700000000L) > > And here are the results: > > >>> execfile("junk.py") > 2567b > 2.57M > 256.70M > 2.57G > 256.70G > > -- > Christopher Barker, Ph.D. > Oceanographer > > NOAA/OR&R/HAZMAT (206) 526-6959 voice > 7600 Sand Point Way NE (206) 526-6329 fax > Seattle, WA 98115 (206) 526-6317 main reception > > Chris.Barker at noaa.gov From bkc at Murkworks.com Fri Mar 8 17:10:13 2002 From: bkc at Murkworks.com (Brad Clements) Date: Fri, 8 Mar 2002 17:10:13 -0500 Subject: why is python slow? References: Message-ID: <3c8937e0$1_10@news.newsgroups.com> "Skip Montanaro" wrote in message news:mailman.1015611735.7436.python-list at python.org... > that can be done. Why not file a bug report, investigate and solve the > problem, then grab some of that fame and fortune I alluded in my post > seeking new developers yesterday? (I'm not picking on Donn, he just happens > to be the one who raised this issue and gave me the nice segue.) Not to segue myself but.. I have patch (505846) sitting in the list since January 19th. After a flurry of give and take activities (i.e. submitting better versions of the patch), nothing has happened since January 28th. I have other patches that depend on this one first (For Windows CE and NetWare) that I have not submitted. I've tried to be good and just wait.. But how long should I expect to wait? I've begged a few times for a response.. Either a rejection or a "be patient" would be nice, but haven't received either. I figured everyone was busy for IPC10.. But still, no response. :-( -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! Check out our new Unlimited Server. No Download or Time Limits! -----== Over 80,000 Newsgroups - 19 Different Servers! ==----- From dreed at capital.edu Tue Mar 26 18:06:48 2002 From: dreed at capital.edu (Dave Reed) Date: Tue, 26 Mar 2002 18:06:48 -0500 Subject: python on Sharp Zaurus Message-ID: <200203262306.g2QN6m119697@localhost.localdomain> Does anyone know if Python runs on the new Sharp Zaurus? http://www.idg.net/go.cgi?id=656429 Thanks, Dave From tim.one at comcast.net Sat Mar 30 17:25:26 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 17:25:26 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: <2zRcLUAVjXp8EwVv@jessikat.fsnet.co.uk> Message-ID: [Robin Becker] > This pretty much seems unwanted to me. Done purely for political > correctness. Whenever new keywords are discussed the Gods are against > them. Now we have to accept new constants true, false + a new type. True, False and bool aren't proposed to be keywords; they're just new builtins. If you currently have code doing try: True except NameError: breathe() I suppose you'll stop breathing. but-if-you-have-code-like-that-maybe-it's-for-the-best-ly y'rs - tim From logiplexsoftware at earthlink.net Fri Mar 22 14:58:12 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 22 Mar 2002 11:58:12 -0800 Subject: SECURITY ALERT!!! . gvc In-Reply-To: References: Message-ID: <20020322115812.2c807086.logiplexsoftware@earthlink.net> On Thu, 22 Mar 2001 15:30:28 -0000 lwvSecurity wrote: > Since the invention of Microsoft Windows, and the further invent of newer Windows versions, (thanks Bill) life has got easier for you and me to work with computers. > > At the same time computers have got much more power fuller, and smaller at the same time. The same computer you are using now would take the most part of your room 15 - 20 years ago. But apparently users are still as illiterate as ever. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From bernie at 3captus.com Tue Mar 5 03:08:24 2002 From: bernie at 3captus.com (Bernard Yue) Date: Tue, 05 Mar 2002 08:08:24 GMT Subject: Brewster's Factor - was :Trouble running programs References: Message-ID: <3C847D7C.5F75CB46@3captus.com> Laura Creighton wrote: > > Bernard Yue's sig is: > > > > There are three schools of magic. One: State a tautology, then ring > > the changes on its corollaries; that's philosophy. Two: Record many > > facts. Try to find a pattern. Then make a wrong guess at the next > > fact; that's science. Three: Be aware that you live in a malevolent > > Universe controlled by Murphy's Law, sometimes offset by Brewster's > > Factor; that's engineering. > > > > So far as I can remember, there is not one word in the Gospels in > > praise of intelligence. > > -- Bertrand Russell > > I wanted to know what Brewster's Factor was. I found out that the first > part of the quote -- the bit that ends with Engineering should be > attributed to Robert A. Heinlein (from The Number of the Beast). Number of the Beast!!! Read the book but don't remember the quote !! Thanks for the correction. > But the only Brewster Factors I can find have to do with polarised light, > or English Chrisitian Revivalist Victorian political parties, neither > of which I suspect is what I am looking for. Any ideas? Laura, I believe you found what you have looking for. I think in the quote Brewster Factor is refering to Brewster Law. Which states that non-polarized light will be reflected as polarized light (a special case in reflection) and reflected and refracted light will be in right angle. I see this as an analogy to Engineering, in which a system only works under certain conditions (Brewster Angle) and failed to function otherwise (Murphy's Law). Robert A. Heinlein should be able to another the question, but we are nearly 14 years too late. > > Laura Creighton I love this newsgroup. Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein Laura Creighton wrote: > > Bernard Yue's sig is: > > > > There are three schools of magic. One: State a tautology, then ring > > the changes on its corollaries; that's philosophy. Two: Record many > > facts. Try to find a pattern. Then make a wrong guess at the next > > fact; that's science. Three: Be aware that you live in a malevolent > > Universe controlled by Murphy's Law, sometimes offset by Brewster's > > Factor; that's engineering. > > > > So far as I can remember, there is not one word in the Gospels in > > praise of intelligence. > > -- Bertrand Russell > > I wanted to know what Brewster's Factor was. I found out that the first > part of the quote -- the bit that ends with Engineering should be > attributed to Robert A. Heinlein (from The Number of the Beast). But > the only Brewster Factors I can find have to do with polarised light, > or English Chrisitian Revivalist Victorian political parties, neither > of which I suspect is what I am looking for. Any ideas? > > Laura Creighton -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein So far as I can remember, there is not one word in the Gospels in praise of intelligence. -- Bertrand Russell One OS to rule them all, one OS to find them, One OS to bring them all and in the darkness bind them, In the Land of Redmond, where the Shadows lie. From gh_pythonlist at gmx.de Wed Mar 13 19:10:56 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 14 Mar 2002 01:10:56 +0100 Subject: Statically linking standard Python modules into an application In-Reply-To: References: Message-ID: <20020314001055.GB1347@lilith.hqd-internal> Le 13/03/02 ? 16:44, Brian Forney ?crivit: > [...] Is there a way to statically link in all of the standard modules > *and* the Python library *and* keep the Python library from calling > dlopen() for standard modules? You need to edit Modules/Setup, then rebuild Python. In theory, putting a "*static*" line at the top, then adding the modules normally built with distutils to this file should do the trick. Gerhard From rwgk at yahoo.com Fri Mar 1 02:05:07 2002 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: 28 Feb 2002 23:05:07 -0800 Subject: Scripting C++ -- 2 -- a more concrete example. References: <3C7E6642.2030202@physics.ucsb.edu> Message-ID: <8be7693c.0202282305.12ee7d46@posting.google.com> Craig Maloney wrote in message news:<3C7E6642.2030202 at physics.ucsb.edu>... > Thanks to all for the great leads to wrapper generators for > Suppose that I have a class Crystal, and a class Atom. I'd like to be > able to do the following: > > ----------------- > Crystal c; > ... > Atom a1; > Atom a2; > ... > > c.addAtom(a1); > c.addAtom(a2); > ... > c.computeEnergy(); > --------------------- > > Atom is a simple enough data structure that default copy works. Crystals and atoms... that looks familiar to me :-) See cctbx.sf.net. This is a C++ library with Python bindings implemented using Boost.Python. > Now here comes the concrete question. If I want to use this class > library from a scripting language (e.g. Python) what are the pros and > cons of using wrapper code (e.g. Boost.Python or SILOON from lanl) vs CORBA. > > To me the main differences are: > > 1) Interface generation. > If I use CORBA, I would have to write IDL interfaces on top of the > library, since there is no reverse mapping from C++ as there is in java. > It seems contrary to the spirit to write the IDL *after* I've written > the class library -- indicating a lack of regard to issues of > distributedness in designing the class library. (see my comment at the end) > > If I use wrapper generators, it seems like there is a chance (e.g. using > SILOON/PDT or BOOST/PDT) that it would be possible to have the wrapper > code automatically generated. I do not know about PDT, it certainly is not currently integrated with Boost.Python. I.e. you have to write the wrappers manually. If you do this while developing a library, the extra coding time is in general negligible compared to the time it takes to develop the rest. If you want to wrap a large existing library it can be a bit cumbersome. > This is a major boon as I would not have to convert > std::valarray to sequence or whatever monkeying I would > have to do. I can imaging this getting pretty hairy to the point of > unworkable. > > 2) Marshalling and Objects-by-value. > When the "Crystal" computes its energy it should *NOT* have to marshall > calls to get at the atom data structures. This is an operation that > will be repeated about 2.85 bijillllion times. In CORBA, this is no > problem -- I would either have Crystal::addAtom take a valuetype (atoms > are easy enough to serialize), or I would use some "co-location" trick > so that the ORB knows that the atom *really* lives in the same address > space as the crystal. Preferrably the former. > > If using a wrapper generator (e.g. SILOON) I don't see a way around the > marshalling of the call to get at the atom data structure. > > Of course, this would be taken care of by a revamp of the design of the > class library... maybe making the crystal an atom factory that produces > new atoms in its own address space. But I would like to avoid thinking > about multi-language and distribution issues when designing the core of > the library. Is this dream just simply self-contradictory? Does "marshalling" mean converting objects to strings (and vice versa)? If you use Boost.Python the wrapped C++ objects are never marshalled. The run-time overhead for crossing the language boundary is very small. In our applications (higher-level management in Python, number-crunching in C++) it is hardly ever noticeable. Ralf From kragen at pobox.com Wed Mar 27 15:27:01 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 27 Mar 2002 15:27:01 -0500 Subject: thread-safe swap Message-ID: <833cyl3gfe.fsf_-_@panacea.canonical.org> Someone recommended using the idiom spam, eggs = eggs, spam to get a thread-safe swap. Does this really work? >>> import dis >>> def x(a, b): a, b = b, a ... >>> dis.dis(x) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_FAST 1 (b) 9 LOAD_FAST 0 (a) 12 BUILD_TUPLE 2 15 UNPACK_SEQUENCE 2 18 STORE_FAST 0 (a) 21 STORE_FAST 1 (b) 24 LOAD_CONST 0 (None) 27 RETURN_VALUE So if this thread loses control anywhere between the first LOAD_FAST and the last STORE_FAST, a value could get stored by another thread into "b" which would then be lost. There isn't anything keeping this from happening, is there? From maurelius01 at hotmail.com Thu Mar 21 16:03:23 2002 From: maurelius01 at hotmail.com (Marc) Date: 21 Mar 2002 13:03:23 -0800 Subject: mutlifile inheritance problem Message-ID: <9896e047.0203211303.741f695a@posting.google.com> I have classes defined in different files and would like to inherit from a class in file A.py for a class in file B.py but am running into problems. I'm using Python 1.5.2 on Windows NT Here's a specific example: ************************ file cbase01.py: class CBase: def __init__(self): self.cclass = None print "cbase" class CImStream(CBase): def __init(self): CBase.__init__(self) print "CImStream" ************************* in file wrappers_A01.py: import cbase01 reload(cbase01) class ImStream_SavedBitmaps(cbase01.CImStream): def __init__(self): cbase.CImStream.__init__(self) print "SavedBitmaps" ************************** in file sequencer01.py import cbase01 # the offending lines, program works reload(cbase01) # if I comment these out. class Sequencer: def Append(self, item): pass ***************************** in test02.py import wrappers_A01 reload(wrappers_A01) import sequencer01 reload(sequencer01) x0 = wrappers_A01.ImStream_SavedBitmaps() *************************************************************** If I run test02 I get the traceback Traceback (innermost last): File "", line 1, in ? File "D:\PythonCode\pna\eyeTracking\tests\test02.py", line 15, in ? x0 = wrappers_A01.ImStream_SavedBitmaps() File "D:\PythonCode\pna\eyeTracking\tests\wrappers_A01.py", line 21, in __init__ cbase.CImStream.__init__(self) TypeError: unbound method must be called with class instance 1st argument Any ideas what I am doing wrong? Thanks, Marc From narnett at mccmedia.com Mon Mar 25 00:37:14 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Sun, 24 Mar 2002 21:37:14 -0800 Subject: Debugging on windows via print statements -- reliable? In-Reply-To: <3C9EA59A.D3F76D2F@engcorp.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen [snip] > By the way, how can Python code get "stuck"? Is it a logic flaw, > or are you talking about the kind of "stuck" that used to happen, > in the "old days", when we were always writing code in languages > which would actually crash the computer? I'm using these vague adjectives because I can't tell what is happening. Somewhere in the midst of retrieving pages with urllib and parsing them with sgmllib, everything seems to stop. And yes, it's a console app for the moment. I have a GUI that'll control it, but I'm working on pieces that grab web pages, extract data and stick them in MySQL. The only thing I'm sure of is that it's not a problem with the database. It happens at a different point each time, sometimes after a few dozen pages, sometimes after a couple of hundred. And I can re-do the same sequence of pages and it'll freeze/loop/stop/whatever at a different point each time. The process is alive, there's no memory size change and it's consuming very few CPU cycles when this happens. I'm working in PythonWin and I would have hoped that "break into running code" would get me into it when this happens, so I could see where it's getting stuck, but no, that would apparently be too convenient. Nick From gimbo at ftech.net Tue Mar 19 10:41:14 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Tue, 19 Mar 2002 15:41:14 +0000 Subject: Getopt / matching problem In-Reply-To: <3C9751DD.1070204@beth.uniforum.org.za> References: <3C9751DD.1070204@beth.uniforum.org.za> Message-ID: <20020319154114.GA8801@andy.tynant.ftech.net> On Tue, Mar 19, 2002 at 04:57:33PM +0200, mixo wrote: > > From running the command "python script.py --use=mixo" > I get the result > [('--user', 'mixo')] > > Why do I get match? Is there something that I have left out? > If I pass "--u", "--us" to script I get the same result? >From the getopt module documentation: Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, it long_options is ['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised. So it's nothing to worry about, just the documented behaviour, and really the way we'd want it to work, if you think about. Cheers, -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From timr at probo.com Sun Mar 3 19:16:29 2002 From: timr at probo.com (Tim Roberts) Date: Sun, 03 Mar 2002 16:16:29 -0800 Subject: Fw: smtplib: including a subject References: Message-ID: <4ve58uc3h1r0qsqp1moa60iug54m32043n@4ax.com> "Tal Linzen" wrote: >Hi. > >I couldn't figure out how to send a mail with a >subject. Help? The KEY point to remember is that smtplib is used, as the name implies, to manage SMTP. SMTP cares nothing about the actual content of the message. It doesn't read the headers at all; the headers and the message body are equally irelevant to SMTP. Here's a sample SMTP exchange: 1. MAIL FROM: 2. RCPT TO: 3. RCPT TO: 4. DATA 5. Subject: This is a subject. 6. From: 7. To: 8. 9. Just checking! 10. . Only lines 1, 2, 3, 4 and 10 are actually SMTP. The rest of it is just text. Also note that the addresses in my sample message body (lines 6 and 7) are completely unrelated to the actual sender and recipients in lines 1, 2 and 3. What you specify to smtplib is the stuff in lines 1, 2, and 3. You have to create the stuff in lines 5 and beyond yourself. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From greg at cosc.canterbury.ac.nz Tue Mar 5 00:04:33 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 05 Mar 2002 18:04:33 +1300 Subject: Python song? (Re: Python isn't necessarily slow) References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> Message-ID: <3C8451E1.B2CD032@cosc.canterbury.ac.nz> Siegfried Gonzi wrote: > > Python isn't necessarily slow: That sounds like a great title for a Python song: "It Ain't Necessarily Slow!" Anyone want to contributes some lyrics? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From emile at fenx.com Fri Mar 1 14:05:41 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 1 Mar 2002 11:05:41 -0800 Subject: Minor, minor style question References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: claird at starbase.neosoft.com (Cameron Laird) writes: > Why would I prefer > string = "" > string = string + "abc " > string = string + "def " > string = string + "xyz" > over > string = "abc " + \ > "def " + \ > "xyz" > ? Isn't the question about line continuations? I don't use them (except on rare occasions), preferring to do something more like: string = ('abc' + 'def' + 'xzy') As to deprecation, a quick scan of the 2.2 standard library shows 42516 lines of which 249 used '\' style continuations, and other styles accounting for 958. (Note: I count a line as a sequence of source lines that together tokenize properly.) HTH, -- Emile van Sebille emile at fenx.com --------- From aahz at pythoncraft.com Sun Mar 31 18:36:31 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 18:36:31 -0500 Subject: Python/Linux References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: In article <0UMp8.42204$1f1.3348597 at e3500-atl2.usenetserver.com>, Robert Oschler wrote: > >I'd like to know which Web site development tool you like the best, because >I'm going to assume that you're using one that integrates well with Python. >Bear in mind that I'm one of those who like to be spoiled by a nice WYSIWIG >IDE if possible. Here's is the choice list I've built up after surfing much, >post much, and reading much replies: > >Quanta >Bluefish >PHP (Will I need to learn this or any other scripting lang if I'm using >Python for all my custom site stuff?) >Open Office's HTML tool >Delph/Kylix with perhaps kbmWABD (I'm Delphi prog'er too) >IBM's WebSphere home page builder (yes I know it cost a little) If you're using Python, go with either Zope or Quixote. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From bokr at oz.net Mon Mar 18 20:00:32 2002 From: bokr at oz.net (Bengt Richter) Date: 19 Mar 2002 01:00:32 GMT Subject: PIL Headaches: Advice Needed References: <4378fa6f.0203161652.7f28e23b@posting.google.com> <7652139e.0203170045.3c143995@posting.google.com> <4378fa6f.0203180858.4ad5f8b3@posting.google.com> Message-ID: On 18 Mar 2002 08:58:11 -0800, mnations at airmail.net (Marc) wrote: >This is the main error that I am seeing: > > >... >File "play2_copy.py", line 90, in createWidgets > im = "Image.open("cs.bmp") ^--?? I that from real code or what are you posting? >File "C:\Python22\lib\Image.py", line 960 in open >IOError: cannot identify image file > > >I have tried this with .gif, .jpg, and a couple of others and none of >the file types are recognized. Here is the code where the image is >imported: > >canvas = Canvas(goFrame, width=400, height=400) > im = Image.open("cs.bmp") > im.show() > canvas.pack() > Funny indentation. That's not how it really looks, right? >What am I doing wrong? > I doesn't look like you are posting actual code or verbatim lines from an interactive session. Since you can interactively walk through suspicious code one statement at a time and look at the results, why don't you do that? Then if it isn't obvious, post a verbatim copy of the failing interaction. You can copy from the windows console window by Alt-SpaceBar>E>K then select the text block with the mouse by pressing with the left mouse button with the cursor on the first character and keeping the left button pressed while moving the cursor to the bottom right to make a block that encloses what you want, and then pressing Enter. That will put it in the clipboard. Then paste into your news reader message editor. HTH! Regards, Bengt Richter From djc at object-craft.com.au Sun Mar 10 01:00:16 2002 From: djc at object-craft.com.au (Dave Cole) Date: 10 Mar 2002 17:00:16 +1100 Subject: Sybase module 0.33 released Message-ID: What is it: The Sybase module provides a Python interface to the Sybase relational database system. It supports all of the Python Database API, version 2.0 with extensions. Note: Since the 0.32 release I have come to the realisation that the Sybase dynamic SQL functionality is not nearly general enough to use for correct DB-API functionality. I have thrown up my hands and gone back to the drawing board with the high level Sybase.py module. There were four pre-releases of the module. The following is a summary of what has changed since 0.32: 1) Bulkcopy support has been temporarily removed from Sybase.py. The low level support is still present in the sybasect extension module. 2) Cursors are no longer using dynamic SQL so there will no longer be an extra result set which reported the status of the temporary stored procedure. This should remove some of the confusion behaviour of cursors. There should be fewer restrictions on the use of cursors. 3) The paramstyle is now 'named'. This means that you can now do this: c.execute("select * from titles where title like @arg", {'@arg': 'The %'}) 4) You can send arguments to Cursor.callproc() the old way: c.callproc('sp_help', ['titles']) or the new way: c.callproc('sp_help', {'@objname': 'titles'}) 5) Some internal cursor state constants were privatised (via leading '_'). Sadly no money was raised in the process and the conditions of the privatisation contract are commercial-in-confidence. 6) You can now compile the extension module without bulkcopy support by doing this: python setup.py build_ext -U WANT_BULKCOPY python setup.py install 7) The default build does not do threading any more so if you want threading enabled you will have to do this: python setup.py build_ext -D WANT_THREADS python setup.py install 8) There is some initial work to support FreeTDS. One of the problems with FreeTDS is that it does not support inline error handling. The callback error handling works well if you do not compile for threads support, but causes problems when compiled for threading. The problem occurs when the extension module releases the global interpreter lock when calling the Sybase CT library. A Python callback causes the interpreter to be reentered by the callback which leads to bad things when the following warning from the Python include file ceval.h is violated: WARNING: NEVER NEST CALLS TO Py_BEGIN_ALLOW_THREADS AND Py_END_ALLOW_THREADS!!! At the moment the module will compile for FreeTDS (at least it does on my machine) and some things do work. All you have to do is compile like this: python setup.py build_ext -D HAVE_FREETDS -U WANT_BULKCOPY python setup.py install There is no error handling and reporting for FreeTDS yet. 9) There is now some basic locale support in the sybasect extension module. I do not have a need for this so am really depending upon someone to try it and report problems: >>> from sybasect import * >>> status, ctx = cs_ctx_alloc() >>> status, loc = ctx.cs_loc_alloc() >>> loc.cs_locale(CS_GET, CS_SYB_LANG) (1, 'us_english') >>> loc.cs_dt_info(CS_GET, CS_DT_CONVFMT) (1, 3) >>> loc.cs_dt_info(CS_GET, CS_MONTH, 1) (1, 'February') >>> loc.cs_dt_info(CS_GET, CS_DATEORDER) (1, 'dmy') In theory you could do something like this: >>> import Sybase >>> from Sybase import _ctx, CS_SUCCEED, CS_SET, CS_SYB_LANG, CS_LOC_PROP >>> >>> status, locale = _ctx.cs_loc_alloc() >>> if status != CS_SUCCEED: ... raise 'cs_loc_alloc' ... >>> if locale.cs_locale(CS_SET, CS_SYB_LANG, 'french') != CS_SUCCEED: ... raise 'cs_locale CS_SYB_LANG' ... >>> db = Sybase.connect('SYBASE', 'sa', '', delay_connect = 1) >>> db.set_property(CS_LOC_PROP, locale) >>> db.connect() 10) There is some extra debugging detail for CS_DATAFMT which means you now get messages like this: >>> import Sybase >>> db = Sybase.connect('SYBASE', 'sa', '', 'pubs2') >>> db._conn.debug = 1 >>> c = db.cursor() ct_cmd_alloc(conn0, &cmd) -> CS_SUCCEED, cmd1 >>> c.callproc('sp_help', {'@objname': 'titles'}) ct_command(cmd1, CS_RPC_CMD, "sp_help", CS_NULLTERM, CS_UNUSED) -> CS_SUCCEED ct_param(cmd1, &databuf0->fmt=[name:"@objname" type:CS_CHAR_TYPE status:CS_INPUTVALUE format:CS_FMT_NULLTERM count:1 maxlength:7], databuf0->buff, 6, 0) -> CS_SUCCEED ct_send(cmd1) -> CS_SUCCEED ct_results(cmd1, &result) -> CS_SUCCEED, CS_ROW_RESULT ct_res_info(cmd1, CS_NUMDATA, &value, CS_UNUSED, NULL) -> CS_SUCCEED, 3 ct_describe(cmd1, 1, &fmt) -> CS_SUCCEED, datafmt0=[name:"Name" type:CS_CHAR_TYPE status:CS_UPDATABLE format:CS_FMT_UNUSED count:0 maxlength:30] ct_bind(cmd1, 1, &datafmt0->fmt=[name:"Name" type:CS_CHAR_TYPE status:CS_UPDATABLE format:CS_FMT_UNUSED count:1 maxlength:30], databuf1->buff, databuf1->copied, databuf1->indicator) -> CS_SUCCEED, databuf1 ct_describe(cmd1, 2, &fmt) -> CS_SUCCEED, datafmt1=[name:"Owner" type:CS_CHAR_TYPE status:48 format:CS_FMT_UNUSED count:0 maxlength:30] ct_bind(cmd1, 2, &datafmt1->fmt=[name:"Owner" type:CS_CHAR_TYPE status:48 format:CS_FMT_UNUSED count:1 maxlength:30], databuf2->buff, databuf2->copied, databuf2->indicator) -> CS_SUCCEED, databuf2 ct_describe(cmd1, 3, &fmt) -> CS_SUCCEED, datafmt2=[name:"Type" type:CS_CHAR_TYPE status:48 format:CS_FMT_UNUSED count:0 maxlength:22] ct_bind(cmd1, 3, &datafmt2->fmt=[name:"Type" type:CS_CHAR_TYPE status:48 format:CS_FMT_UNUSED count:1 maxlength:22], databuf3->buff, databuf3->copied, databuf3->indicator) -> CS_SUCCEED, databuf3 11) The was a minor change to setup.py for Linux. No longer looks for both libsybtcl and libtcl. Now just looks for libinsck. 12) The tar file now unpacks to a directory called sybase-. The module is available here: http://www.object-craft.com.au/projects/sybase/sybase-0.33.tar.gz The module home page is here: http://www.object-craft.com.au/projects/sybase/ - Dave -- http://www.object-craft.com.au From plopp at dummyaddress.doh Sun Mar 31 19:32:23 2002 From: plopp at dummyaddress.doh (Mikke M.) Date: Mon, 1 Apr 2002 02:32:23 +0200 Subject: Replace high-bit characters in file. References: Message-ID: > > # This is not tested, of course > > file_contents = open('dbasefile', 'rb').read() > > file_contents = unicode(file_contents, 'latin-1').encode('cp850') > > # file_contents is now a string containing the contents of the > > # file in cp850 format. You can write that string to a file, if you > > # want. > > open('dbasefile.out', 'wb').write(file_contents) > > > > Is that what you wanted? > > Probably not. If a (dBase) file is a binary thing, it might well be > that you modify the non-text parts of it. You really have to > understand the structure of the file, and apply the transformation > only to the text fragments. The routine above ran in to trouble, exiting with a "UnicodeError: charmap encoding error: character maps to ". I could solve that with a: file_contents = unicode(file_contents, 'latin-1').encode('cp850','replace') But that would, as you say, be dangerous as it may replace some of the non-text parts. However, it set me on the right track, so I edited the dbf-module I'm using (http://www.fiby.at/dbfpy/index.html) so that when it writes a text field to the dbase file, it is written in cp850. This way only the relevant part of the file is changed. Thanks guys!! /Mikke From martin at v.loewis.de Sun Mar 31 17:22:12 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Apr 2002 00:22:12 +0200 Subject: Replace high-bit characters in file. References: Message-ID: "Brian Quinlan" writes: > > I need a script that replaces national characters in a (dBase)file. > > > > The original file is encoded in Latin-1 but I need it to be in CP850 > > instead. > > # This is not tested, of course > file_contents = open('dbasefile', 'rb').read() > file_contents = unicode(file_contents, 'latin-1').encode('cp850') > # file_contents is now a string containing the contents of the > # file in cp850 format. You can write that string to a file, if you > # want. > open('dbasefile.out', 'wb').write(file_contents) > > Is that what you wanted? Probably not. If a (dBase) file is a binary thing, it might well be that you modify the non-text parts of it. You really have to understand the structure of the file, and apply the transformation only to the text fragments. In general, this is more complicated, as the size of the string may change under the conversion, but in this specific case, this can't happen. Regards, Martin From jimd at vega.starshine.org Wed Mar 27 06:40:52 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 27 Mar 2002 11:40:52 GMT Subject: seek in a file References: Message-ID: In article , Andreas Penzel wrote: > Hello NG! > How to jump to a specified line in a file which is read-opened? > With seek() I can jump to an exact position of the complete file in > "byte-steps". > Is seek able to jump to a line-number? > If not, what else can I do? >Thanks for help! >- Andreas This is going to sound harsh, but have you THOUGHT about what you're asking? Close your eyes and think about how the computer works. If a particular system *could* seek directly by line number how *could* that possibly work? What would the system have to *know* in order for that to work? You clearly know what seek() is (at least to some small degree). seek() is a method for Python file objects, it calls the fseek() C library function. lseek() and llseek() are Unix (and Linux) system calls (which are generally called by the C libraries on these systems). You've already seen that seek() provides an interface to randomly access any byte of a file. Perhaps you've read the man pages for fseek() and/or lseek() (if you're on a UNIX or UNIX-like system). But how could the OS seek to an arbitrary line number? I can only think of three ways that this could work: 1) Lines could be of fixed length 2) Files could be indexed with the offsets of each line terminator 3) The OS could search through the file searching for line terminators We know that the modern systems on which Python runs don't have fixed line length constraints. You might guess the files and filesystem metadata don't contain line terminator indexes (under UNIX, Linux, MacOS and the various MS Windows OSes, at least). So that pretty much leaves us with option #3. It turns out, of course, that the OS leaves option number three to "user space." In other words, they don't provide system calls or low level (core) functions to search through and count line terminators. Of course it's true that Python *could* provide such a convenience function. However, Python couldn't portably provide such a function that would be any more efficient than a short function that you can write for yourself. The easiest answer would be simply: f = open(yourfile,'r') lines = f.readlines() your_line = lines[n] f.close() ... where n was the line number you wanted (and yourfile is a variable containing the name of your target file, duh!). This could actually be shortened to: open(yourfile,'r').readlines()[n] (all on one statement line, creating an anonymous file object, reading ALL of its lines and returning the nth one; and implicitly closing the file as the reference count to the anonymous file goes to zero; because we didn't bind it to a variable name). That would be the easy and somewhat sloppy answer. It's probably fine for files that you can guarantee are small (that is relatively smaller than the memory available to your Python processes). Stylistically it's better to have three or four lines of code, the open and close, and the readlines() method. If you're going to access more than just one line, then you might as well store the whole readlines() list into a variable and use that repeatedly. If there's any chance that your file might exceed (or even approach) your available memory then you should limit the amount size of your readlines() method. Of course that means keeping track of a few more details: f.open(yourfile,'r') curLine = 0 while 1: lines = f.readlines(10000) if curLine < n: curLine += len(lines) else: break your_line = lines[ n - curLine ] f.close() That should create a loop that will terminate when the "lines" list contains line number n (your target line as in my previous examples). The tricky part is that the target line might end up anywhere in the "lines" buffer. So, at the end of the loop we have to find our target line by subtracting the count of all of the lines that we'd previously read (and implicitly discarded) to leave us with the remaining offset into our lines buffer. Naturally you could create your own convenience function that did all this for you. Of course this is predicated on the notion that your file contains lines of reasonable length. More precisely it could fail if you file contains any unreasonably long lines before your target line. In practice I wouldn't worry much about this. You could seek to the end of the file (f.seek(0,2)) and check the size using f.tell() and then just do a "readlines()" if that's less than some reasonable watermark (10 to 60 Mb on a late model low-end single-user PC). It is very unlikely that longest line length is going to be a problem. (If it was, then you could use f.read(x) where x was your buffer size, and then parse through that character/byte buffer to separate it into lines. At that point you'd be well advised to look at the StringIO module, which would allow you to treat strings as I/O streams and perform readlines() methods on strings as they are returned by a regular file objects read(x) method. As I say, it's unlikely that you have to go that far; I'm just mentioning these options to be a completist --- to explain how you could use Python's features to overcome all adversity, even the tragedy of insufficient memory and degenerate text file formatting). Given your original question and my (harsh) answer you might naturally ask why Python doesn't provide a convenience function to search for a arbitrary line by number. I hinted at part of the answer. The Python interpreter can't do this more efficiently than you can (in part, at least, because the most efficient way to accomplish this will depend on the amount of memory you have available, and the nature of the text file that you are searching). Another reason is that it is quite rare for people to need access to specific line (by number) in text files. If a given application requires such access then it would normally be accomplished by employing some form of indexing or by using fixed record lengths (which might still each be contained on a single line, but that is beside the point). So it seems pretty obvious why Python (and other programming languages) don't offer the function that you were asking for. From maxm at mxm.dk Wed Mar 13 03:38:48 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 08:38:48 +0000 Subject: Question about scientific calculations in Python References: Message-ID: <3C8F1018.2020407@mxm.dk> Jason Orendorff wrote: > I'm going to attempt to explain how you can do this with Numeric > Python, but you'll have to understand I have no clue what I'm > doing scientifically. Damn this is a good post! Even I can understand it, and see why Nummeric is smart. I have never looked at Nummeric as I believed that I had to do gene sequencing, neutron analysis or somesuch to find any use for it. But I could see right here in this short example that there was several functions that I have unnessacerilly written myself recently in my bussines-logic apps. So this just moved Nummeric several notches up on my to-learn list. Thanks and regards Max M From grante at visi.com Sun Mar 10 15:05:24 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 20:05:24 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> <1a9n8us1629mrvei40hdkuuerc1j6p318m@4ax.com> Message-ID: In article <1a9n8us1629mrvei40hdkuuerc1j6p318m at 4ax.com>, Courageous wrote: > >>Hmm, I don't really see the difference in practice between >>statically linking and installing a bunch of "private" DLLs >>that are only used by my app. In one case they're all in one >>file, in the other case they're in a bunch of files that have >>to be linked at run-time. In both cases none of the stuff is >>being shared with anybody else, so it's not like putting things >>in DLLs is saving any system resources -- though it perhaps >>make the packaging simpler. > > The case for the DLL is more obvious when what it is your > distributing is a family of applications which live together. > There may also be load time differences between an application > that is statically linked and one that is dynamically linked. > I seem to recall in my Unix days that using .so's dramatically > quickened load times. I would think that for an isolated app, .so's would slow down load times. With a statically linked program all you do is a single memmap() call (well, ignoring a few details). With .so's you've actually got to resolve all of the symbols and do the linking step (not required for statically linked images). Since you've got the same number of bytes to swap in off disk, that should be a wash. If, most of the .so's are already paged in because they're being used by other programs, then I can see that using .so's could speed things up since you don't have to wait for the VM system to page them into RAM. -- Grant Edwards grante Yow! Hello, GORRY-O!! I'm at a GENIUS from HARVARD!! visi.com From QnickQm at alum.mit.edu Thu Mar 14 17:44:33 2002 From: QnickQm at alum.mit.edu (Nick Mathewson) Date: Thu, 14 Mar 2002 22:44:33 GMT Subject: structseq and keywords? References: Message-ID: In article , Quinn Dunkan wrote: > On Wed, 13 Mar 2002 15:22:18 GMT, Nick Mathewson > wrote: >>I agree with this. One of the explicit design decisions was that >>since it's so easy to create a lookalike class in Python, there's not >>a lot of reason to expose structseq as a metatype. > > Ok, I guess what I really wanted was a DEFSTRUCT-like facility. I'll use > Michael's python StructSeq for that. I was originally going to do things > that way, but some demon whispered and I decided not to, for whatever > reason. Errr... quick question. If all you want is DEFSTRUCT, are you sure you need even a Python StructSeq? In other words, the point of my message was that, unless you're trying to support legacy code, it's probably adequate just make something that supports: x.a, x.b, x.c but not have to deal with the cruft structseq does to make sure that legacy code can still say: x[0], x[1], x[2] But-it's-your-program-not-mine-ly yrs, -- Nick Mathewson Remove Q's to respond. No spam. From erno-news at erno.iki.fi Sat Mar 16 21:17:24 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 17 Mar 2002 04:17:24 +0200 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: In article , grante at visi.com (Grant Edwards) writes: | In article , Donn Cave wrote: || C I/O basically sucks for this application. When you ask for 1024, || fread is bound to get that amount, just as it is if you ask for a || line via fgets ("readline".) If you omit the amount, you're asking || for all the data, won't return until the socket's other end closes. | Sorry, with all the talk of sockets, I was thinking of the recv() call. you can use os.read() to get s.recv() like functionality for any fd. -- erno From jolsen at mailme.dk Thu Mar 14 07:07:39 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 14 Mar 2002 04:07:39 -0800 Subject: XML-RPC Question Message-ID: Has anyone used the SimpleXMLRPCServer class? Setting up a server goes something like this: from SimpleXMLRPCServer import * class MyClass: def helloWorld(self): return "Hello World!" def echo(self, text): return text myob=MyClass() server=SimpleXMLRPCServer(("",50000)) server.register_function(myob.helloWorld) server.serve_forever() The server can now be accessed by a client, e.g.: import xmlrpclib srv=xmlrpclib.Server("http://localhost:50000") try: print srv.helloWorld() print srv.system.listMethods() except xmlrpclib.Error, v: print "Error", v The first srv.helloWorld() call succeeds, but srv.system.listMethods() results in a "Fault 1" exception "system.listMethods" is not supported... Is there something wrong here, or does SimpleXMLRPCServer, not support the listMethods() call? Cheers Jesper From sjmachin at lexicon.net Fri Mar 8 02:48:08 2002 From: sjmachin at lexicon.net (John Machin) Date: 7 Mar 2002 23:48:08 -0800 Subject: NoteTab Lite References: <3C882A0C.DB4B81B8@engcorp.com> Message-ID: Peter Hansen wrote in message news:<3C882A0C.DB4B81B8 at engcorp.com>... > William Kennedy wrote: > > > > Does anyone use the NoteTab series of editors for their coding, > > Is this anything like the NotePad series of editors? ;-) > > > if so do they have a Python library I can have. > > I confess to never having used the program, but I wonder if > your question is very clear. Does the editor use Python as > a scripting language, and you want a library of routines? > Or are you asking for a set of configuration options for > working with Python code? Or something else that isn't > clear (to me)? > > Hoping this isn't more obvious to others.... > > -Peter Not very obvious, but a few seconds googling brings up a hint that the OP is looking for a Python equivalent of the following: PerlDE.zip; 15 Jun 01; Jason Waugh Adds pretty much everything you would need to make NoteTab a Perl development environment -- autocomplete of common structures, context sensitive help for perl functions, help for perl packages, clips to interact with ActiveState's Perl Package Manager (PPM), and more. From mail at andreas-penzel.de Wed Mar 27 04:52:23 2002 From: mail at andreas-penzel.de (Andreas Penzel) Date: Wed, 27 Mar 2002 10:52:23 +0100 Subject: seek in a file References: Message-ID: "Steven Majewski" wrote: > Are the files too big to fit in memory ? the file is about 1 MB, i have to test out working > What do you want to do with the lines ? > ( I hope you weren't planning on trying to modify a line in a file: > because of the variable length on lines, if you don't write > exactly the same number of chars back, you will either overwite > the next line, or leave an extra partial line after your edited > line. Most text editors read the whole file into memory and then > write out a new file after it's modified in memory. ) In the file are barcodes of products, one per line. The program has to look if the scanned code from the barcode-scanner is identically with one in the file included. This is important because the barcode-scanner sometimes works not correct. All i need is an search-routine that compares the scanned code with the codes in the file. If there is an code, the programs waits for the next code. From sven.NO.axelsson at bokochSPAMwebb.se Wed Mar 13 07:21:21 2002 From: sven.NO.axelsson at bokochSPAMwebb.se (Sven Axelsson) Date: 13 Mar 2002 13:21:21 +0100 Subject: NormalDate 1.2 released References: Message-ID: Duncan Booth wrote in news:Xns91CF5F8D7A318duncanrcpcouk at 127.0.0.1: > sjmachin at lexicon.net (John Machin) wrote in > news:c76ff6fc.0203111907.12122c8b at posting.google.com: > >> There's even a story that the date of >> introduction in Sweden varied by parish! > > Dont forget that Sweden even had a 30th February one year! > Yes, the story is really strange. Sweden decided to make a gradual change from the Julian to the Gregorian calendar. By dropping every leap year from 1700 through 1740 the eleven superfluous days would be omitted and from 1 Mar 1740 they would be in sync with the Gregorian calendar. (But in the meantime they would be in sync with nobody!) So 1700 (which should have been a leap year in the Julian calendar) was not a leap year in Sweden. However, by mistake 1704 and 1708 became leap years. This left Sweden out of synchronisation with both the Julian and the Gregorian world, so they decided to go back to the Julian calendar. In order to do this, they inserted an extra day in 1712, making that year a double leap year! So in 1712, February had 30 days in Sweden. Later, in 1753, Sweden changed to the Gregorian calendar by dropping 11 days like everyone else. -- Sven Axelsson, Bok & webb sven.NO.axelsson at bokochSPAMwebb.se From gimbo at ftech.net Mon Mar 25 09:03:52 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 25 Mar 2002 14:03:52 +0000 Subject: Indentation problem In-Reply-To: <3C9F2341.1000802@udcast.com> References: <3C9F2341.1000802@udcast.com> Message-ID: <20020325140352.GA22091@andy.tynant.ftech.net> On Mon, Mar 25, 2002 at 02:16:49PM +0100, Gilles Diribarne wrote: > I've some problem with identing code. I'm allright with the example. > But, I think it's important to have an "end" building block like "!:" > > What do you think about that? I think you're wrong to think that it's important to have such a construct. The reasons why I think that are: * It's clearly not necessary for the language to "work" (otherwise it wouldn't). By that I mean we can write parsers, compilers, etc. * It's also in fact beneficial for a number of reasons, to do with readability, umambiguity, and elimination of religious wars, as discussed in an FAQ which I will link to later... * I haven't seen any arguments to convince me otherwise (including yours, which I'll examine shortly). > Why I would like to put this in the code? > 1/ Because it's almost impossible to paste python code with ident = n > spaces to another code with indent = m spaces Is this a problem you've come across much? Or just a hypothetical situation? I don't think it _is_ impossible, it just might be slightly hard work. If the original programmers paid attention to the style guide, this wouldn't be a problem of course. And if you're dealing with enough code for this to be problematic, I think you need to ask yourself if copy-and-paste is the right thing to do... > This kind of examples occurs more and more and you can indent the code > by hand when it's 10 lines of codes, but not 1000 code lines. > It prevents the re-use of code pieces. Only if copy-and-paste is the only way to re-use code pieces, which it isn't. I would hope that 1000 lines of code would be structured into functions, classes, maybe even modules, in which case you probably don't need to edit the code at all. Just import the module and use what you need. I'm not saying that you should never copy-and-paste, though. Sometimes, yes, it's the right thing to do. In which case... > 2/ Programmers wants independence: some wants to manage building blocks > with spaces, other with tabs, some wants length = 4 with tabs. > I would like to use my own programming style! But, my code risks to be > not supported by others. There's a python style guide here: http://python.sourceforge.net/peps/pep-0008.html If you care about your code being supported by others, I highly recommend you read it and apply it. It happens to recommend that you use 4 spaces, and no tabs whatsoever. Emacs mode in python takes care of this very nicely. You can't say in one breath that you want independence to write code in any style you like, and then complain in the next breath that other programmers, whose style differs, don't want to read it (and thus don't want to use it because they don't understand it or trust it). This is why it's _good_ that python doesn't use delimiters: we don't have religious wars over where to put the braces. OK, so we might argue over how many spaces to use, but a) you get that argument in languages with delimiters _too_, and b) Guido says 4, so use 4. ;-) > EXAMPLE: > > pythona.py: > def func(): > a = 1 > if a == 1: > a ==2 > > pythonb.py > def func2(): > a = 2 > if a == 2: > print "Yeah!" > > You cannot merge correctly or tell me how to do this ? Easy. Let's say we want to keep 4 spaces of indentation, as Guido recommends in the style guide - so we're going to change func() and keep func2() as it is. In our favourite editor we mark a region covering all of func(), and use search-and-replace to turn all occurrences of " " (2 spaces) into " " (4 spaces). Tah-dah! If the code contains any strings which might have multiple spaces in them, we'll need to be careful, but I think we can handle that. Of course, this won't work if func() isn't self-consistent about its indentation, but frankly I don't think func() deserves to run if that's the case. I don't know if python will let it or not, because I've never tried. By the way, I _think_ python-mode in emacs actually _is_ capable of changing an entire document's indentation from n-spaces to m-spaces automatically and intelligently, simply by changing a variable - but I might be wrong. > 3/ A large number of programming language use this. C, PERL, Ruby, ... > Why not Python? It's called "progress". http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.002.htp -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From vinjhodge at techemail.com Mon Mar 18 00:05:54 2002 From: vinjhodge at techemail.com (Vincent) Date: Mon, 18 Mar 2002 00:05:54 Subject: WORLDS #1 HOME BASED BUSINESS OPPORTUNITY!! Message-ID: Hi, My name is Vincent. I am an ordinary man living in the UK who has learned how to make a living on the Internet working from home. I am willing to teach you to do the same via simple, step by step, easy to follow lessons so you can be successful to, as quickly and painlessly as possible. I will work closely with you and teach you everything I know for free. I will also provide you with the free tools, resources and software so you can achieve this success in an efficient and easy manner. It is an international business with over 5.5 million entrepreneurs from more than 200 countries worldwide becoming affiliates; many are earning in excess of $100,000+ a month. It is officially the largest and fastest growing Internet Marketing Company in the world. You don't have to be a computer whiz or genius to learn to earn on the Internet. You just need a dream and be willing to give some time to learning and implementing the things I teach you. You won't get rich quick but you will be able to build a good solid income, an income that will depend solely on you and whether or not you are willing to learn. If you are willing to learn and want to get to know and work with a real person, then contact me. Why would I be willing to help you for Free? The company I am affiliated with pay me commissions on how well I do at promoting their products/services. If I teach you to do the same they pay me commissions on how well you do at promoting their products and services also. So my goal will be to teach you so well that you are making money and I am making money. The great thing about this business is that if you don't make money then I don't make any money. To build a profitable online business you just have to know how and where to advertise these products/services. I will show you some tried and tested advertising techniques that have been the backbone behind my success over the last yea or so. You can also have a fully working registered copy of Desktop Server 2000, Atomic Harvester 3, List Manager, Text Bomber 2000 and Post News 2000 for free, worth well over $1000. These 5 incredible advertising programs are all you will need to start and build any online business. If you are interested in learning more or to receive your free software please send a blank E mail with ?Tell Me More? or ?Software? written in the subject line and mail it to freeeleads at yahoo.co.uk I look forward to hearing back from you soon and hope to be working closely with you in the near future. I am at your service! Vincent This is a onetime mailing, you will not receive any further E-mail's from me and you do not have to remove yourself from any list. Your E-mail address came with a bulk E-mail list that I brought from an online provider. They told me in good faith that you had agreed to receive information on lucrative work at home business opportunities. If offended in my mailing please contact the list provider at leads4sale2001 at yahoo.co.uk From andrewm at object-craft.com.au Sun Mar 24 23:23:31 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Mon, 25 Mar 2002 15:23:31 +1100 Subject: Debugging on windows via print statements -- reliable? In-Reply-To: Your message of "Sun, 24 Mar 2002 19:43:36 -0800." Message-ID: <20020325042331.0188B38F4C@coffee.object-craft.com.au> >Is there something on Windows (Win2K, to be exact) that I need to do to make >sure that print statements are actually output as soon as the statement is >executed. You could try sys.stdout.flush() after each print - stdio might be buffering the output in block-sized chunks. -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From jim.jacobs at jacobshome.com Sat Mar 9 19:54:25 2002 From: jim.jacobs at jacobshome.com (Jim Jacobs) Date: Sat, 9 Mar 2002 19:54:25 -0500 Subject: Tkinter error References: Message-ID: The problem appears to be that I define enviroment variables for TK_LIBRARY and TCL_LIBRARY. Thanks, Jim "Martin v. Loewis" wrote in message news:m3bsdx9yjs.fsf at mira.informatik.hu-berlin.de... > "Jim Jacobs" writes: > > > "self.tk = _tkinter.crate(screenName, baseName, className) > > TclError: Can't find a usuable init.tcl in the following directories: [list > > of directories]" > > > > Among the directories listed is the directory in which init.tcl is located. > > What gives? > > It wasn't usable :-) I have no clue why this would happen, but I know > how to find out: use the source. > > Regards, > Martin From DavidA at ActiveState.com Mon Mar 11 13:14:52 2002 From: DavidA at ActiveState.com (David Ascher) Date: Mon, 11 Mar 2002 10:14:52 -0800 Subject: Learning Python 2nd Edition??? References: <1001ff04.0203101710.46f27d85@posting.google.com> Message-ID: <3C8CF41C.1DB4987F@activestate.com> Bob wrote: > > Is there an "updated" Learning Python book in the works? Yes. Mark Lutz and I have started to work on it. There's no precise (or even vague) date for it hitting the shelves though (so much has changed!). -- David Ascher From erno-news at erno.iki.fi Tue Mar 12 09:17:16 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 12 Mar 2002 16:17:16 +0200 Subject: Raw Ethernet under Win32? References: Message-ID: In article , grante at visi.com (Grant Edwards) writes: | Is there any way to do raw Ethernet packets under Win32 Python? i've heard there's a windows port of libpcap, and there's pylibpcap. might work. -- erno From skip at pobox.com Wed Mar 6 16:18:10 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 15:18:10 -0600 Subject: The language vs. the environment Message-ID: <15494.34706.724985.628479@beluga.mojam.com> There has been a huge amount of recent PEP activity related to further enhancements to the language. I think in general that if more of this energy was directed at the overall environment (library, support tools, installers, documentation, etc) we'd be better off in the long run. For the most part, I think the proposals currently on the table, while some are very nice, aren't going to make a significant change in programmer productivity, code maintainability or accessibility of the language by new users. I understand the lure. I have succumbed to the lure myself on many occasions. It's cool to participate in a bit of language design, most of us are pretty good programmers and we can project how we might use a particular feature. As Andrew Kuchling said on his page about the Frank Willison award he received last month: Thanks to Guido, first, for writing a language that's both fun to hack in, and fun to hack on. Still, even though Andrew is clearly a damn talented programmer, if you think about what he's best known for in the Python community, it's likely his "What's New" documents, e.g.: http://www.amk.ca/python/2.2/ If you're looking for something to munch on, here are some suggestions, not all of which require that you write code: * breathe some life into the catalog-sig: http://www.python.org/sigs/catalog-sig/ * find a Python bug without a proposed fix and write one (there are currently between 250 and 300 open bug reports): http://sourceforge.net/tracker/?group_id=5470&atid=105470 * document an undocumented module from the standard library: http://www.python.org/doc/current/lib/undoc.html * write a HOWTO (another of Andrew's little sideline projects!) about your little niche of Python expertise: http://py-howto.sourceforge.net/ -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From mcherm at destiny.com Wed Mar 13 16:33:14 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 13 Mar 2002 16:33:14 -0500 Subject: 15 minute presentation on python? Message-ID: <3C8FC59A.407@destiny.com> Ian Parker writes: > I wow'd my audience by using Python with the win32 extensions to show > simple it was to load data (proxy server log files) into MS Excel. [...] Congradulations! Glad it went so well. By the way, I'm doing a brief Python presentation in a couple of weeks... would you be interested in sharing your presentation? -- Michael Chermside mcherm at destiny.com From akuchlin at ute.mems-exchange.org Thu Mar 21 13:00:41 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 21 Mar 2002 18:00:41 GMT Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: In article , Thomas Heller wrote: > I've thought a little bit more about this. IMO PEP 262 (database of > installed packages) should be implemented, so that the database > is updated by distutil's install command - then we can write a > robust uninstall. PEP 262 still has many, *many* XXX comments marking potential issues that need to be cleared up before it can be implemented. Most aren't particulaly complicated, just cases where I'm not sure if a feature is needed or if it's just extra fluff. Once those uncertainties are cleaned up, I'll try to get it implemented for the Python 2.3 time frame. --amk (www.amk.ca) #1 rule of the intergalactic explorer, Doctor: if you hear somebody talking about "good vibes" and "letting it all hang out", run a mile. -- Captain Cook, in "The Greatest Show in the Galaxy" From geoff at gerrietts.net Wed Mar 6 16:06:15 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Wed, 6 Mar 2002 13:06:15 -0800 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: References: Message-ID: <20020306210615.GF20722@isis.gerrietts.net> Quoting Christopher Encapera (ChrisE at lantech.com): > [...] > A child, or adult, is inherently flexible when it comes to syntax, > but a computer is (inherently) not. > [...] > Thus, the need for jumping right into syntax immediately (if you > want to produce anything even remotely meaningful) A point well taken, but also note that when we set out to learn a new language, the most effective teaching methodologies rely on pointing out the patterns in that language very early on: you learn to conjugate verbs, learn proper forms of address, etc. Later, you learn more complicated variations on the patterns (past tense, past perfect tense, possessives, prepositional phrases, etc). Whereas the five-year-old will learn to speak by absorbing the language "in the wild", the student will try to apprehend it by absorbing the patterns, then learning the limits of those patterns through application and introduction of new patterns. These techniques are naturally more successful when the student is immersed in an environment rich with opportunity to encounter those limits. > Also concerning logic, I think it would be (perhaps) more accurate > to say that people think (and solve most of their problems) at a > higher level of abstraction - more in the realm of "meanings" and > "relationships" where many different kinds of knowledge and > inter-connectedness come into play. I think you're right. I'm trying to oversimplify intuition, or maybe oversimplify what we're really talking about by calling it intuition. Logic is both less subjective and less forgiving, and it operates at a much more concrete level of thought. --G. -- Geoff Gerrietts "I have read your book and much like it." --Moses Hadas From maxm at mxm.dk Thu Mar 21 03:55:21 2002 From: maxm at mxm.dk (Max M) Date: Thu, 21 Mar 2002 08:55:21 +0000 Subject: how to read full file into buff for re using? References: Message-ID: <3C999FF9.2010608@mxm.dk> Zoom Quiet wrote: > i'm chinese python fresh men; help please! > how to read full file into buff for re object using? > such as: > re.sub() f = open('file.txt', 'r') content = f.read() f.close() More info her: http://www.python.org/doc/current/tut/node9.html#SECTION009200000000000000000 > /======================\ > | Time is unimportant; > | only life important! > \======================/ But perhaps you should spend your time searching the web then ;-) http://www.google.com/search?hl=en&q=python+opening+file+read+contents regards Max M From just at xs4all.nl Sun Mar 3 03:54:20 2002 From: just at xs4all.nl (Just van Rossum) Date: Sun, 03 Mar 2002 09:54:20 +0100 Subject: PEP 234 little bug? References: <3c817238@nntp.server.uni-frankfurt.de> <3C817FC1.A155DBAB@earthlink.net> Message-ID: In article <3C817FC1.A155DBAB at earthlink.net>, Hans Nowak wrote: > Michael 'Mickey' Lauer wrote: > > > > Just read through some of the already implemented PEPs. > > > > PEP 234 (iterators) states: > > > > > - It has been proposed that a file object should be its own > > > iterator, with a next() method returning the next line. This > > > has certain advantages, and makes it even clearer that this > > > iterator is destructive. The disadvantage is that this would > > > make it even more painful to implement the "sticky > > > StopIteration" feature proposed in the previous bullet. > > > > > > Resolution: this has been implemented. > > > > I can't see a next() in a file object. Shouldn't it be > > "Resolution: this has not been implemented." ? > > Hm, I don't think so. I think it does not say that the *file* > object should have a next() method... rather, it says that > it's its own iterator, and the iterator has the next() > method. Maybe the wording could have been a bit more careful, > but essentially it's true what is says. And iterating over > files has indeed been implemented in 2.2. Just yesterday I've filed a bug about the current behavior that is caused by the fact that the file object is *not* its own iterator: http://sourceforge.net/tracker/?func=detail&aid=524804&group_id=5470&atid =105470 Just From matthias_j at lycos.com Sun Mar 3 10:26:29 2002 From: matthias_j at lycos.com (Matthias Janes) Date: 3 Mar 2002 07:26:29 -0800 Subject: Can't seem to get it right: Win NT registry save and load References: <0aag8.8540$va.1091@nwrddc02.gnilink.net> Message-ID: Thank's alot - you pushed me in the right way - I actually do not realy need to save whole hiv but just a few keys. Thanks - I thought this could work somehow like regedit's export import feature but properly it's not realy what I need. From kosh at aesaeion.com Wed Mar 20 09:56:05 2002 From: kosh at aesaeion.com (kosh at aesaeion.com) Date: Wed, 20 Mar 2002 07:56:05 -0700 (MST) Subject: Java and Python In-Reply-To: <3C981961.9F5E5383@engcorp.com> Message-ID: On Wed, 20 Mar 2002, Peter Hansen wrote: > Ahmed Moustafa wrote: > > Way, way down the list of things I look for in a resume > is the programming languages a candidate has. Not entirely > unimportant, but useful only taken as a whole. I don't care > whether somebody knows Python, and have found and hired > only one such programmer yet (and not because he knew Python). > The others had a variety of backgrounds including Java, > C++, Delphi, VB, C, BASIC, assembly of various kinds, > and so forth. Those with only a single language, or > maybe two, probably didn't get hired. Those with a dozen > were more able to demonstrate their flexibility to me. The problem I have with someone learning lots of languages is that most of what I have seen is that they never go beyond a surface level understanding of the language. So you end up seeing people that can essentially write C in any language or java etc. However in order to be really productive you need to know a language and know it very well. I would rather see someone that can demonstrate higher level mastery with one language then a surface level with many. You can't get to more advanced features until you understand all of the basic features. However once you learn those features you are in a better position to apply them in another language. From greg at cosc.canterbury.ac.nz Wed Mar 6 22:00:26 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Mar 2002 16:00:26 +1300 Subject: PEP 284, Integer for-loops References: Message-ID: <3C86D7CA.F53189AE@cosc.canterbury.ac.nz> Steve Lamb wrote: > > On Wed, 06 Mar 2002 16:57:03 -0800, David Eppstein > wrote: > > Did you try running range(n-1,0)? What list did it give you? > > >>> range(-10,0) > >>> [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1] > > And? How does this prove your point The point was, I think, that >>> n = 10 >>> range(n-1,-1,-1) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] but >>> foo = range(n-1,0) >>> foo.reverse() >>> foo [] > In your notation how would you do the following? > > for x in range(n-1,-1,-2): for 0 <= i < n/2: x = 2*i + 1 ... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From aahz at pythoncraft.com Mon Mar 25 10:05:37 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Mar 2002 10:05:37 -0500 Subject: Debugging on windows via print statements -- reliable? References: Message-ID: In article , Nick Arnett wrote: > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen >> >> By the way, how can Python code get "stuck"? Is it a logic flaw, >> or are you talking about the kind of "stuck" that used to happen, >> in the "old days", when we were always writing code in languages >> which would actually crash the computer? > >I'm using these vague adjectives because I can't tell what is >happening. Somewhere in the midst of retrieving pages with urllib and >parsing them with sgmllib, everything seems to stop. Ah. You're probably getting stuck in urllib. You need to use http://www.timo-tasi.org/python/timeoutsocket.py -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From martin.franklin at westerngeco.com Wed Mar 13 04:12:01 2002 From: martin.franklin at westerngeco.com (Martin Franklin) Date: Wed, 13 Mar 2002 09:12:01 +0000 Subject: Scrolling line number Tkinter References: <3C8E84AA.4070306@club-internet.fr> Message-ID: Fabien Henon wrote: > I am currently writing a text editor for POV-RAY under Windows using > Tkinter. It should be working as well with linux and Mac. > > To display the line numbers, I use a scrolling column at the left of the > editor with a text box. Can you please explain what a scrollng column is? Perhaps if you post some code we could help some more. > > I also linked the main text editor with a scroll. > > My problem is that the text editor is well linked to the scroll, but the > line numbers do not move when I use the arrow cursors. > > Thanks for any help > > Fabien It sounds like you need to link both the scrolled column and text box to the same scrollbar.... From philh at comuno.freeserve.co.uk Sat Mar 30 18:38:19 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 23:38:19 +0000 Subject: PEP 285: Adding a bool type References: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 30 Mar 2002 20:05:35 +0000, phil hunt wrote: >On 30 Mar 2002 01:36:43 -0800, Paul Rubin wrote: >>Guido van Rossum writes: >>> Dear reviewers: >>> >>> I'm particularly interested in hearing your opinion about the >>> following three issues: >>> >>> 1) Should this PEP be accepted at all. >> >>I don't see much need for it. > >Nor do I. Python works OK as it is, asnd this proposal adds nothing >new semantically (because bool must act the similarly to int, for >compatibility). The only advantage I see is that code is slightly >more self-documenting, e.g.: > > return True > >instead of: > > return 1 I've gone through some of my herbivore code, looking to see where I've used 0 or 1 as a boolean. Example 1: debug = 0 # debugging this module? Frankly, if that is unclear to anyone, they are not cut out to be a programmer. Bear in mind that most non-programmers are aware of the 0/1 paradigm for boolean values: it appears on much electrical equipment. Example 2: CONFIG_DEFAULT_VALUES = { 'dest': "file:mess_out_%(ix)s", 'log': 1, 'logItems': ["i", "ip", "o", "op", "cmd", "comment"], 'logMessItems': ["From", "To", "Cc", "Bcc", "Subject", "Message-Id", "X-Herbivore"], } Here, the 1 value for 'log' means turn on logging, so could naturally be replaced by a boolean. These are default values for the config file; in the file they will look like: log = 1 The file is executable Python code, and so could naturally be changed to: log = True if it is unclear. But (1) it isn't unclear, since the default config file contains a comment before each config variable, saying what it means -- and anyway there will be a GUI config tool for Herbivore, and (2) Herbivore, by design is required to be easily installed; specifically, the user shouldn't have to upgrade to a newer version of Python, so I wouldn't be able to use booleans for a long time after they'd been added. So there would be no benefit for me at least in adding this feature. Now we turn to the other side of the coin: would this proposal cause problems. Contrary to my initial post, I see one place where it might well do. Consider a program that communicates with instances of the same program on other machines by way of Python data expressed as repr() strings. Each instance of this program will work on its own. Each instance will continue to work if Python on that machine is upgraded to a post-boolean version. But the upgraded and unupgraded will no longer be able to talk to each other if there are any boolean values being passed around. This could well be a hard-to-track-down error, since both versions will continue to work perfectly well on their own. So because there seem to be few advantages, potential disadvantages, and because the proposal adds unnecessary complexity to the Python language in return for some superfluous syntactic sugar, I dislike this proposal. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From tchur at optushome.com.au Fri Mar 15 17:43:45 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 16 Mar 2002 09:43:45 +1100 Subject: basic statistics in python References: Message-ID: <3C927921.27E772D3@optushome.com.au> dsavitsk wrote: > > this is really embarassing :-) > > >>> import win32com.client > >>> xl = win32com.client.Dispatch('Excel.Application') > >>> xl.WorksheetFunction.StDev(1,1,1,3,3,45,3,2,1,1,2,3,2,1) > 11.565627361442019 > >>> xl.WorksheetFunction.Pearson((1,4,3,2,5),(5,3,2,5,4)) > -0.48507125007266594 Hmm, how about these legacy-free solutions... Using Walter Moreira's RPy module ( http://rpy.sourceforge.net ) and R ( http://www.r-project.org ): >>> from rpy import * >>> r.var((1,1,1,3,3,45,3,2,1,1,2,3,2,1)) ** 0.5 11.565627361442019 >>> r.cor((1,4,3,2,5),(5,3,2,5,4)) -0.48507125007266594 Or using Gary Strangman's stats.py module ( http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html ): >>> from stats import * >>> stdev((1,1,1,3,3,45,3,2,1,1,2,3,2,1)) 11.565627361442017 >>> pearsonr((1,4,3,2,5),(5,3,2,5,4)) (-0.48507125007266594, 0.40754435760237651) Note that stats.py also returns the 2-tailed p-value as well (which can also easily be obtained from R via RPy). Tim C From pearu at cens.ioc.ee Sun Mar 31 05:17:29 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sun, 31 Mar 2002 12:17:29 +0200 Subject: Most important extensions? In-Reply-To: References: Message-ID: SWIG, f2py, wxPython On 30 Mar 2002, Aahz wrote: > I'm teaching Python for [Perl] Programmers at OSCON this July. I've > already decided to mention mxODBC, NumPy, and PIL, plus PythonPoint (aka > ReportLab) gets a mention on my title page. I'd like this group to vote > on the most important extensions for me to add to this list. Please vote > for no more than three. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Why is this newsgroup different from all other newsgroups? > From fredrik at pythonware.com Wed Mar 20 15:55:10 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 20 Mar 2002 20:55:10 GMT Subject: Unicode problem References: <3c98f206.24909027@news.tiscali.no> Message-ID: gargravarr at whoever.com wrote: > I have a problem with Unicode strings, the error I get is: > UnicodeError: ASCII encoding error: ordinal not in range(128) > > It is caused by > body.write('

%s

\n' % i.firstChild.data) > > Where body is a StringIO object, and i is a xml.dom.minidom object. > The characters it reacts to is the 3 Norwegian 'extra' ones: ?, ?, ? > (if you can see them) if you don't tell Python what 8-bit encoding you want to use for a Unicode string, Python will assume ASCII. to convert to an 8-bit string with a known encoding, use the encode method: s = i.firstChild.data.encode("iso-8859-1") you should probably escape < > & too; consider using something like: from cgi import escape def encode(s): if not s: return "" return escape(s.encode("iso-8859-1")) body.write('

%s

\n' % encode(i.firstChild.data)) From ffjhenon at club-internet.fr Sun Mar 17 16:51:25 2002 From: ffjhenon at club-internet.fr (Fabien Henon) Date: Sun, 17 Mar 2002 22:51:25 +0100 Subject: Linux endline References: <3C932C41.2974C1DA@club-internet.fr> Message-ID: <3C950FDD.4080005@club-internet.fr> Fredrik Lundh wrote: > Fabien H?non wrote: > >>1? When I use it under Linux I would like to get rid of the \r which >>appears at the end of each line. ( I know there is a difference of >>endline between Windows, Mac and Linux). >> > > how about > > if line.endswith("\r\n"): > # deal with DOS file ending > line = line[:-2] + "\n" > self.text.insert(END, line) > > >>3? Is there a way to fire up an external application (like POV or a >>modeler) in background >> > > look up "os.spawn" in the library reference. > > > > > > Thanks I'll give it a try. Fabien From tbabbitt at commspeed.net Thu Mar 7 11:04:45 2002 From: tbabbitt at commspeed.net (Tom Babbitt) Date: Thu, 7 Mar 2002 09:04:45 -0700 Subject: Python and computer graphics References: <3C8785EA.5010509@student.kun.nl> Message-ID: <1015517388.720858@news.commspeed.net> "husam" wrote in message news:3C8785EA.5010509 at student.kun.nl... > hi, > can anybody points me to usefull resources (books, urls) about using > python for computer graphics that help for building skills in this > subject from scrash? > > thanks in advance > A long time ago I read a book simply titled 3D computer graphics, I think it was by some of the folks at pixar. My philosophy is not to spend too much time at the bottom but go right to the top, check out http://www.linmpi.mpg.de/dislin/ http://mayavi.sourceforge.net//index.html http://pygame.seul.org/ Tom Babbitt From heiko.wolf at dlr.de Tue Mar 19 08:47:53 2002 From: heiko.wolf at dlr.de (Heiko Wolf) Date: 19 Mar 2002 05:47:53 -0800 Subject: MPI changes the command line arguments Message-ID: Hi there, I.ve got a Python script that should run parallel. So I access MPI-funtions to put it on different processors. That works fine until commandline arguments come into play... I want to pass a script file that should be read. For the first process, this works fine, the script file is simply sys.argv[1]. But from the second process on, the name of the script file is not in sys.argv anymore... MPICH just changes the commandline parameters... But there is something even more astonishing: As I pass the commandline arguments to the C-function MPI_init() and do a printf() there, everything is in its right order, the name of the script_file is just argv[1]!!! Has anyone experienced similar problems? What would be a solution for this? Thanks, Heiko From db3l at fitlinxx.com Fri Mar 1 13:59:55 2002 From: db3l at fitlinxx.com (David Bolen) Date: 01 Mar 2002 13:59:55 -0500 Subject: Can somebody kill getpathp for me? References: Message-ID: "Chris Gonnerman" writes: > No, but win32all does (for instance). The point is, I never want my > CD-based runtime to ever see the end user's install, if he/she has one. > The programs I want to run from CD may get psycho if the local version > has conflicting libraries, and in fact I have already encountered this > problem (so it's not just theoretical). You may not technically need to package things up, but if you use Gordon McMillan's installer (or py2exe as well as I believe), they will lock down your sys.path to the local installation. So you could build an image for your application using one of those tools, and execute that from the CD. Of course, this may not be perfect if you want the CD to work on both Windows and Unix, but it would avoid needing to rebuild a different python front-end for Windows. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From tim.one at comcast.net Fri Mar 22 16:51:30 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 22 Mar 2002 16:51:30 -0500 Subject: PySequence_Check is always true on instances? In-Reply-To: <20020322182402.B7591@casa.parque> Message-ID: [Walter Moreira] > Hi. If I define a simple class > > >>> class eggs: > ... pass > >>> a = eggs() > > and I call PySequence_Check on the instance 'a', at C level, it > returns 1. Right. This is an unfortunate consequence of the "type/class split" before 2.2: all classic classes fill in all type method slots "just in case", so pass all tests that just look for the existence of non-NULL method slots: int PySequence_Check(PyObject *s) { return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } > If the class is a new style class: > > >>> class eggs(object): > ... pass > >>> b = eggs() > > then PySequence_Check on 'b' returns 0. I proved this on Python > 2.2 and 2.1 (couldn't download 2.2.1 yet). That won't change in 2.2.1. All old-style instances return true for these; whether a new-style instance returns true depends on whether it inherits or directly defines the type slots being examined. > Is this a bug? Not in the sense you're hoping for . > If it is not a bug, which is the standard way to check that an > object is sequence, in C? There isn't one: it depends on exactly what *you* mean by "a sequence". It's a fuzzy concept in Python, and you'll find that PySequence_Check() is rarely used in the core. In most cases for 2.2, it's not a question worth even trying to answer: most "sequence contexts" in 2.2 were generalized to allow any iterable object, and the core usually determines whether an object is iterable by seeing whether PyObject_GetIter() returns NULL or not. From mikeb at mitre.org Tue Mar 19 10:35:36 2002 From: mikeb at mitre.org (Mike Brenner) Date: Tue, 19 Mar 2002 10:35:36 -0500 Subject: Book Draft Available: Text Processing in Python Message-ID: <3C975AC8.E9F02553@mitre.org> David Mertz > ... I am working on a book called _Text Processing in Python_. ... David, you might consider producing a text_tools.py library: a complete "textual bag of tricks" that you could give to the Python community. The book would then serve as the documentation for that library. If you decide against this, a second possibility would be for you to focus that book to a user who will develop that library. In that case the book could set the direction and give the basic tools needed to produce the tools. I will not at this time give a list of what I see as missing, because most of the chapters are not filled in, but it you take either of the above approaches, I will be happy to share what I feel would complete either the bag of tricks or the direction for developing the bag of tricks, when you are close to completing most of the chapters. From tim.one at comcast.net Sat Mar 2 00:58:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 02 Mar 2002 00:58:18 -0500 Subject: Use of select.select In-Reply-To: <98a8b53e.0203011656.7aaad470@posting.google.com> Message-ID: [MShyam] > Our product embeds python in C++ and in our > py methods, we use select.select in several > places. When purifying the executable, we > find that when select.select(...) is executed, > we find several BSWs, BSRs, IPWs and IPRs > (beyond stack writes/reads, invalid pointer > writes/reads). Has such a problem been reported? > What's the fix? We're using python 1.5.2. I strongly advise you try a more recent release (like 2.1.2). 1.5.2 is nearly 3 years old, never had a bugfix release, and nobody is likely to remember 1.5.2 details accurately anymore. More recent versions have also been run under Insure by other people. Short of that, I expect you won't get much help. You can view the CVS history of selectmodule.c online at then navigate to Modules and then to selectmodule.c. Revision 2.28 was released in 1.5.2; it's currently at revision 2.60. From neal at metaslash.com Mon Mar 18 18:36:51 2002 From: neal at metaslash.com (Neal Norwitz) Date: Mon, 18 Mar 2002 18:36:51 -0500 Subject: Generating getter methods with exec References: <3C964E1A.84D5A26B@ndh.net> <3C96569F.8E76FA6E@metaslash.com> <3C966323.A522D680@ndh.net> Message-ID: <3C967A13.C6074484@metaslash.com> Stefan Schwarzer wrote: > > Hello Neal > > thank you for your answer. :) > > Neal Norwitz wrote: > > You don't need to generate code. This should do what you want: > > > > class GetterTest: > > def __init__(self): > > self._dict = {'key1': 'one', > > 'key2': 'two', > > 'key3': 'three'} > > > > def __getattr__(self, attr): > > try: > > return self._dict[attr] > > except KeyError: > > raise AttributeError, "getting attribute '%s'" % attr > > > > >>> g = GetterTest() > > >>> g.key1 > > 'one' > > >>> g.key2 > > 'two' > > >>> g.key3 > > 'three' > > >>> g.key4 > > Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 8, in __getattr__ > > AttributeError: getting attribute 'key4' > > Yes, that's the straightforward solution. :-) > > On the other hand, what I posted was a simplified example. Finally, I > will have several dictionary-like objects and not all of their items > should be accessible by get/set methods (only some of the corresponding > attributes belong to the public interface). I'm a bit afraid the overhead > of dynamically making all the decisions for every access might be slow > (though it may well be that all will be fast enough). > > So to rephrase the problem a bit: I would like to generate simple getters > and setters with rather little decision overhead during the actual accesses. :-) Well in that case: class GetterTest1: def __init__(self): self._dict = {'key1': 'one', 'key2': 'two', 'key3': 'three'} def _make_getters(self, dict_name, key_list): for key in key_list: code = "def %(key)s(): return %(dict_name)s['%(key)s']\n" % vars() exec code in self.__dict__, self.__dict__ ----------------- The problem is the distinction between bound vs unbound methods. BTW, this version is about 3 times faster than the previous. It took .03 seconds to call key1 10,000 times vs. .1 seconds. Neal From akuchlin at mems-exchange.org Thu Mar 28 15:07:10 2002 From: akuchlin at mems-exchange.org (Andrew Kuchling) Date: Thu, 28 Mar 2002 15:07:10 -0500 Subject: PEP262 - database of installed packages In-Reply-To: <20020328112544.A13176@ActiveState.com> References: <20020328112544.A13176@ActiveState.com> Message-ID: <20020328200710.GA26312@crystal.mems-exchange.org> On Thu, Mar 28, 2002 at 11:25:44AM -0800, Trent Mick wrote: >Yes, a couple of tags were added under the tag to enable a >PPD to decribe (1) what language it is suitable for (in our current usage, >Perl or Python) and (2) what range of versions of that language interpreter >it will work for. OK, those changes seem straightforward and can be handled when the time comes. Here's another question: is there any explanation of how version numbers are handled? distutils/version.py has extensive examples in the docstrings for the StrictVersion and LooseVersion classes, and I'm wondering how they'd be mapped to PPD's version tuples. The PPD man page on aspn.activestate.com gives an example version tuple as "4,2,0,0", but it's not clear how that maps to a version number, or what a version number such as 2.2.1a3 would be translated to as a tuple. --amk (www.amk.ca) Is this thing reliable? -- Grace, asking about the TARDIS, in "The Enemy Within" From mwh at python.net Tue Mar 12 07:32:03 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 12 Mar 2002 12:32:03 GMT Subject: Question about scientific calculations in Python References: Message-ID: Martin Kaufmann writes: > Hello Newsgroup > > I'm trying to write a program to calculate diffraction patterns for > electron diffraction on clusters (100-10'000 atoms). So far I used > Python only for CGI programming and system tools (on a rather low > level...). Therefore I don't know whether it's reasonable to program > such a project in Python (I really like the language). Presently my > man concern is speed as the main function of the program is a nested > loop, the inner over several 1000 bins of a histogram and the outer > over several 1000 values of scattering factors. In the end I should be > able to simulate diffraction patterns and compare them to the > experimental data (i.e. run this function several times). > > Now my questions: Would it be best to > > (a) write the whole program in C/C++ (I know only the basics of C but > it would be a good "excuse" to learn it...)? Well, you're unlikely to get advised to do this here :) > (b) write the main program in Python but the heavy calculations in C > (I played today with scipy.weave -- the speed is much better but I > didn't really understand what I was doing...)? This is probably the better option, but first... > (c) program it in Python and don't care about speed (or buy a new > workstation...)? ... I'd do this. Write your algorithm in Python. Run it on small examples to test. See if it's fast enough to run your real problems. If it's not, go for (b). It may be possible that modules already exist to do the heavy lifting -- e.g. Numeric. It's hard to say for certain without knowing more about your algorithms. Things like weave and PyInline may help. > Are there any libraries or other resources that would help? I used the > Scientific Python library for the histogram but it was much slower > than my DIY approach. Maybe you could submit better code to the SciPy project? > I hope my questions are not too much OT. Don't think so myself. Cheers, M. -- CLiki pages can be edited by anybody at any time. Imagine the most fearsomely comprehensive legal disclaimer you have ever seen, and double it -- http://ww.telent.net/cliki/index From tejarex at yahoo.com Wed Mar 27 10:04:20 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Wed, 27 Mar 2002 15:04:20 GMT Subject: Why does this work? References: <3CA1BB93.FC00D40D@pop.ntlworld.com> Message-ID: "a.clarke11" wrote in message news:3CA1BB93.FC00D40D at pop.ntlworld.com... > Hi > I defined a class, and made an instance. The class sis not have a > def__init__() line. A class statement may optionally have a body that defines *class* attributes (members and methods). The body may optionally include an __init__(self, args) method, which is mostly used for initialing *instance* attributes immediately after the creation of a new (and blank) instance. When you try to read instance.name, the interpreter first looks in the instance dictionary for instance attribute 'name'. If it does not find it, it then looks in the class dictionary for class attribute 'name'. (And if there are base classes, it will look thru their dicts also if necessary.) > In the class, I defined a function f(x) and an list > object X.tiles. Why can I later call instancename.f, and > instancename.tiles? Because that is how Python classes work, as explained above. Terry J. Reedy From maric.michaud at cirec.com Thu Mar 7 12:09:59 2002 From: maric.michaud at cirec.com (Maric) Date: Thu, 7 Mar 2002 18:09:59 +0100 Subject: popen3 on win32 python:2.1.2 In-Reply-To: <3C879869.3090803@thomas-guettler.de> Message-ID: <005301c1c5fa$ea59e3e0$470010ac@GERLAND2.local> We had a similar problem on linux using popen3 to manage cdrecord and mkisofs. These two programs for some unknown reasons (not in all cases) doesn't close standard error output and continuously send null char in it. We resolve it by waiting for process to send null chars either on standard and standard error output (while process running correctly this doesn't happen) and then close the pipe. The child now can shutdown properly. Works fine. -----Message d'origine----- De : Thomas Guettler [mailto:st-newsgroups at thomas-guettler.de] Envoy? : jeudi 7 mars 2002 17:42 ? : python-list at python.org Objet : popen3 on win32 python:2.1.2 Hi! popen3() hangs on W2K: (stdin, stdout, stderr)=popen3('wvWare -x wvware.xml foo.doc') text=stdout.read() --> read() never ends. It works if wvware produces few output, but with larger files it hangs (0% CPU usage). wvware is a binary from gnuwin32.sourceforge.net I use the python version which comes with zope: 2.1.2 Platform: Windows 2000 SP2 Is this a know problem? Are there workarounds? thomas -- http://mail.python.org/mailman/listinfo/python-list From jwbaxter at spamcop.net Tue Mar 26 22:45:34 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Tue, 26 Mar 2002 19:45:34 -0800 Subject: question on slices References: Message-ID: In article , John Warney wrote: > I am sorta new to programming, i have had an intro to programming > using C++ and thats it. Other than that i have kinda read a few > things but now i am into Python.....blah blah blah..... > The issue that i have a problem with is slices. for instance let me > show you a snippet: > > >>> numlist=[0, 1, 2, 3] > >>> numlist[1] > 1 > >>> numlist[2] > 2 > >>> numlist[1:2] > [1] > > This last one doesnt make since to me since i am asking for a range > from 1-2. Why in the world does it give me 1 when i am asking for 1-2 > which would logically be: > > >>> numlist[1:2] > [1, 2] > > but it's not. it doesnt make since. Just seems strange when i just > was in a C++ class and it would do the logical thing. You think you are asking for the elements from 1 *through* 2. You aren't...instead, you are asking for the elements from 1 through just before 2. Before you say how clearly bogus that is, play around with slices given the above and note how consistently they work, particularly with negative (counting from the ends) numbers given. Also, note that numlist=[0, 1, 2, 3] otherlist = numlist[0:2] + numlist[2:] print otherlist makes sense...ie, otherlist looks the same as numlist. No need to fudge with a +1 or a -1 to make that happen. --john From phd at phd.pp.ru Mon Mar 11 11:59:25 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 11 Mar 2002 19:59:25 +0300 Subject: equivalent of "export" (changing parent's environment) In-Reply-To: <20020311115016.A35060@doublegemini.com>; from cce@clarkevans.com on Mon, Mar 11, 2002 at 11:50:16AM -0500 References: <20020311115016.A35060@doublegemini.com> Message-ID: <20020311195925.B364@phd.pp.ru> On Mon, Mar 11, 2002 at 11:50:16AM -0500, Clark C . Evans wrote: > Hello. I have two shell scripts, a.sh and b.sh such > that a.sh calls b.sh, and b.sh uses "export key=value" > to set some defaults used later on in a.sh. There is something wrong in your explanation (or understanding). There is no way b.sh can change *anything* in a.sh environment. Either a.sh just "source" (inclide) b.sh (not exec, but source), or b.sh returns new environment to a.sh using echo (and a.sh executes generated commands). Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From sandskyfly at hotmail.com Thu Mar 14 02:54:42 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 13 Mar 2002 23:54:42 -0800 Subject: basic statistics in python References: Message-ID: "dsavitsk" wrote in message news:... > hi all, > > never having done numeric calculations in python* i am seeking advice on how > to best go about doing some basic statistics. in particular, i need to find > standard deviations and point bi-serial correlations**, and i am seeking > advice on the best way to go about it. i know how to do them, but i am > wondering if there are prebuilt modules that might simplify the task. here's a good start: http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html for some nice pure python statistical function implementations. Orange, the super cool python machine learning system also includes an extension called statc.dll which has some fast functions. http://magix.fri.uni-lj.si/orange/ a data mining extension to orange for clustering and whatnot is also available: http://ai.fri.uni-lj.si/~aleks/orng/ There is the fine and well-documented python Numeric library: http://www.pfdubois.com/numpy/ Scipy - scientific tools for python (includes a version of Numeric): http://www.pfdubois.com/numpy/ And, of course, there is Scientific Python: http://starship.python.net/crew/hinsen/scientific.html all of these, like python, are fun, fun, fun... enjoy (-: Sandy From jriveramerla at yahoo.com Tue Mar 19 19:17:15 2002 From: jriveramerla at yahoo.com (Jose Rivera) Date: 19 Mar 2002 16:17:15 -0800 Subject: What am I doing wrong with urllib.urlopen() ? Message-ID: <11e94203.0203191617.46008366@posting.google.com> Hi... Thanks in advance for any help... I want to retrieve data from the web for historic research about real state prices, fetching the info from a newspaper page, for personal use, loading this to MySQL DataBase for later study on trends, but I don't want to be doing this procedure manually every day. But this routine just gives me an error, please try it and see whats wrong?, I have not found what am I missing. When I try the address genereated by the code directly on the iExplorer.EXE, it works... but not on Python... This is the routine: -------------------- import os import urllib params={} params["pagina"] = 1 params["Presentacion"] = "Tabla" params["Tipo"] = "CASAS" params["Order"] = "Order By Fecha Desc" params["id_inmueble"] = "3" params["zona"] = "0" params["COLONIA"] = "0" params["RECAMARAS"] = "0" params["BANOS"] = "0" params["dia"] = '' params["PLANTAS"] = "0" params["Constr_i"] = "-1" params["constr_f"] = "-1" params["Terreno_i"] = "-1" params["Terreno_f"] = "-1" params["Precio_i"] = "-1" params["Precio_f"] = "-1" params["fotos"] = "0" # This is the address calculated #http://avisos.elnorte.com/casa_venta_result.asp?fotos=0&Order=order+by+colonia&Precio_i=-1&Presentacion=Tabla&Precio_f=-1&PLANTAS=0&pagina=1&id_inmueble=3&dia=&RECAMARAS=0&constr_f=-1&COLONIA=0&BANOS=0&Tipo=CASAS&Constr_i=-1&Terreno_i=-1&Terreno_f=-1&zona=0 pms=urllib.urlencode(params) direccion="HTTP://AVISOS.ELNORTE.COM/casa_venta_result.asp?%s"%pms #print direccion f=urllib.urlopen(direccion) ff=open('xc.htm','w') ff.write(''+direccion+'<\br>') ff.write(f.read()) ff.close os.system('start xc.htm') From ballabio at mac.com Tue Mar 26 10:30:37 2002 From: ballabio at mac.com (Luigi Ballabio) Date: Tue, 26 Mar 2002 15:30:37 +0000 Subject: list element of a class with the for statement In-Reply-To: References: Message-ID: <5.1.0.14.0.20020326152905.00a5e0a0@mail.mac.com> At 02:41 PM 3/26/02 +0100, Tjabo Kloppenburg wrote: >or, in python 2.2 syntax: > > def __iter__(self): > self.ptr = 0 > return self > > def next(self): > if self.ptr < (len(self.__records) - 1): > self.ptr = self.ptr + 1 > return self.__records[self.ptr] > else: > raise StopIteration def __iter__(self): return iter(self.__records) should do the job without having to go through all that machinery... Bye, Luigi From see at below Mon Mar 11 07:05:11 2002 From: see at below (Paul Foley) Date: 12 Mar 2002 01:05:11 +1300 Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: On 12 Mar 2002 00:16:45 +1300, I wrote: > (defun eval (form) > (funcall (compile nil `(lambda () , at form)))) Yikes; better make that `(lambda () ,form) -- Whenever you find that you are on the side of the majority, it is time to reform. -- Mark Twain (setq reply-to (concatenate 'string "Paul Foley " "")) From bokr at oz.net Tue Mar 12 18:28:00 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Mar 2002 23:28:00 GMT Subject: Anonymous attribute/property possible? References: Message-ID: On Mon, 11 Mar 2002 10:46:13 GMT, Michael Hudson wrote: >bokr at oz.net (Bengt Richter) writes: > >> A class with an anonymous attribute/property would provide a place to put >> get/set/del-triggered code. >> >> Use of an object with an anonymous property in an expression >> or statement would result in calling the get/set methods defined. >> >> Thus you could write foo(bar) with the effect of foo(bar.__anonymous__) >> and bar() with the effect of bar.__anonymous__() >> >> And bar = baz with the effect of bar.__anonymous__ = baz. >> >> But since __anonymous__ could be a property, you could define >> methods at will (e.g., get_bar, and set_bar) and write >> bar = baz with the effect bar.set_bar(baz) and >> foo(bar) with the effect foo(bar.get_bar()) >> >> This might work nicely with an interpolated-string class. >> E.g., >> is = IS('The get_is anonymous property method will interpolate $variables') >> print is # the reference would trigger interpolation with current values >> # you could do this now, but you'd have to write "print is.some_property" >> > >Ouch. > Where does it hurt ;-) >> If you wanted to access the actual object that had an anonymous >> property, you'd have to give it a named method returning self for >> that purpose. Or obj.self, better. >> >> I think this could open up a whole world of scary delights ;-) >> (And ISTM without a backwards compatibility problem). > >Just in case the fact that this is a horrible idea doesn't put you off >, how would you implement this without a fairly huge performance >hit? LOAD_FAST is currently, well, fast. > Well, I was avoiding premature optimization ;-) I'm not seriously advocating this. I just wanted to explore the notion a little. I should look at the code, but if LOAD_FAST gets a pointer to the object representation, it might not be so bad to check a boolean value cached therein to see if __anonymous__ magic was associated. I'm not suggesting a lookup in the object's attribute dict to see if it has the __anonymous__ attribute at run time. Adding or deleting .__anonymous__ dynamically would have restrictions. I'm thinking a flag bit in some standard lowlevel object representation slot indicating presence of the __anonymous__ attribute, which could be checked with a test and jump (if there is already a representation type code used in a switch, maybe a new case wouldn't add any new overhead). You might need a LOAD_SELF byte code for references to the object itself where *no* __anonymous__ flag check was to be made, which the compiler would generate from a reference to obj.self as a reserved attribute name. Thus obj.self would generate LOAD_SELF obj and obj would generate LOAD_FAST obj. Anyway, if the flag was set, it would mean that there was an implicit LOAD_ATTR or STORE_ATTR using __anonymous__, which could presumably share normal code for those. Thinking-via-the-keyboard-again-ly ;-) Regards, Bengt Richter From just at xs4all.nl Tue Mar 26 09:23:54 2002 From: just at xs4all.nl (Just van Rossum) Date: Tue, 26 Mar 2002 15:23:54 +0100 Subject: list element of a class with the for statement References: Message-ID: In article , Tjabo Kloppenburg wrote: > or, in python 2.2 syntax: > > > def __getitem__(self,i): > > return self.__records[i] > > def __iter__(self): > self.ptr = 0 > return self > > def next(self): > if self.ptr < (len(self.__records) - 1): > self.ptr = self.ptr + 1 > return self.__records[self.ptr] > else: > raise StopIteration But that's different! In the "old-style" iterator the next bit will work as expected: for entry1 in db: for entry2 in db: ... But with the way you wrote the new-style iterator it won't. It's also not thread-safe. Just From mpoulin at verinet.com Sat Mar 23 09:54:56 2002 From: mpoulin at verinet.com (Marc Poulin) Date: Sat, 23 Mar 2002 09:54:56 -0500 Subject: Packaging tool References: Message-ID: <3c9cb2b9$0$4057$7586b60c@news.frii.com> There are Python front-ends to both rpm and dpkg: http://www.megaloman.com/~hany/RPM/RByName.html http://packages.debian.org/stable/devel/dpkg-python.html Are these suitable for your needs? In article , "mohamed lazreg" wrote: > --- Gillou wrote: >> "make" seems to be what you're looking for. It's not in python, but it >> does the job. > > Nice try...:):):P. By a packaging tool I do not mean a make utility. I > have in mind some thing like dpkg, the Debian package management system. > (but I would like to have it in python). > > Thank you anyway... From thomas at weholt.org Sat Mar 23 12:42:54 2002 From: thomas at weholt.org (Thomas Weholt) Date: Sat, 23 Mar 2002 17:42:54 GMT Subject: When to use locks in a threaded Web-server Message-ID: I got a web-server project based on BaseHTTPServer using threads ( SocketServer.ThreadingMixin ). What do I have to do to make it "safe", thread-wise? When do I have to aquire locks to set variables in a) the webserver itself or b) in variables in the given requesthandler ?? I thought each request would be handled using a seperate thread using this method, ie. no locking required for altering stuff inside the requesthandler alone. Is this correct? Is each handler a fresh new instance of the custom requesthandler-class? My assumptions lead me to think that I only have to use locks when changing things in the global thread, the webserver, both from the requesthandlers and inside the thread itself, ie. if the webserver alters variables in the webserver. Correct? Below are some code to examplify : The HTTP-server class HTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): def __init__(self, root, hostaddress, port, handler, static_folder = None): BaseHTTPServer.HTTPServer.__init__(self, (hostaddress, port), handler) self.var1 = 1 The custom requesthandler : class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def __init__(self): BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, ....) self.svar1 = 1 def do_GET(self): # something self.server.var1 = 100 self.svar1 = 100 What variables requires a lock to be safe? var1 in HTTPServer? svar1 in the RequestHandler? Other situations I'll have to watch out for? Any clues, hints etc. appreciated. Best regards, Thomas Weholt From aahz at pythoncraft.com Mon Mar 25 09:58:17 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Mar 2002 09:58:17 -0500 Subject: Root access with python References: <7x663krjtp.fsf@ruckus.brouhaha.com> Message-ID: In article <7x663krjtp.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >mtaylor at lowebroadway.com (Moray Taylor) writes: >> >> I want to know how to run a 'root' command with python, i.e. mounting >> an NFS drive. >> >> On the terminal, you would do a 'su', type your password, then enter >> the command you wanted to run. How is this achieved within Python? >> >> My purpose is to make a small GUI app with PyQT to make mounting NFS >> volumes easier, I can handle the GUI bit, but I don't understand how >> to 'su'. > >Don't try to do that unless you REALLY know what you're doing with >security implementation. > >Instead, run "su" the usual way and type your password to get a root >shell, then launch your GUI app from the root shell. Good advice. Nevertheless, if Moray wants to shoot zirself in the foot, zie should take a look at os.setuid(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From fredrik at pythonware.com Mon Mar 18 11:27:07 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 18 Mar 2002 16:27:07 GMT Subject: Old File Purge Suggestions? References: <1W9l8.176946$Dl4.19853391@typhoon.tampabay.rr.com> Message-ID: Chris Liechti wrote: > > I'm using sys.stdin.readlines(): getting the date passed in from > > from "ls -l" (linux). Then compare dates using the mxDateTime > > i think os.stat gives you the same information as "ls -l" and you > don't have to parse strings (use os.listdir to get the names and then > stat on them) os.path.getmtime is a bit easier to use, e.g: import time, os now = time.time() max_age = 3 * 86400 # three days for file in os.listdir(directory): fullname = os.path.join(directory, file) if now - os.path.getmtime(fullname) > max_age: print "remove", fullname # os.remove(fullname) From DeepBleu at DeepBleu.org Fri Mar 1 09:13:32 2002 From: DeepBleu at DeepBleu.org (DeepBleu) Date: Fri, 1 Mar 2002 08:13:32 -0600 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <20020227163411.71b4b4d8.alex@netWindows.org> Message-ID: "Dennis Roark" wrote in message news:Xns91C39C93F933Edenroearthlinknet at 207.217.77.23... > Alex Russell wrote in > news:20020227163411.71b4b4d8.alex at netWindows.org: > [....................] >That the D & D book > came out in Python was more of an indication of Python going mainstream, > and for that I celebrate it. > This is the only saving grace of this book. What is so sad is that they'll end up making tons of money (to my knowledge, two of their books are textbooks: C++ and Java) with their money making publishing machines while someone like Mark Hammond can not find a job. Of course not to mention that they may be probably going ahead for plans for a book on Python (Complete Python Lab maybe) with a CD and start their won consulting business on Python. Rediculous! Then of course we'll see some professors assigning the D & D Python book as a textbook on a scripting language. How disgusting! DeepBleu From roy at panix.com Sun Mar 31 09:26:28 2002 From: roy at panix.com (Roy Smith) Date: Sun, 31 Mar 2002 09:26:28 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote: > Your list of alternatives that reek in comparison was > puzzling. int(bool(obj)) doesn't reek to me: it is obvious what it > does, it does that efficiently, and it requires less typing than > operator.truth(obj). Seems to me, obj.bool().int() would be the obvious way. From brian at sweetapp.com Tue Mar 5 18:22:14 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 5 Mar 2002 15:22:14 -0800 Subject: python IDE, komodo In-Reply-To: <3c854cbd$1_1@news.iprimus.com.au> Message-ID: <005101c1c49c$95b69e00$445d4540@Dell2> Jamie Carl wrote: > > Komodo is good, but I am biased. :) > > Take a look at: > > http://www.python.org/editors/ > > > > Didn't he say free would be nice? Komodo isn't free. If he [Marcus] is serious about debugging, I think that IDLE-fork (http://idlefork.sourceforge.net/) is the only free IDE with the ability to debug scripts in a separate process (Komodo has this ability). For tracing (code converage?) and profile tools, he can just look at the scripts that ship with Python. I don't think that any of the IDEs have any significant level of integration. One important thing to note is that Komodo doesn't have an interactive shell (which all of the free IDEs do). Anyway, why not just try Komodo and see if it works for you? Cheers, Brian From QnickQm at alum.mit.edu Mon Mar 4 18:06:55 2002 From: QnickQm at alum.mit.edu (Nick Mathewson) Date: Mon, 04 Mar 2002 23:06:55 GMT Subject: Problem with SRE's regular expressions References: <3C83D5C6.7010303@free.fr> <3C83EA12.5030406@free.fr> Message-ID: In article <3C83EA12.5030406 at free.fr>, Christophe Delord wrote: > Thanks for your explanation! > > In my real program, I had a more complex regexp. I need to match text > enclosed in << ... >> > I first have used such an expression : <<([^>]|>[^>])*>> > but I prefered <<.*?>> because it is more readable. > > I'll listen to the advice and use my old regexp to see how faster it is > this way ;-) > > Thanks, > Christophe. # # Actually, it looks like you can do at least sixty times better than # the re you have above. # import sys, time, re print sys.version def timefn(fn): t = time.time() fn() t = time.time() - t print "%40s %f" % (fn.__name__, t) m#Very Long String vls = "<<" + " "*100 + ">>" def simple_version(): ' This is the version from your post ' r = re.compile(r'<<([^>]|>[^>])*>>') for i in xrange(10000): r.match(vls) def non_grouping_match(): ' This one uses non-grouping matches ' r = re.compile(r'<<(?:[^>]|>[^>])*>>') for i in xrange(10000): r.match(vls) def match_with_big_groups(): ''' This one uses [^>]+ inside the group, in order to make each group as large as possible. ''' r = re.compile(r'<<([^>]+|>[^>])*>>') for i in xrange(10000): r.match(vls) def non_grouping_match_with_big_groups(): ' This version uses both of the above tricks. ' r = re.compile(r'<<(?:[^>]+|>[^>])*>>') for i in xrange(10000): r.match(vls) def nongreedy_match(): " And for comparison, here's the one with the nongreedy match. " r = re.compile(r'<<.*?>>') for i in xrange(10000): r.match(vls) timefn(simple_version) timefn(non_grouping_match) timefn(match_with_big_groups) timefn(non_grouping_match_with_big_groups) timefn(nongreedy_match) # # Platform: # 2.2+ (#30, Jan 29 2002, 21:20:45) # [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] # # OUTPUT # simple_version 37.967640 # non_grouping_match 34.108361 # match_with_big_groups 0.818009 # non_grouping_match_with_big_groups 0.634849 # nongreedy_match 16.892410 So it looks like the big win is to use [^>]+ inside your parenthesis. It's a slight improvement to use (?: ) instead of ( ), but not much. Bonus observation 1: In this case, the overhead from matching a parenthesized expression over and over is more than than the backtracking overhead from '.*?' . Bonus observation 2: I purposefully put some '>' characters into the test string. When I took them out, I found that the 60X performance improvement turned into a 332X performance. Thus, the winning pattern above is fastest of all when the parenthesized expression matches only once. It-looks-like-I'm-going-to-have-to-go-rewrite-all-the-scanners-I'm- maintaining-ly Y'rs -- Nick Mathewson Remove Q's to respond. No spam. From eppstein at ics.uci.edu Tue Mar 5 16:37:39 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 05 Mar 2002 13:37:39 -0800 Subject: Status of PEP's? References: Message-ID: In article , James_Althoff at i2.com wrote: > And note again also, that (the equivalent of) > > def __contains__(self,x): > raise TypeError > > could be added to class int if the anguish proved to be insurmountable <0.1 > wink>. That would cause me much more anguish than even PEP 276 in its present form. I really like the fact that "for ...stuff..." loops over exactly those values for which "...stuff..." is true. I don't want to see that broken. From boudewijn at tryllian.com Sat Mar 2 04:57:15 2002 From: boudewijn at tryllian.com (Boudewijn Rempt) Date: Sat, 02 Mar 2002 08:57:15 -0100 Subject: Black Adder and PyQt References: Message-ID: <3c8087eb$0$18514$e4fe514c@dreader4.news.xs4all.nl> Ron Stephens wrote: > I am thinking of buying a "home" license of Black Adder, to use for > making GUI's for Python programs to be used on Linux+KDE and also > perhaps for the new Sharp Zaurus. Does anyone have any experience with > Black Adder that they can share? One of my main reasons for wanting > Black Adder is to use the GUI builder, so I am particualrly interested > in opinions about that aspect of Black Adder, but I am also interested > in other aspects as well. > > One question I have concerns licensing. If I buy the "home" version, > could I still share my programs as GPL'ed open source, or would that > require me to buy the "professional" license, which is much more > expensive? In other words, my programs would never be used in any > commercial way but I might want to post them as open source, free > software. > > I know Black Adder is still in beta, but is it stable enoough to use > already? I suppose I should ask how it compares to PythonWare amd > WingIDE, but I kind of favor the PyQt toolkit becuase it will > hopefully work well on the Sharp Zaurus as well as the KDE desktop. I think WingIDE is a better IDE -- but it doesn't include the GUI designer. The gui designer is, in fact, just the Qt Designer as included with Qt, so you could you use that, but you'd lose all the nice integration. With the latest version of PyQt, you can compile Qt 3 .ui files to Python, too, but that's not part of BlackAdder yet. Have you seen that my book on PyQt and BlackAdder is out? You can order it at opendocs.org (never mind that the website still says it's in final copy-edit -- copies are shipping now, only Joshua is a bit slow updating), or read it online. But the paper copy is very pleasant possession :-). -- Boudewijn | http://www.valdyas.org From mcherm at destiny.com Mon Mar 25 18:00:29 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 25 Mar 2002 18:00:29 -0500 Subject: question on slices Message-ID: <3C9FAC0D.2050306@destiny.com> >>>> numlist[1:2] > [1] > > This last one doesnt make since to me since i am asking for a range > from 1-2. Why in the world does it give me 1 when i am asking for 1-2 > which would logically be: > >>>> numlist[1:2] > [1, 2] > > but it's not. it doesnt make since. Just seems strange when i just > was in a C++ class and it would do the logical thing. > Actually, this *IS* doing the "logical" thing, but only once you get into certain Python mindsets. In Python, all ranges are "half-open". That means that the lower end point IS included, but the upper end point is not. You've encountered this pattern before in C++: for( int i=0; i Message-ID: Arcady Genkin writes: > How do I signal the GUI thread that new information for a particular > object has arrived? Currently I'm using after() method of the Tkinter > object to update info for *all* objects every second, but that is > hardly a good design, since there may be 500 of them, and the new info > can be arriving once every 15 minutes. > > Any ideas and/or pointers to the documentation (preferably online) > highly appreciated. There are different ways to do this. For example, you don't need to redraw everything in your after() method - just produce a global list of things to redraw, and have your after method analyse this list. If you want to delete the need for an after() method altogether, you could register an after_idle callback. You can do that from a different thread; Tkinter will call the after_idle callback from the same thread that runs the mainloop. Notice that Tkinter currently uses "busy waiting" to cope with multithreading as well, so an additional after() callback won't hurt too much. HTH, Martin From tejarex at yahoo.com Sun Mar 17 22:06:23 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Mon, 18 Mar 2002 03:06:23 GMT Subject: how to print class names, not references References: <3C9544B5.47CD0918@pop.ntlworld.com> Message-ID: "a.clarke11" wrote in message news:3C9544B5.47CD0918 at pop.ntlworld.com... > Hi, > I wrote a function of x, where later in the program x is substituted by > class names. In the function, print x is used, but this returns > <__main__.Player instance at 0x38b1ce90> rather than the plain old class > name that I wanted. > How can I print the name instead? grab the string that tells too much: toomuch = str(x). then pull out the part you want -- which is perhaps the definition name between the first '.' and first ' '. Terry J. Reedy From trentm at ActiveState.com Wed Mar 13 15:29:53 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 13 Mar 2002 12:29:53 -0800 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: ; from aahz@pythoncraft.com on Wed, Mar 13, 2002 at 01:17:15PM -0500 References: Message-ID: <20020313122953.B15069@ActiveState.com> [Aahz wrote] > In article , > Trent Mick wrote: > >[Michael Hudson wrote] > >> > >> Time to look at roundup again? The tracker on sf is starting to piss > >> me off (even more). > > > >If you *are* going to get motivated to look at a different tracker *please* > >consider bugzilla. You will find it a much more appropriate than roundup. > > Sure! Knowing nothing about SF trackers (yesterday was my first > submitted bug, I think), roundup, or bugzilla, I think I'm in a perfect > position to evaluate all of them. Can you explain what makes bugzilla > superior to roundup? Bugzilla has a big use community, hence, I would suspect better support. It is heavily used in a lot of projects. Roundup is not, from what I know. With bugzilla you can explicitly add yourself and remove yourself from the Cc lists of bugs. With roundup you get plopped onto a the nosy list of a bug by responding to traffic on the discussion. That seems like a good idea but we (Komodo development folks at ActiveState) found that that didn't scale that well to lots of and long standing bugs when people joined and left the team. Roundup's use of the subject line of emails to carry bug attributes did not, in our experience, scale well. MarkH does a good defense of bugzilla here: http://aspn.activestate.com/ASPN/Mail/Message/1060597 > What, if anything, does roundup have that bugzilla > does not? It is written in Python. :) Trent -- Trent Mick TrentM at ActiveState.com From philh at comuno.freeserve.co.uk Mon Mar 25 14:11:25 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 25 Mar 2002 19:11:25 +0000 Subject: Indentation problem References: Message-ID: On Mon, 25 Mar 2002 14:16:49 +0100, Gilles Diribarne wrote: >Hi, > >I like Python language and use it every day. But... >I read some articles from October, 1998 where there was a fight with >space and tabs and indent problems. >Today, we can found code with spaces and tabs in the code. > >I've some problem with identing code. I'm allright with the example. >But, I think it's important to have an "end" building block like "!:" > >What do you think about that? > >Why I would like to put this in the code? >1/ Because it's almost impossible to paste python code with ident = n >spaces to another code with indent = m spaces >This kind of examples occurs more and more and you can indent the code >by hand when it's 10 lines of codes, but not 1000 code lines. >It prevents the re-use of code pieces. This implies 2 things: (1) you regularly cut and paste 1000-line code fragments (2) when you do this in other langs, such as C, you don't bother reformatting. I'm glad I don't have to maintain your code!!! Some editors, such as nedit, allow you to indent/outdent blocks of code. I suggest you use such an editor if this is a problem for you. >2/ Programmers wants independence: some wants to manage building blocks >with spaces, other with tabs, some wants length = 4 with tabs. These people have the option of not using python. The python standard defines tab == 8 spaces. >I would like to use my own programming style! But, my code risks to be >not supported by others. There's a python indent utility, that allows code to be re-indented. You could extend this, so that everyone gets the code in the format they like, and it gets put in CVS in a standard format. >4/ Solve the problem of space and tabs length. But, we should keep the >indenting mode which produces beautifull syntax. >pythona.py: > def func(): > a = 1 > if a == 1: > a ==2 > print "beatifull! Isn't it?" No idea what you are getting at here. >You cannot merge correctly or tell me how to do this ? >This is simply because the language doesn't have a "end" instruction >block. It has ":" as beginning instruation block. >I would like to propose an end instruction block like "!:" or "end" How about using "#end"? Or "#end def", "#end for", etc. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From holger at trillke.net Sun Mar 24 18:29:36 2002 From: holger at trillke.net (holger at trillke.net) Date: Mon, 25 Mar 2002 00:29:36 +0100 Subject: Stopping threads from the outside In-Reply-To: <3C9E53D8.4FA20F3D@engcorp.com>; from peter@engcorp.com on Sun, Mar 24, 2002 at 05:31:52PM -0500 References: <3C9E173A.88BBDBB4@engcorp.com> <3C9E53D8.4FA20F3D@engcorp.com> Message-ID: <20020325002936.I12768@prim.han.de> > > > "The network"? Which one? The Internet, or an internal > > > network over which you have full control? Who controls > > > the servers on which these agents will be running? > > > > well. at the moment the servers are under my control. > > but this is hopefully going to change. > > So is your purpose in shutting down threads that you want > to prevent agents written by others from running forever? > Or can you count on the good behaviour of those writing > agents to run on these servers? Mainly i want to be able to replace running agents (for the develop/deploy/test-cycle). > > In fact it is quite hard to group the agent-threads because they are very > > autonomous (and btw quite cooperative with other agents). > > "Cooperative"? As in, working together on problems? Or > working on their own individual problems without any > interference or perhaps interaction? ok. speaking plaintext: one agent is constructing (updating) and providing navigationable Music-Objects (like Song, Group, CD). another is analyzing samba- and other logfiles to see which song was played when/how often/... the third provides methods for a "virtual hitparade" like "top ten" and stuff. this one works on the other agents. actually a fourth one is also installed (a "quixote"-agent) which provides a web interface (using the third "scoring" agent). So basically one Agent-Thread may call into methods of another agent (not message-oriented, calls into the other modules in the same thread). But i want to be able to "correct" the code of e.g. the Music-Objects Agent: i have to first stop/kill the thread which might be in the process of updating stuff. then bring in new code and deploy it. the last part actually works. killing the agent is the issue which i originally wanted to "solve" generically. The prescribed "ThreadInterruptException" could be generated by the python-interpreter working on this thread. Something like threading.interrupt(threading.Thread-instance) would signal the interpreter to generate an exception on the next possible occasion. Is this nonsense or a sensitive approach? thanks, holger From James_Althoff at i2.com Fri Mar 1 19:04:16 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 16:04:16 -0800 Subject: Status of PEP's? Message-ID: [David Eppstein] > I was starting to think it might be time to write a > PEP, but then Tim's comment about how he dislikes iterating > over 3 discouraged me. [Bjorn Pettersen] > I would still encourage you to write a PEP, especially if you think > this should be implemented instead of PEP 276. I agree as I just remembered another issue that came up concerning the "for-relational" suggestion. Namely, that the "for-relational" syntax doesn't handle step values for intervals. So even though there would be new syntax, we would still need to use range/xrange in cases requiring a step value not equal to 1 or -1. Jim From tegskywalker at hotmail.com Wed Mar 20 04:05:59 2002 From: tegskywalker at hotmail.com (TegSkywalker) Date: Wed, 20 Mar 2002 03:05:59 -0600 Subject: Recommended Books/Resources for Python Message-ID: Hey all. Sorry if this sounds like a stupid question (new and want to learn Python) but do any of you have any suggested books or readings on how to learn Phython? I saw an O'Reilly book over at Amazon.com (http://www.amazon.com/exec/obidos/ASIN/1565924649) and wasn't 100% sure if this was a good source or not. Here is another question. I see that Python is a multisource language spanning different OSes like Windows, Linux, and Mactintosh like how Java aims to be. If I were going to program something like an interactive CD and wanted to give it to people to check out, would they have to have a Python interpreter installed on their machine or will it run like a normal Windows .exe file for example? Any help is appreciated. Thanks for your time! :) From gh_pythonlist at gmx.de Sun Mar 17 19:28:11 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 18 Mar 2002 01:28:11 +0100 Subject: Problem using pexports & Cygwin to build Python 2.2 extension modules In-Reply-To: References: Message-ID: <20020318002811.GC99651@lilith.hqd-internal> * Les Button [2002-03-17 15:21 +0000]: > Has anyone else had success building an extension module with Windows > Python 2.2 and Cygwin/gcc? Yes, me. Though I now prefer mingw. I just used this instead of pexports: http://cygwin.com/cygwin-ug-net/dll.html#DLL-LINK Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 8.1 ?C Wind: 1.0 m/s From hgg9140 at seanet.com Wed Mar 27 17:51:25 2002 From: hgg9140 at seanet.com (Harry George) Date: 27 Mar 2002 14:51:25 -0800 Subject: Dealing with python version References: Message-ID: Andrei Kulakov writes: > Hello, > > Correct me if I'm wrong, but it seems like if python1.6 or 2.0 are > already installed and you install a newer version, python command still > points to the old interpreter. > > I think it would be sensible to use the newest installed python to run > a program. Is there some elegant way to do that? > > I would ideally prefer it to run using newest interpreter available > unless it's older than some minimum requirement. It's not very > user-friendly to put #!/usr/bin/env python2.1 bang line and then say in > a README that if user gets an error, he has to somehow find out what's > the latest version he's got and change the bang line to it. > > What's the proper way to deal with all of this? > I'll assume *NIX, and more specifically Linux (because it has python scripts scattered through the std installation). Typically, the preinstalled scripts are expecting a specific version of python, and expect to find it via: #!/usr/bin/python or #!/usr/bin/env python You don't want to screw up those preinstalled scripts, so don't do anything to the original installation. Instead, install new version elsewhere, e.g.: /usr/local/bin/ python2.0 python2.1 /usr/local/lib/ python2.0 python2.1 Each installation will create a generic "python" binary (e.g., /usr/local/bin/python) as well as the versioned name. Delete the generic one, so it doesn't interfere with the preinstalled python. That leaves the problem of accessing the new ones. I use little scripts: /usr/local/bin py20 py21 Where py20 is, e.g.: #!/bin/sh unset PYTHONHOME PYTHONPATH PYTHONLIB /usr/local/bin/python2.0 "$@" To use: py20 myprogram.py Can also start scripts with: #!/usr/local/bin/python2.0 > Thanks, > > - Andrei > > -- > Cymbaline: intelligent learning mp3 player - python, linux, console. > get it at: cy.silmarill.org -- Harry George hgg9140 at seanet.com From calves at coelce.com.br Mon Mar 11 12:42:51 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Mon, 11 Mar 2002 14:42:51 -0300 Subject: RES: lambda question Message-ID: <29A97D00F387D411AC7900902770E148044AB32D@lcoeexc01.coelce.net> Thanks, It solved my problem. > -----Mensagem original----- > De: Corrado Gioannini [mailto:corrado.gioannini at nekhem.com] > Enviada em: segunda-feira, 11 de mar?o de 2002 14:30 > Para: Alves, Carlos Alberto - Coelce > Cc: python-list at python.org > Assunto: Re: lambda question > > > On Mon, Mar 11, 2002 at 02:06:51PM -0300, Alves, Carlos > Alberto - Coelce wrote: > > second code: > > > > def exe1(f,list): > > return map(lambda x:eval(f),list) > > > > Can someone explain to me why the first code works while > second doesn't. > try this: > > def exe1(f, list): > return map(lambda x, y=f: eval(y), list) > > cheers, > Corrado > -- > Corrado Gioannini > > > Nekhem Technologies > Tel.: (+39) 011 4407581 > > - > "Thought is only a flash between two long nights, > but this flash is > everything." > (H. > Poincar?) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhammond at skippinet.com.au Sun Mar 24 17:13:12 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 24 Mar 2002 22:13:12 GMT Subject: win32com problem (146 and 2.2) References: <3c9ce52f.4396882@netnews.attbi.com> Message-ID: <3C9E4F90.6050708@skippinet.com.au> Joe Smith wrote: > A coworker gets the following error: > > > Traceback (most recent call last): > File "C:\My Stuff\V3\GotoYahoo.py", line 7, in ? > ie.Navigate('http://www.yahoo.com') > File "", line 2, in Navigate > > pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, > None, None, > 0, -2147467259), None) > > > The script: > > > import win32com.client > > ie = win32com.client.Dispatch("InternetExplorer.Application") > ie.Visible = 1 > > ie.Navigate('http://www.yahoo.com') > > > A script similar to this one was working on his machine and all of a > sudden these sort of error started occuring. So, he uninstalled > win32com (146) and python 2.2 and then reinstalled them. He was still > having the problem, so I wrote the small script above to reproduce the > proble. He says that he has not changed the configuration on his > machine and I am stumped. IE has probably just started failing. Write a WSH version, and I expect you will find the exact same thing happening. Check for dead and invisible IE processes. Mark. From geoff at gerrietts.net Tue Mar 5 03:04:34 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 5 Mar 2002 00:04:34 -0800 Subject: Newbie ?:A more concise way? In-Reply-To: <8fc4b19e.0203042338.141afe8b@posting.google.com> References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <8fc4b19e.0203040130.17140530@posting.google.com> <8fc4b19e.0203042338.141afe8b@posting.google.com> Message-ID: <20020305080434.GA8197@isis.gerrietts.net> Quoting Brian (brian at lodoss.org): > Do you also feel my original code is better in terms of style or would > it be even better as the more verbose: > > z = [] > for i in xrange(y): > z.append(MyClass()) It might go faster. :) An alternative (though not a good one) might be to make MyClass's __init__ accept *args and ignore them: class MyClass: def __init__(self, *args): pass instant_list = map(MyClass, range(y)) There's not much compelling about this solution, but it does get rid of the extra function call. > OK - now I have another question (and remember I'm new to Python) if > map and lambda are part of the core language and have well defined > behavior, why is it that using them is considered bad form? Are they > just the redheaded step-children of the language, or what? ;-) An amusing but possibly apt observation. Through occassional glimpses at conversations, a few attributed quotes, and a bunch of my own guesswork, I would lay it out sorta like this: map() and the other functionals were added because it's a convenient form, a contributed patch, and popular among devotees of functional languages. With built-in functions, they can still be quite peppy, and there's no denying the power of expression they offer. But for most tasks, it's like having a 25 lb sledge and a whole lot of finishing nails to drive. It can get the job done, but it won't always be pretty. That said, a lot of people use them. Even when aware of the tradeoffs, I use them, definitely a lot more than I should. List comprehensions has reduced that somewhat. I think that I have seen notables in the python community (I would name names, but I don't have quotes to reference) have indicated regret at the introduction of map() and friends into the language. They end up being appropriate only very, very rarely. The lambda construct doesn't suffer from quite the same stigma, though I think some feel that it's overused, and to bad effect. The consequence often seems to be code that's a harder to read and understand rather than the other way around. I don't think I'm terribly religious either direction on this issue; in some ways, I'm like the contemporary smoker. I know functional functions and excessive lambdas are bad for me, but I just can't quit. I think there are a lot of us sinners in this particular layer of Hell. --G. -- Geoff Gerrietts "By doing just a little every day, I can gradually let the task completely overwhelm me." --Ashleigh Brilliant From brian at sweetapp.com Tue Mar 26 14:24:31 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 26 Mar 2002 11:24:31 -0800 Subject: stop In-Reply-To: Message-ID: <000201c1d4fb$db0aea50$445d4540@Dell2> Fredrik wrote: > Ok, so I'm going to be quite honest, I dont write perfect code, so today > while working in PythonWin I imported a file. Problem was that the file > happened to contain an infinte loop, which the interpreter gladly ran, > untill I killed the entrire program. Annoying. Is there no %&/!#ing stop > button in PythonWin? When PythonWin is running, there should be a PythonWin icon in the tray bar. Right click on that and select "Break into running code". Cheers, Brian From usenet at thinkspot.net Sun Mar 3 15:03:52 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 03 Mar 2002 12:03:52 -0800 Subject: Deitel and Deitel Book... References: Message-ID: On Sun, 3 Mar 2002 12:01:03 -0600, "Jason Orendorff" wrote in comp.lang.python in article : > I dislike Deitel & Deitel because of their casual disregard for > correctness. I can't open any of their books without finding an error. > In C++HTP, they illustrate "Circle" as a subclass of "Point". Well, it's true I didn't particularly care for that example. > Maybe they do this because they think it simplifies the point they're > making, but I think it's a disservice to the student. Anyone serious > about programming in C++ will need to know what derived classes > signify. I guess I found the book a useful reference, it was easy (for me) to find stuff in the index (someone here said their indices weren't good, and that surprised me), plus there are plentiful code examples. But I've only seen the one text (the C++HTP) and not the others. I don't care for a formulaic approach to writing programming books, where the author has a book already in one language and then adapts it to other languages, but this approach is quite common in the programming textbook arena, and I wouldn't single out Deitel and Deitel on that point alone. The paper is thin and the binding does suck, but the binding just came off of my Programming Python 2nd edition this past month, and often that type of stuff is the publisher's perogative and not the author's. Anyhow, now I start to sound like I'm defending D&D, which I'm certainly not. I was only expressing surprise at the general dislike for their book that so many have posted in this thread, as it is counter to the opinions I've encountered on their book in the past. In fact, I know some teachers who think that their book is practically the C++ gospel or something. I never had that high an opinion of their book. As I related, I didn't choose it for the text when I taught C++. I considered several other books, and ended up with the one by Walter Savitch. And while the narrative was very good in Savtich's book, there not enough good exercises and programming assignments for my high school students, and I was always having to search other books for that type of stuff and often ended up using exercises out of the Deitel's book. The exercises in C++HTP are very good for instructors to assign to students and not many books have that type of stuff. I'm currently teaching math at the University level, and it seems that I have LOTS more time to prepare for class than I did at the high school level, and I don't assign near as much work (I see the students far less and they are supposed to be more responsible to take some initiative for the learning on their own). So whether a book with so many exercises is really necessary for college...still, when I was a student using that text, I appreciated the availability of those exercises. Even if the instructor didn't assign them I could do them on my own to my benefit. But for a high school instructor, a book with a LOT of fairly good exercises has a lot of appeal over a book with few. The students often don't read the book anyway, and you can correct the information in the book in class if need be. I wonder that the many exercises and code examples are not a large part of the appeal of this text over some others. -- Sheila King http://www.thinkspot.net/sheila/ "When introducing your puppy to an adult cat, restrain the puppy, not the cat." -- Gwen Bailey, _The Perfect Puppy: How to Raise a Well-behaved Dog_ From pobrien at orbtech.com Sat Mar 16 17:41:41 2002 From: pobrien at orbtech.com (Patrick K. O'Brien) Date: Sat, 16 Mar 2002 22:41:41 GMT Subject: Which class method will be used when calling it? References: <3C9290A7.AA3931CB@ccvcorp.com> Message-ID: "Jeff Shannon" wrote in message news:3C9290A7.AA3931CB at ccvcorp.com... > > Now it becomes a bit more difficult to figure out which version of f() is > called. In Python 2.1 and earlier, the base classes are searched > depth-first, so that the call would resolve to B.f(), but if class D were > declared as D(C, B) [note reverse order of ancestors], then d.f() would > resolve to A.f() (since C has no f(), but C's parent A does). Python 2.2 > changed this, so that (in essence) a breadth-first search is done; under > 2.2, d.f() should resolve to B.f() regardless of the order that the parents > were listed when D was declared. > > (At least, I *think* I'm remembering this correctly.... ;) ) > Classic classes resolve this as they always have, even under Python 2.2. Only new style classes follow the new mechanism. Details: http://www.python.org/2.2/descrintro.html#mro -- Patrick K. O'Brien Orbtech From tdi01fhu at syd.kth.se Wed Mar 27 10:54:01 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Wed, 27 Mar 2002 16:54:01 +0100 Subject: location of gmpy, google Message-ID: >>> Skip Montanaro 03/27/02 16:42 PM >>> FREDRIK> Where can I get gmpy? >>Try searching for "gmpy" on google. I happened to find it while looking around some python pages, however, Im unable to get it to work. Anyone willing to give me some instructions on how getting something like gmpy in PythonWin is done? All help is appreciated. /Fredrik From arun at sharma-home.net Mon Mar 11 01:14:04 2002 From: arun at sharma-home.net (Arun Sharma) Date: Sun, 10 Mar 2002 22:14:04 -0800 Subject: Iterating over unicode strings In-Reply-To: References: <3C8C3136.9050507@sharma-home.net> Message-ID: <20020311061403.GA22580@sharma-home.net> On Sun, Mar 10, 2002 at 10:48:44PM -0600, Jason Orendorff wrote: > 1. Your unicode string might be wrong. > > Python doesn't know the encoding of your program, > unfortunately, so it assumes ASCII. Anything that's > not ASCII causes an error. To fix this, specify the > encoding: > > line = unicode("??????|| ?????????????????? ???????????????", 'utf-8') > > 2. print won't work. :( > > Python doesn't know the encoding of your terminal, > unfortunately, so it assumes ASCII. Any output that's > not ASCII causes an error. To fix this, specify the > encoding: > > print c.encode('utf-8') > > Hope this helps. Thanks, that solved the problem. -Arun From p.magwene at snet.net Sat Mar 9 17:05:42 2002 From: p.magwene at snet.net (Paul M) Date: Sat, 09 Mar 2002 22:05:42 GMT Subject: disipyl - a 2D and 3D Python plotting library Message-ID: DESCRIPTION: ----------- disipyl is an object-oriented wrapper around the DISLIN plotting library. DISLIN is a powerful and flexible multiplatform (Win32, Unix, Linux, etc.) library designed for displaying scientific data. DISLIN's author, Helmut Michels, has made available a DISLIN plotting extension for the Python programming language (see http://www.linmpi.mpg.de/dislin/ for more details). disipyl provides a set of classes which represent various aspects of DISLIN plots, as well as providing some easy to use classes for creating commonly used plot formats (e.g. scatter plots, histograms, 3-D surface plots). A major goal in designing the library was to facilitate interactive data exploration and plot creation. Documentation, a tutorial, and a demo program are included. The library has been tested on Win32, Linux, and FreeBSD, but I anticipate that it should work on any platform which can make use of Python, NumPy, and the DISLIN python extensions. Feedback, comments, and critique are gladly accepted (email: paul.magwene at yale.edu). VERSION: ------- This is release 0.5 of disipyl. HISTORY: ------- disipyl is a complete re-write of an earlier plotting library called pxDislin. While similar in spirit, disipyl is much more flexible and much more easier to use than pxDislin. URL: ---- You can find disipyl at: http://pantheon.yale.edu/~pmm34/disipyl.html From evebill8 at hotmail.com Sun Mar 17 17:21:33 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Sun, 17 Mar 2002 22:21:33 GMT Subject: sunstring References: <0r4l8.22204$P4.1955815@newsread2.prod.itd.earthlink.net> <3C94DCC1.748EDC18@engcorp.com> Message-ID: No, sir! I am very very new to python. I just bought the O'Reilly book today. Billy "Peter Hansen" wrote in message news:3C94DCC1.748EDC18 at engcorp.com... > Billy Ng wrote: > > > > Would anybody tell me how to do substring in python? > > Use slices. And look at the string module. > > Have you gone through the tutorials yet? > > -Peter From joonas at olen.to Thu Mar 7 02:14:32 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Thu, 07 Mar 2002 09:14:32 +0200 Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> <3C84E363.6020106@olen.to> <3C84EBED.8090607@bath.ac.uk> <3C8651E9.493CDA64@olen.to> Message-ID: <3C871358.306F01A4@olen.to> Donn Cave wrote: > > Quoth Joonas Paalasmaa : > | Simon Willison wrote: > |> Joonas Paalasmaa wrote: > |>> Simon Willison wrote: > |>>| I've written a simple Python script to scan a bunch of URLs for "live" > |>>| sites and grab the title of those pages. It works by using popen() to > |>>| call lynx and analyse the HTTP response: > |>>| > |>>| ----------------------------------------------------------------- > |>>| > |>>| command = "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~"+user+"/" > |>> > |>> > |>> Use: > |>> > |>> command=["/opt/bin/lynx","-mime_header","http://www.bath.ac.uk/~"+user+"/"] > |>> > |>> for better security. > |> > |> I'm a Python newbie :) How does that makes things more secure? > | > | If you pass a string to os.popen as the first argument, the process is > | envoiked > | by by running the argument in shell. That can cause problems if the > | string is composed from non-safe variables. Imagine situation where > | variable 'user' is "; rm -fR ~/; echo ". That causes command > | "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~; rm -fR ~/; echo /" > | to be run in shell. > | But if a list is passed to os.popen, os.popen will run a program named > | in the first item of > | the list with the rest of the list as arguments. > > TypeError: popen() argument 1 must be string, not list > > You meant os.popen2(), not os.popen(). Yes. I forgot that only os.popen2 accepts list as the first argument. - Joonas From ajs at ix.netcom.com Sat Mar 16 18:49:02 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Sat, 16 Mar 2002 18:49:02 -0500 Subject: Operator overload question Message-ID: <000001c1cdff$76345420$9e47f6d1@ArtsPortable> Given: class Complex(complex): def __mul__(self,other): other=Complex(other) t = complex.__mul__(self,other) return Complex(t.real,t.imag) __rmul__ = __mul__ def __add__(self,other): other=Complex(other) return Complex(self.real.__add__(other.real),self.imag.__add__(other.imag)) __radd__ = __add__ Then: print type(Complex(5,4) * 7) >> print type(7 * Complex(5,4)) >> print type(Complex(5,4) + 7) >> But: print type(7 + Complex(5,4)) >> Multiple choice: That the result at But is a surprise to me because I am missing: 1)Something obvious about __radd__ or general classic syntax 2)Something related to new style classes 3)Other Art From martin at v.loewis.de Sun Mar 24 17:06:53 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Mar 2002 23:06:53 +0100 Subject: 2.2 open References: Message-ID: Pearu Peterson writes: > > So open is now a file? That seems a bit odd to me. > > Correction: open is the type of file. Correction: open is file. Just try it >>> open is file 1 So open is the type of file objects. The type of file is something different: >>> type(file) Regards, Martin From logstx at bellatlantic.net Sat Mar 16 15:59:26 2002 From: logstx at bellatlantic.net (logistix) Date: Sat, 16 Mar 2002 20:59:26 GMT Subject: Help with a Python ASP C extension module ... References: <40ee0487.0203152316.70c12a49@posting.google.com> Message-ID: I've had to build some COM components that do this. There are two ways to do it. The easy way and the right way. (sorry examples are in VB, they've got these darn "corporate standards") The easy way create a function that let's you pass in the response object and capture it. Then on the script side: <% Dim foo Set foo = Server.CreateObject("foo.bar") Set foo.response = Response foo.otherMethod("ttt") ' can access foo's internal copy of response. %> The right way is to grab a reference to the Response Object via MTS. It's not really that hard, there are just a few more steps involved. Here's the code I reference for that: http://www.microsoft.com/mind/0999/vbcom/vbcomtextfigs.htm#fig14 Of course VB is nice enough to provide wierd wrapper objects to prevent you from understanding what's really going on ;) Hopefully it's a straightforward translation to Component instantiation. If you haven't dealt with COM components in C before, get ready for a rude awakening. That's what finally turned me off to C++. You have to jump through hoop after hoop after hoop just to deliver on C++'s promise of "reusable objects" -- - "Eric Vasilik" wrote in message news:40ee0487.0203152316.70c12a49 at posting.google.com... > I am writing a C extension to Python. The reason I am writing an > extension is that I believe that the implementation of > Response.BinaryWrite() in the Window's ASP extension (I am using > Active State's Python 2.1) is not releasing the global interpreter > lock. I am getting very poor performace using it and I believe that > my server is not taking advantage of writing out multiple streams > because of the global lock. > > Instead of writing out a response with: > > Response.BinaryWrite( buffer( open( fileName, 'rb' ).read() ) ) > > I am now doing the following: > > PythonExt.binaryWriteFile( Response, fileName ) > > The difference between these two is that the first calls the default > implementation of Response.BinaryWrite and the second calls an > extension I have written which reads the file and writes it out to > response, all while the interpreter lock is released. > > My problem, is I cannot find any documentation on how to get a hold of > the IResponse object from the Python Response object. I need to get > it so that I may call BinaryWrite on without going back into the > Python interpreter. > > I thought I would be able to find the source for the Response object > with the source from Active State, or the source from Mark Hammond's > win32All, but I found no references there. Any help would be > appreciated. From Oschler at earthlink.net Tue Mar 5 10:05:58 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 5 Mar 2002 10:05:58 -0500 Subject: Get reference to "owner" References: <20020305072655.GA1525@lilith.hqd-internal> Message-ID: <625h8.3294$tg2.206482@e3500-atl1.usenetserver.com> Gerhard, Excellent!!! Never expected to find a language that could do this and it something I've wanted very badly for a long time. Yes that's exactly what I meant. B knows about the A that owns it without having to artificially pass a reference of A to B during construction. Thanks again. Gerhard H?ring wrote in message news:mailman.1015314249.8983.python-list at python.org... > Le 05/03/02 ? 08:26, Gerhard H?ring ?crivit: > > Le 05/03/02 ? 01:41, Robert Oschler ?crivit: > > > I've never seen this feature in any programming language I've worked in but > > > it can't hurt to ask. Can an aggregated class object get a reference to the > > > class object that aggregates it? So if ClassAggregator contained an > > > instance of ClassAggregatee is there a Python syntax/construct that a > > > function in ClassAggregatee could use to get a reference to the instance of > > > ClassAggregator that contained it? > > > > [unfinished code] > > If I understood you correctly, this might do the trick: > > import sys > > class A: > def __init__(self): > self.b = B() > > class B: > def __init__(self): > print sys._getframe(1).f_locals['self'] > > a = A() > > It even works with Jython, so it's reasonably portable. > > Gerhard > -- > This sig powered by Python! > Au?entemperatur in M?nchen: 1.8 ?C Wind: 1.6 m/s > From pereira at cis.upenn.edu Sun Mar 10 12:18:19 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Sun, 10 Mar 2002 12:18:19 -0500 Subject: python and haskell for fun References: Message-ID: On 3/10/02 9:00 AM, in article b03e80d.0203100600.2df43d02 at posting.google.com, "Sandy Norton" wrote: > A case in point is ye olde quicksort: > > Now if that ain't purrty I don't know what is... But this may be a somewhat biased example since Python comprehensions were partly inspired by Haskell's... Dinosaurs-remind-one-of-birds-ly yours -- F From michael.neuroth at freenet.de Thu Mar 7 19:26:20 2002 From: michael.neuroth at freenet.de (Michael Neuroth) Date: Fri, 08 Mar 2002 01:26:20 +0100 Subject: undefined symbols when linking Python into a shared library References: <3C8540B5.E133D407@freenet.de> <3c863019.155813297@news.laplaza.org> Message-ID: <3C88052C.591A9CC5@freenet.de> Mats Wichmann writes: > : Traceback (most recent call last): > : > : File "", lind 2, in ? > : > : File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 35, in ? > : > : import _tkiter # If this fails your Python my not be configured for Tk > : > : ImportError: /usr/lib/python2.1/lib-dynload/_tkiter.so: undefined symbol: _Py_NoneStruct > > If this is a direct snip, and not a transcription, the problem is sa > typo: _tkiter is used instead of _tkinter Sorry, I misstyped the error message, it should be _tkinter. > : How can I verify, that this symbols are in the shared library? > > Use objdump on the shared library this works as well as "nm -D" and objdump shows that the symbol is exported: 000a7bac g DO .data 00000008 Base _Py_NoneStruct Thank you. Michael. From francis.meyvis at sonycom.com Tue Mar 5 05:59:37 2002 From: francis.meyvis at sonycom.com (Francis Meyvis) Date: Tue, 05 Mar 2002 10:59:37 GMT Subject: I've got the unicode blues References: <3c846d80.95456984@news.isar.de> Message-ID: > lines = ReadLinesFromAnything("test.reg") > file = open("test.out","wb") > file.write(codecs.BOM_LE) > for line in lines: > file.write(line.encode("utf-16le")) > file.close() > > The LE/BE codecs don't write a BOM, so they operate nicely using > sequential write. In fact, this is what the UTF-16 codec does: it > first writes the BOM, then writes the data in the chosen endianness. > > > - *much* better support for UNICODE Textfiles in python > > - a *much* better documentation on this in python. > > > > So now I already feel much better :) These will generate a single starting BOM in the 2byte unicode file f = codecs.open("test.out", "w", "utf-16") for l in lines: f.write(l) f.close() --- Kind regards, best wishes, francis meyvis From johnroth at ameritech.net Thu Mar 28 13:07:54 2002 From: johnroth at ameritech.net (John Roth) Date: Thu, 28 Mar 2002 13:07:54 -0500 Subject: problems with circular references References: Message-ID: "jimh" wrote in message news:a7tbd4$qc7$1 at web1.cup.hp.com... > I am working on python code that consist of quite a few files (about 50; > each file contains one class). All errors returned by functions are numeric > and are defined in the individual files. There is a MessageCatalog.py class > which will map these numbers into strings. This MessageCatalog.py has to > import all of the 50 other files to have access to their error numbers. So > far, so good - no problems yet. > > Here is the problem: Most of these 50 classes need to use the MessageCatalog > themselves. This means, of course, that classA imports MessageCatalog which > imports classA. This doesn't work very well. > > Does anyone have ideas on how to deal with this situation? > > Thanks, > Jim I had that (almost) exact same problem, but with commands commands instead of messages, and I didn't want to couple the command modules with a central dictionary. In fact, I wanted the entire thing to be highly modular: load the commands you wanted, and just those commands. What I wound up doing is putting the part of the command dictionary in needed by a module in that module, and putting a small routine at the end to copy it into the main driver/parser module. This worked well. The loop still exists at run time, but it doesn't exist at load time, so there isn't any module. It might be slightly cleaner to register the commands in a special purpose module that doesn't have any other function. Then it's down at the bottom of the tree, and can't cause any load time loops. Oh, well. Add it to the refactoring list... John Roth > > From kosh at aesaeion.com Mon Mar 11 03:59:54 2002 From: kosh at aesaeion.com (kosh at aesaeion.com) Date: Mon, 11 Mar 2002 01:59:54 -0700 (MST) Subject: How do you protect the source code of python applications? In-Reply-To: <3C8C6EC5.8080308@student.kun.nl> Message-ID: On Mon, 11 Mar 2002, husam wrote: > hi, > Is there a way to protect the source code of applications written with > python? Overall I would do it with a license. You can do lots of things that will take a lot of time to do and will hide it from many people but none of those methods will ever be perfect. No matter how much you obfuscate the code it can be decoded regardless of the language being used. Overall if you want to really keep your code safe then you can't give your code out. So you would want to make an app server and just give the customer a client to connect to the app server and that way noone could ever get the code for the app. Designing and building web applications http://webme-eng.com From dale at riverhall.NOTHANKS.co.uk Tue Mar 26 15:23:44 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Tue, 26 Mar 2002 20:23:44 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: "Dean Goodmanson" wrote: >"The joy of coding Python should be in seeing short, concise, readable >classes that express a lot of action in a small amount of clear code -- not >in reams of trivial code that bores the reader to death." Guido van Rossum > I didn't see the original post but I *really* hope this was said in jest. Or is Guido getting writing software and writing novels confused? -- Dale Strickland-Clark Riverhall Systems Ltd From henrik.motakef at web.de Sun Mar 3 07:28:20 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 03 Mar 2002 13:28:20 +0100 Subject: regular expression for nested matching braces References: Message-ID: <86d6ylrg2j.fsf@apo.hmotakef.int> "Paul M" writes: > Is it possible to create a regular expression for searching for the > outermost matching braces in a string in which there may be nested braces? Not really. However, there is a Python wrapper for sgrep (structured grep) that could be useful. Sorry, I don't have a link. Try Google or Freshmeat. hth Henrik From kragen at pobox.com Tue Mar 19 02:18:24 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 19 Mar 2002 02:18:24 -0500 Subject: psyco, jython, and python speed tests References: Message-ID: <83hendkou7.fsf@panacea.canonical.org> sandskyfly at hotmail.com (Sandy Norton) writes: > o Developments like psyco should be encouraged and supported because > ultimately accelerating python is a good thing: it takes away one > usual criticism of those who have _never tried_ to develop in > python. For those who have, the productivity benefits, of course, > by far outweigh any so-called 'performance' issues. This is unjustifiably glib. Lots of programs don't need to run fast. Some programs do need to run fast. Some programs justify significant work to get them to run fast. Accelerating Python is a good thing not because of "so-called 'performance issues", but because in some cases, there really *are* performance issues that rule Python out. From tl_news at nexgo.de Thu Mar 14 07:54:22 2002 From: tl_news at nexgo.de (Tino Lange) Date: Thu, 14 Mar 2002 13:54:22 +0100 Subject: does Python support some kind of "casting" Message-ID: Hi! Some days ago I posted two questions here in one message. The first was answered, the other not - maybe because the "Subject" line of the Message was related to the first question.... Here's my other question again - with an appropiate "Subject" line in the Header. I'm playing with the new 2.2-feature of subclassing builtin types. Especially I built an "MaxSizedList" that is a list, but it cannot grow over a maximum size. It throws the first elements away if new elements are appended. Now I wanted to transfer the MaxSizedList on request via XML-RPC. But xmlrpclib only knows about "real" lists, not subclassed lists. And there seems to be no interface to add dump()-Methods for other data types, or? So the best solution is to transport an object like return list(newlist) But I guess this makes a temporary copy of my MaxSizedList just for the XML-RPC-transport, or? So it's horrible inefficient? Is there no other way to deal with subclassed types in this lib besides patching the xmlrpclib to know my MaxSizedList? Is there a kind of casting to a "normal" list possible without making a completely new list from the MaxSizedList-Content? Thanks a lot for your help! Tino From mnations at airmail.net Mon Mar 18 18:38:39 2002 From: mnations at airmail.net (Marc) Date: 18 Mar 2002 15:38:39 -0800 Subject: Checkboxes and Tortured Logic Message-ID: <4378fa6f.0203181538.5cde340e@posting.google.com> I know there's got to be a better way to do this than the way that I found. But the only way I've been able to succesfully retrieve a value from a checkbox (using the scant documentation I've been able to find) looks something like this: self.modVar = StringVar() self.testModules = [ ('EQPT Provisioning Test Cases', 0, 0, NORMAL), ('OCN Provisioning Test Case', 1, 0, NORMAL), ('STS Provisioning Test Case', 2, 0, NORMAL)] for module, row, col, status in self.testModules: setattr( self.modVar, module, StringVar() ) self.modButton = Checkbutton(modFrame, text=module, state=status, anchor=W, variable = getattr( self.modVar, module)).grid(row=row, col=col, sticky=W) ... def ocnRun(self): #while self.ok: for module, row, col, status in self.gui.testModules: print "The module is=", module a = getattr(self.gui.modVar, module) print "The value is=", a #print "The variable is=", self.modButton.variable #print "The value is=", self.gui.modVar.get() print "The value is=", a.get() self.gui.slot = self.gui.list.curselection() #printAll( self.gui.ipaddr.get(), self.gui.var.get(), self.gui.list.get(self.gui.slot) ) ... ocnRun is called from the main Gui GO button which starts up a separate thread. The first snippet is in one class and the second snippet is in another. But the only way I've been able to see any value is to assign the getattr() result (which is an object of type IntVar) to a variable and then use that variable with the get() function. It doesn't work when I combine the two functions into the same line which is confusing. Also, I haven't found a way to get an "OFF" value. The only values that are returned are the "ON" values. Default ON is the value one, and I can get that value, plus manipulate it using the "onvalue" option. Default for OFF is '0', but that does not come through. Plus, I can't manipulate the default value using the "offvalue" option. Basically I just need to pass the on and off values through to the other class and have access to the result. Is there an easier way to do this. Thanks, Marc From jimd at vega.starshine.org Mon Mar 25 04:58:15 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 25 Mar 2002 09:58:15 GMT Subject: The OOM-Killer vs. Python References: <3c9e2b5f.9993062@news.t-online.de> Message-ID: In article , Chris Liechti wrote: > gerson.kurz at t-online.de (Gerson Kurz) wrote in news:3c9e2b5f.9993062 > @news.t-online.de: >> I have a python-based SMTP server (see http://p-nand- >> q.com/shicks.htm) >> running on our server, and in general it has worked flawless (since >> about nov 2001). However, in the recent week that dreaded linux OOM >> killer twice killed the python process. [The machine has 768mb ram >> call me oldfashioned but that SHOULD be enough for both Linux & >> Python to get along, really. OK, its running KDE, and has only 256mb >> for swap, but still...] > maybe you have some other leaking app and the OOM killer just picks > the largest. if you want a reliable server i wouldn't use it as > workstation too :-) >> Anyway, even though I believe that this is more of a fault of the >> Linux Kernel VM quality than the script (the system has been >> running fine for months and now two kills in one week - that smells >> fishy About two years ago (March of 2000) there was a huge flamewar on the Linux kernel mailing list (LKML) about a proposed set of patches to allow users (admins) to disable "overcommit." When your program uses malloc (implicitly done by your Python processes, of course) then the Linux kernel will return success even if there isn't physically enough memory+swap to guarantee that the whole block of memory can be supplied. This is called "overcommit" (and is common among UNIX and other general purpose operating systems). Searching Google's Linux pages on "overcommit" or "disable overcommit" or even "disable overcommit" and "patch" will quickly bring up various subsets of that discussion. Unfortunately I don't know the current status of Linux sysctl to control the "overcommit" vm features. I'm cross posting this to c.o.l.d.s (comp.os.linux.dev.system) in hopes of getting a clue. I see a /proc/sys/vm/overcommit_memory entry on my 2.4.9 kernel which might be either to a magic sysctl node. You might be able to echo -1 > into that node (virtual file) to disable overcommit. That should cause malloc()'s to fail when there isn't enough RAM+swap to satisfy a request. Note that this might not actually solve your problem. It should prevent the OOM killer from becoming active (since you won't truly be "out-of-memory") but might cause programs to abend (abnormally terminate themselves) when their malloc's return -ENOMEM. If you have swap active it also might make the system go into vm thrashing and it might make the whole system seem much worse because many of the (formerly innocuous) malloc()s will be going unsatisfied. Personally I think the various libraries, compilers and applications which are blindly allocating far more memory then they actually use are really the heart of the whole overcommit problem. That might not be Python (or it might be indirectly due to Python's use of some libraries on your system, possibly it could be glibc and libm bloating). Unfortunately memory is a shared resource, so it only takes one bad appl. (so to speak) to ruin the whole basket for all of us. From bokr at oz.net Fri Mar 29 20:03:46 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Mar 2002 01:03:46 GMT Subject: Slice objects. How to apply them to strings? References: <04g9au4kn4dtg92584l12n0ut001c7rb9m@4ax.com> Message-ID: On Fri, 29 Mar 2002 19:29:25 +0000, Dale Strickland-Clark wrote: >Dale Strickland-Clark wrote: > >>I'm using Python 2.1 here but this still seems to apply on 2.2 >> >>I have a little string-based class which needs to emulate strings for >>most things. This includes slicing. >> >>So I need a __getitem__ magic method. >> >>This will get passed a slice object. >> >>How am I supposed to translate this into a string slice? >> >>This seems to be the tidiest I can come up with and it's a mess: >> >>def __getitem__(self, item): >> if item.step: >> return self.s[item.start: item.stop: item.step] >> if item.start: >> return self.s[item.start: item.stop] >> return self.s[item.stop] >> >>If 'item' is a slice object, shouldn't I just be able to say: >> >> self.s[item] >>? >> >>Wouldn't this be really sensible? >> >>What's worse, is that I can't even do this: >> >>import operator >>operator.getitem(self.s, item) >> >>Somebody please tell me I'm being dim and I've missed something. How >>do you apply a slice object to a sequence? >> >>Thanks > >Can anyone shed any light on this for me? > Why not subclass str? Here is a toy: >>> class SX(str): ... def __getitem__(self,item): ... if type(item) is int: return 'SX<'+str.__getitem__(self,item)+'>' ... return 'SX<:<'+''.join( ... [str(self)[i] for i in xrange(item.start,item.stop,item.step)] ... )+'>:>' ... def __getslice__(self,i,j): ... return 'SX<<'+str.__getslice__(self,i,j)+'>>' ... >>> s=SX('0123456789') >>> s '0123456789' >>> s[1] 'SX<1>' >>> s[1:8] 'SX<<1234567>>' >>> s[1:8:2] 'SX<:<1357>:>' However, to be robust, I guess one must watch for slices and tuples in __getitem__ to cover all the variety, and perhaps expect just straight start,stop in __getslice__ ? (Can someone verify the latter?) >>> class C: ... def __init__(self,*v): print 'init',v ... def __getitem__(self,*i): print 'getitem',i ... def __getslice__(self,*slc): print 'getslice',slc ... >>> c=C('012345') init ('012345',) >>> c[1] getitem (1,) >>> c[1,2] getitem ((1, 2),) >>> c[1:2] getslice (1, 2) >>> c[1,2,3] getitem ((1, 2, 3),) >>> c[1:2:3] getitem (slice(1, 2, 3),) >>> c[1:2,3:4] getitem ((slice(1, 2, None), slice(3, 4, None)),) >>> c[1:] getslice (1, 2147483647) >>> c[:2] getslice (0, 2) >>> c[:2,3] getitem ((slice(None, 2, None), 3),) >>> c[:2,3:] getitem ((slice(None, 2, None), slice(3, None, None)),) Regards, Bengt Richter From dreed at capital.edu Wed Mar 13 07:54:36 2002 From: dreed at capital.edu (Dave Reed) Date: Wed, 13 Mar 2002 07:54:36 -0500 Subject: MySQL Library or Interface? In-Reply-To: (stephen@stephencox.org) References: Message-ID: <200203131254.g2DCsaP26752@localhost.localdomain> > From: "Stephen Cox" > > Is there a MySQL library or some kind of framewrok available for Python? http://www.python.org/topics/database/modules.html Dave From peter at engcorp.com Wed Mar 6 20:07:59 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Mar 2002 20:07:59 -0500 Subject: Threading help? References: <3C867E68.B4C3FED2@accessforall.nl> <20020306132612.4a5d756a.logiplexsoftware@earthlink.net> Message-ID: <3C86BD6F.9D258DA7@engcorp.com> Cliff Wells wrote: > > On Wed, 6 Mar 2002 13:26:12 -0800 > Cliff Wells wrote: > > > The approach I would take, based upon the information given, is to have > > thread A retrieve the data every .1s (using time.sleep), when the data > is > > retrieved, put it on a Queue and go back to sleep. Thread B blocks on > the > > Queue until data is available. When data becomes available, B processes > > that data and place it on a second Queue for thread C (thread C handling > > HTTP requests) to deal with. > > Hm. Okay, I had to reconsider this. Clearly if the processing is slower > than .1s and data is being added to it every .1s, the Queue is going to > endlessly grow as more data is added to it. If this is the case, it might > make sense to have more than one consumer thread (B) doing the processing. I might be missing something, but I don't see how adding another thread (with a slight extra overhead associated with it) would actually increase performance for what I infer is CPU-bound processing in thread B. Threads don't add performance capacity, they remove it! (Or is B blocking on something like a socket, thus slowing it down?) -Peter From thomas at weholt.org Sun Mar 17 18:42:52 2002 From: thomas at weholt.org (Thomas Weholt) Date: Sun, 17 Mar 2002 23:42:52 GMT Subject: Format profile-data into "nice" HTML ? Message-ID: <0S9l8.11822$TU3.312633@news4.ulv.nextra.no> I need to show the results of code-profiling in a web-page. Parsing the data in pstats-objects seem complicated and I was wondering if anybody has ever done this before. If not, can anybody tell me the easiest way to do this? The pstats-module was .... well, not that easy to understand. I was hoping to be able to put the results into a nicely formatted table, but a plain print like the one it produces now will also do the trick. I just don't seem to be able to capture the output of the print_stats-method. Any help appreciated. Best regards, Thomas Weholt From bokr at oz.net Sun Mar 17 15:06:29 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Mar 2002 20:06:29 GMT Subject: a text processing problem: are regexpressions necessary? References: Message-ID: On 17 Mar 2002 05:29:18 -0800, sandskyfly at hotmail.com (Sandy Norton) wrote: >Hi, > >I thought I'd share this problem which has just confronted me. > >The problem > >An automatic way to tranform urls to articles on various news sites to >their printerfriendly counterparts is complicated by the fact that >different sites have different schemes for doing this. (see examples >below) > >Now given two examples for each site: a regular link to an article and >its printer-friendly counterpart, is there a way to automatically >generate transformation code that is specific to each site, but which >generalizes across all article urls within that site? > >Here are a few examples from several online publications: > >http://news.bbc.co.uk/hi/english/world/africa/newsid_1871000/1871611.stm >http://news.bbc.co.uk/low/english/world/africa/newsid_1871000/1871611.stm > >http://www.economist.com/agenda/displayStory.cfm?Story_ID=1043688 >http://www.economist.com/agenda/PrinterFriendly.cfm?Story_ID=1043688 > >http://www.nationalreview.com/ponnuru/ponnuru031502.shtml >http://www.nationalreview.com/ponnuru/ponnuruprint031502.html > >http://www.thenation.com/doc.mhtml?i=20020204&s=said >http://www.thenation.com/docPrint.mhtml?i=20020204&s=said > >I'm kinda heading in the direction of attempting to generate regular >expressions for each site... But I'm a bit apprehensive about doing >this. Is there a more pythonic way to approach this problem? > >Any advice would be appreciated. > My approach would be to write a function that accepts an example pair of urls as above and returns a functor that will transform the display version to the print version. A functor is a callable instance of a class, and a class instance can contain data as well as the method (__call__) that gets called when you use the instance as a function. Thus you can store rules, regexes or whatever necessary to do the job in the class instance, once your function has those generated. E.g., your function could pass the rules it determined to the class constructor and then return the instance. Of course you design your functor class to support what you need for the above. You might want to put the functors in a dictionary according to site domain (key modified if need be to distinguish different rules generated for different parts of the same site). E.g., if you have disp_url and print_url, with one rule per site, you could store it something like site_dom = disp_url.split('/')[2] # assuming "http://site_dom/..." funcdict[site_dom] = get_url_rewrite_functor(disp_url, print_url) and then later use the stored rules to convert some new display url by site_dom = new_disp_url.split('/')[2] new_print_url = funcdict[site_dom](new_disp_url) Now it's just a matter of writing get_url_rewrite_functor ;-) To analyze the differences between urls, I think I would start by splitting them with re.compile(r'([/?])') and then deal with the differing pieces one by one. I might split those further by numbers and periods (re.compile(r'([\d.]+)') and/or scan them for matching prefix and suffix sequences. It will probably be easier to store rules as a list of (fcn,args..) tuples to operate on selected items of the first level split than generating a single glorious regex substitution, but OTOH it might not be that bad. You'll also have to decide whether to treat url elements that match in examples as constants to verify or variables to pass through. Some are more obvious than others. For a start you can probably pass everything through that you don't generate a change rule for, but it's good to flag violations of your assumptions. Your best final approach may depend on what your performance requirements are, but you're probably better of optimizing later, after you get some play time with the algorithms. BTW, give your functor class a __str__ method to return a printable representation of its rules in some form, to help debugging. Anyway, that's how I'd start out. YMMV. HTH, Regards, Bengt Richter From ajs at ix.netcom.com Fri Mar 15 12:51:48 2002 From: ajs at ix.netcom.com (Arthur) Date: Fri, 15 Mar 2002 12:51:48 -0500 Subject: random appreciation Message-ID: I had wrttien: >And yes, it *is* nice not to have to worry about where >self.imag/self.real might leave me. Except of course for the fact the formula is dead wrong, and oh yeah divide by zero, and.... details, details... Meanwhile studying Guido's Type/class unification paper at www.python.org/2.2/descrintro.html I'll get there. Art From usenet at thinkspot.net Sun Mar 17 17:52:30 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 14:52:30 -0800 Subject: Where to download bugfix for email Module? References: Message-ID: On Mon, 18 Mar 2002 00:55:26 +0300, Oleg Broytmann wrote in comp.lang.python in article : > On Sun, Mar 17, 2002 at 09:36:10AM -0800, Sheila King wrote: > > (1) stability. Can I expect this latest code to be stable? Somehow I would > > think that would be questionable with late releases? > > No, you have to learn development history (CVS is *developer's* tool!) > and checkout latest stable release. Arggh! I sorta wanna do developer-type things, but I'm not sure I want to be a *real* developer. Well, I'll let the idea warm up over time... > I heard that Brry is going to release an archive of a stable version... > don't know *when*. I suspect the usual time - Real Soon :) LOL. > > > (2) distribution. If I want to distribute code that I'm developing, and I > > use the latest CVS releases to develop my code, such that my code relies on > > these CVS releases, how do I distribute code to others who are running the > > standard 2.2 install? > > The simplest (though not the best) solution would be to distribute a > copy of the email package with your code. You know, Python inserts the path > to your application in the beginning of sys.path, so upon "import email" > your copy of the package will be imported, and not standard package. Thanks for the suggestion. Out of curiousity...what is the *best* (or better) method??? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From bokr at oz.net Sat Mar 23 15:59:03 2002 From: bokr at oz.net (Bengt Richter) Date: 23 Mar 2002 20:59:03 GMT Subject: how do i get RGB from HEX? References: Message-ID: On Fri, 22 Mar 2002 16:49:24 +0000, Robin Becker wrote: >In article , G. Willoughby > writes >>Hi, >> i have been trying to do this for to long now, i know there is an easy >>way, please somebody put me out of my misery! i need to get the RGB value of >>a HEX number (eg, #DCDCDC). can anyone help? >> >>thanks, >> >>G. Willoughby >> >> >split into pairs after stripping the # > >>>> def rgb(h): >... n = eval('0x'+h[1:]) >... return (n>>16)&0xff, (n>>8)&0xff, n&0xff >... >>>> rgb('#DCDC0a') ,-^^ | ??? | vvv >(220, 220, 220) >>>> rgb('#DCDC0a') >(220, 220, 10) >>>> > >I'm sure there's probably some better way, but the above works. A little better ;-) Avoiding eval when possible, e.g., >>> def rgb(h): ... n = int(h[1:],16) ... return (n>>16)&0xff, (n>>8)&0xff, n&0xff ... >>> rgb('#DCDCDC') (220, 220, 220) >>> rgb('#DCDC0a') (220, 220, 10) >>> rgb('#0a') (0, 0, 10) Regards, Bengt Richter From m.faassen at vet.uu.nl Sat Mar 9 06:07:00 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 9 Mar 2002 11:07:00 GMT Subject: The language vs. the environment References: <23891c90.0203071057.57204175@posting.google.com> <23891c90.0203080727.30419fd8@posting.google.com> Message-ID: Tom Good wrote: [snip] > This skill level point system sounds like it could be the basis of a > Python Role-Playing Game. "My Python Wizard character just gained a > level. Now which statistic should I increase: Python Internals, > ZOPE, Generators, or PEPs? ZOPE would help me in combat against > web-based monsters, but I'll recover hit points more quickly with > Generators . . ." See also: http://www.twistedmatrix.com/users/jh.twistd/python/moin.cgi/PythonRolePlayingGame Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From cs1spw at bath.ac.uk Tue Mar 5 11:01:51 2002 From: cs1spw at bath.ac.uk (Simon Willison) Date: Tue, 5 Mar 2002 16:01:51 GMT Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> <3C84E363.6020106@olen.to> Message-ID: <3C84EBED.8090607@bath.ac.uk> Joonas Paalasmaa wrote: > Simon Willison wrote: > >> I've written a simple Python script to scan a bunch of URLs for "live" >> sites and grab the title of those pages. It works by using popen() to >> call lynx and analyse the HTTP response: >> >> ----------------------------------------------------------------- >> >> command = "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~"+user+"/" > > > Use: > > command=["/opt/bin/lynx","-mime_header","http://www.bath.ac.uk/~"+user+"/"] > > for better security. I'm a Python newbie :) How does that makes things more secure? From jochen at unc.edu Tue Mar 19 20:51:32 2002 From: jochen at unc.edu (Jochen =?iso-8859-1?q?K=FCpper?=) Date: 19 Mar 2002 20:51:32 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tue, 19 Mar 2002 20:20:36 -0500 Tim Peters wrote: Thanks for the quick answer. The problem is resolved. Tim> [jochen at bock.chem.unc.edu] >> [1] If it is in there, it doesn't work for me with current python cvs >> branch release22-maint. I still have to manually add -lieee. >> (RedHat-7.0 with current updates.) Tim> I don't know what "current" meant to you at the time you wrote this. About 20:00 (8:00pm) EST today, March 19. Tim> Tim> Michael Hudson did backport the patch into 2.2.1c1, which Tim> Tim> was released yesterday. So please try 2.2.1c1, and if you Tim> Tim> still have a problem, file a bug report about it on Tim> Tim> SourceForge. 2.2.1 final is expected in about a week. Well, changing cvs from release22-maint to r221c1 helps. That is, everything seems to work fine with the cvs sources tagged r221c1. Then, is it really necessary to mess up the cvs tags so much? Why isn't it possible to have a single python-2.2 branch which one could follow to get all the stuff that's incorporated into that version? [1] There are huge differences between release22-maint and r221c1, it seems from the number of patches applied when going from one to the other. But then some files are in the same (non-main) branch. ??? Thanks for all your work, and thank you for the quick help again. Greetings, Jochen - -- University of North Carolina phone: +1-919-962-4403 Department of Chemistry phone: +1-919-962-1579 Venable Hall CB#3290 (Kenan C148) fax: +1-919-843-6041 Chapel Hill, NC 27599, USA GnuPG key: 44BCCD8E -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6-cygwin-fcn-1 (Cygwin) Comment: Processed by Mailcrypt and GnuPG iEYEARECAAYFAjyX6yYACgkQiJ/aUUS8zY76QwCdGZsJd1b+0qJ19LJ5TlvwI5fP kbcAniNe/5eiPnEUfGbddLCpyYD1+gmr =fLmk -----END PGP SIGNATURE----- From dysfate at gmx.de Thu Mar 21 05:43:45 2002 From: dysfate at gmx.de (Johannes Stiehler) Date: 21 Mar 2002 11:43:45 +0100 Subject: FastCGI Message-ID: Is there anybody out there who uses python together with fastcgi for realizing large scale applications. And if so, which FastCGI-Wrapper is the most recommendable? The ones I've looked at so far are: jonpy, fcgi.py, thfcgi.py. Documentation seems to be lacking for most of them and jonpy only works with python 2.2 and doesn't seem very flexible. Johannes -- _____________________________________________________________________________ Johannes Stiehler stiehler at cis.uni-muenchen.de Centrum f?r Informations- und Sprachverarbeitung 089/2180-9706 Ludwig-Maximilians-Universit?t Oettingenstr. 67 Systemverwaltung & Anwendungsbetreuung 80538 M?nchen From peter at engcorp.com Sat Mar 9 22:57:42 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Mar 2002 22:57:42 -0500 Subject: should i learn it first ? References: Message-ID: <3C8AD9B6.5CEE7588@engcorp.com> "G. Sumner Hayes" wrote: > [snip stuff] > I think a good progammer should master at least one statically typed > functional language (ocaml is my preference, other examples are ML, > Haskell), one high-level dynamic language (Python, or Ruby, Smalltalk, > etc) and C for pragmatic reasons. That gives some exposure to many > different kinds of programming. > > After that, Lisp, Prolog, and eiffel are worth a look (not necessarily > master) from a mind-expansion POV (and some assembly language) and from > a pragmatic POV Perl, Java, and C++ (on Windows) or Objective C (on Mac) > or the Unix scripting environment (awk, sed, [k]sh, etc) on Unix. I agree with much of what you say, especially the "consider skipping C++ and just learn C part", but _what_ pragmatic point of view is it that has one learning Perl, Java, or C++ when one uses Python already? Not dissing those languages, but when would you really need them? Or were you thinking strictly from the "job market pragmatism" POV? -Peter From vinay_sajip at yahoo.co.uk Thu Mar 14 21:58:42 2002 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 14 Mar 2002 18:58:42 -0800 Subject: ANN: Logging Module for Python conforming to PEP 282, first release Message-ID: <2e37dc1.0203141858.54408796@posting.google.com> I've just made available the first release of a logging module for Python. It broadly conforms to PEP 282(see http://python.sourceforge.net/peps/pep-0282.html - though that is still a work in progress). The distribution contains simple examples such as logging to console, file and streaming sockets. The simplest example might be # -- app.py --------------------- import logging logging.info("Starting...") logging.warn("Nothing to do!") logging.info("Done...") # -- end ------------------------ and logging levels DEBUG, INFO, WARN, ERROR, and FATAL are supported. Handling of exception information (tracebacks) is supported. Plus a whole lot more! Levels, Loggers, Handlers, Formatters, Filters... The documentation can be found at http://www.red-dove.com/python_logging.html Development status is pre-alpha but it has been tried out (I won't say "tested" :-)) on 1.5.2 and 2.1.1, Windows platforms. I'm dying to get feedback so please try it out! You can email me via the link on the documentation page, or give feedback via comp.lang.py if you deem it appropriate. Thanks & Regards Vinay Sajip Red Dove Consultants Ltd. From tejarex at yahoo.com Fri Mar 15 10:44:47 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 15 Mar 2002 15:44:47 GMT Subject: Connecting to a Gnutella-network References: Message-ID: "Thomas Weholt" wrote in message news:PCnk8.84$5Kn.171039232 at news.telia.no... > Hi, > > I've looked at the Gnutella Protocol, v.0.4, and wondered about trying to > create an implementation in python. I'm a newbie when it comes to this sort > of thing, but have created several simple to complex server types of > applications using SocketServer and its friends like BaseHTTPServer etc. > > Has anybody tried to do this before? Does anybody have pointers for newbies > like me in such a project ( how to start, how to connect to nodes on a > gnutella network etc. ) > > I'll be glad for any pointers you might have. try google.com: Python Gnutella From sholden at holdenweb.com Wed Mar 6 07:23:49 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 6 Mar 2002 07:23:49 -0500 Subject: mx package References: Message-ID: <6Tnh8.355581$n73.11380721@atlpnn01.usenetserver.com> Or look on www.egenix.com, whene Marc-Andre Lemburg's Python modules are pointred to. This will eventually be the standard URL, I believe, but there's at least a link at the bottom of the page. regards Steve -- "Case Van Horsen" wrote in message news:Lzlh8.21871$e07.4404 at sccrnsc01... > > "Colin Fox" wrote in message > news:pan.2002.03.06.01.23.47.195291.3038 at crystalcherry.com... > > I'm trying to work with Zope and Postgres, and one of the > > packages I'm trying to install (psycopg) requirs mxDateTime, which in > > turn requires mx. > > > > I can't find any mention of this 'mx' package anywhere. > > > Try searching Google with "mxDateTime". mxDateTime is part of the Base set > of tools, which is the mx package. > > Case > > From kkto at csis.hku.hk Tue Mar 26 00:53:59 2002 From: kkto at csis.hku.hk (Isaac To) Date: 26 Mar 2002 13:53:59 +0800 Subject: Indentation problem References: <7isn6o9fld.fsf@enark.csis.hku.hk> Message-ID: <7ieli7an7s.fsf@enark.csis.hku.hk> >>>>> "Skip" == Skip Montanaro writes: Isaac> I'd rather suggest to have a Python-specific indentation command Isaac> in Emacs that will "reindent a region in a way that fits the Isaac> current indentation style and fit in the current context, but Isaac> retain the original meaning". This really shouldn't be that Isaac> difficult. Anyone will try his elisp skills? Skip> Check out python-mode: Skip> http://www.python.org/emacs/python-mode/ Skip> It already has key bindings C-c > and C-c < which indent or dedent Skip> the selected region by the indentation delta. Works like a charm. This is somewhat close to what I say, but a little bit off: it won't reindent to the correct tab width. E.g., if you have the following def f(a): print("Trying " + a) if (a <= 0): return 1 else return a * f(a-1) print("Done") and you try to use the C-c > command, you end up with def f(a): print("Trying " + a) if (a <= 0): return 1 else return a * f(a-1) print("Done") It still works, but it doesn't look nice. What I want is a real reindentation which understand how Python reads indentation, making it def f(a): print("Trying " + a) if (a <= 0): return 1 else return a * f(a-1) print("Done") Yes, it is very Python specific. Regards, Isaac. From dgallion1 at yahoo.com Sun Mar 10 18:51:44 2002 From: dgallion1 at yahoo.com (Darrell) Date: Sun, 10 Mar 2002 23:51:44 GMT Subject: Zope stdin References: <3C8BECF0.30207@void.si> Message-ID: http://www.zope.org/Members/haqa/ZCGI Janez Jere wrote: > HHi, > could anyone help me port my simple cgi to zope script. Problem which I > am unable to solve is reading posted raw data (legacy client posts a xml > document to my cgi and expects a result). > > Among all my attempts the closest solutions are: > request.get(BODY) # BODYFILE a > and > request.stdin.read() # but it is not allowed to access read method. > > #echo cgi > import sys, os > length = os.environ['CONTENT_LENGTH'] > print 'Content-Type: text/plain' > print > print sys.stdin.read(int(length)) > > Thank for help. > Janez From grey at despair.dmiyu.org Thu Mar 7 21:13:22 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 08 Mar 2002 02:13:22 -0000 Subject: PEP 284, Integer for-loops References: <3C86D7CA.F53189AE@cosc.canterbury.ac.nz> <3C881016.FE73EDCA@cosc.canterbury.ac.nz> Message-ID: On Fri, 08 Mar 2002 14:12:54 +1300, Greg Ewing wrote: > If someone can present a realistic problem requiring > a loop of that sort, I may be able to suggest something. Stop that! This is usenet! Reason and logic are not allowed! -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From aahz at pythoncraft.com Thu Mar 28 22:35:47 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2002 22:35:47 -0500 Subject: The Python Way References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: In article , Joel Bender wrote: > >Thinking of automatic locking concepts, has there been a PEP for >synchronized objects like Java? > > class Snorf: > def __init__(self): > self.lock = lock.lock() > > def doSomething(self,x) synchronize(self.lock): > code > >It would be nice if the synchronize parameter could be an instance, >class or module lock. There was some discussion of this in the past month (can't remember if it was c.l.py or python-dev), but no PEP. Actually, the discussion came up with something a bit more general, along the lines of pre- and post-code: class MyLock: def start: def finish: using MyLock(): The using construct would automatically call the start() and finish() methods of the MyLock() instance, no matter what exceptions got raised in . -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From chris.gonnerman at newcenturycomputers.net Mon Mar 4 11:54:50 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 4 Mar 2002 10:54:50 -0600 Subject: Can somebody kill getpathp for me? References: Message-ID: <006601c1c39d$4e1d2820$0101010a@local> ----- Original Message ----- From: "Tim Peters" > [Tim] > > If, e.g., I set PYTHONHOME to \Python22, then execute python while *in* > > my \Python21 directory (these both referring to PythonLabs distros), > > then Python 2.1.2 comes up with sys.path pointing entirely at Python 2.2 > > directories. This is insane, but shows that PYTHONHOME works the way > > getpathp.c says it works. > > [Mark Hammond] > > insane by design ;) PYTHONHOME was supposed to be a global override. > > What's insane is that *I* would do such a thing, not that PYTHONHOME > believes me. It's great that PYTHONHOME believes me. But you still get the path elements from add-on libraries as well. PYTHONHOME doesn't work for me. > The other form of insanity is that there is no "global override" for *all* > of sys.path. Indeed, the lack of a global, no-kidding, I-really-mean-it, > don't-you-dare-try-to-outguess-me-at-all override is exactly Chris's > problem. Yup. Why don't we have such a thing? > > ... > > Or, use MSVC or some other resource editor to change the single string > > resource in the compiled Pythonxx.DLL (ie, no need to rebuild the DLL). > > This will cause a different registry key to be used (by the core, and > > also by extensions that are registry aware). > > Hmm. In the absence of a global no-kidding whole-sys.path override, maybe > someone would like to contribute a Python script to fiddle the DLL. *That* > should end this thread . I ended up changing two registry key values in the DLL using a hex editor. It's a hack, but it works for me. From nospam at bigfoot.com Mon Mar 18 16:23:22 2002 From: nospam at bigfoot.com (Gillou) Date: Mon, 18 Mar 2002 22:23:22 +0100 Subject: How to "hook" print statement. Message-ID: My problem (Windows)... I get text in cp1252 (sampled from a file) I want to print to the console. For this I need to recode this text in cp850 before printing. But if the stdout is redirected to a file, I need to keep it in cp1252 encoding. They got strange ideas at MS to hve 2 different encodings for Windows and DOS console mode. Any clue to have this done as transparently as possible ? Thanks in advance. --Gilles From akuchlin at crystal.mems-exchange.org Tue Mar 19 09:39:07 2002 From: akuchlin at crystal.mems-exchange.org (A.M. Kuchling) Date: 19 Mar 2002 14:39:07 GMT Subject: Java and Python References: Message-ID: In article , Steven Majewski wrote: > Nobody supports "Java", although often someone supports particular > implementations of Java. ( Sun supports J2SE SDK, Apple supports For some definition of "supports". Back in December I ran into a Java VM bug that was reported to Sun in 1999 but doesn't seem to be fixed in either the VM in Netscape 6.2 or in IBM's 1.3 JVM. See my Dec. 18th entry at http://www.amk.ca/diary/2001/dec.html. --amk (www.amk.ca) Nothing I've ever written has reached 1.0. -- Greg Ward at IPC7, on using small version numbers From phd at phd.pp.ru Thu Mar 28 07:59:38 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 28 Mar 2002 15:59:38 +0300 Subject: Zope Install probs on Mandrake 8.2 In-Reply-To: ; from bosahv@netscapenospam.net on Thu, Mar 28, 2002 at 05:16:38AM +0000 References: Message-ID: <20020328155938.H11101@phd.pp.ru> On Thu, Mar 28, 2002 at 05:16:38AM +0000, Bo Vandenberg wrote: > "python wo_pcgi.py" fails building the extension modules saying "cannot stat > `/usr/lib/python2.2/config/Makefile.pre.in': No such file or directory. Zope is incompatible with Python 2.2 yet. Use Pythgon 2.1.2. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From max at alcyone.com Thu Mar 7 16:54:55 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 07 Mar 2002 13:54:55 -0800 Subject: [GERMAN] "ziegenproblem" References: <7x3czc87qq.fsf@ruckus.brouhaha.com> Message-ID: <3C87E1AF.6F18B426@alcyone.com> Paul Rubin wrote: > Once you do this a few times, you will understand the paradox. Of course, the Monty Hall problem isn't a "paradox" in the mathematical sense, it's just a somewhat counterintuitive result. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From mwh at python.net Fri Mar 22 04:51:28 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 22 Mar 2002 09:51:28 GMT Subject: __file__ for relative imports References: Message-ID: Ken Seehof writes: > > Robin Becker writes: > > > > > Is there an obvious reason why modules imported from the current > > > directory don't have an absolute pathname for __file__? > > > > No. I think there's a bug on sf about this. > > > > It would be a bit of a pest to implement, I think, but I may be > > missing something. > > > > Cheers, > > M. > > I keep bumping into that one too. I can't think of any advantage > for the current semantics, so I am submitting a PEP. I didn't see > a bug in sf or an existing PEP, but I might have missed something > so please let me know. Seems like a PEP is more appropriate than > a bug report though. It's here: http://www.python.org/sf/415492 > I can't think of any reason for it to be difficult to implement. > Seems like the code that assigns to __file__ in the first place > could simply call abspath(), which should give correct results at > load time. Now explain how you import os.path. Cheers, M. -- ... when all the programmes on all the channels actually were made by actors with cleft pallettes speaking lines by dyslexic writers filmed by blind cameramen instead of merely seeming like that, it somehow made the whole thing more worthwhile. -- HHGTG, Episode 11 From loewis at informatik.hu-berlin.de Thu Mar 7 10:00:08 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 07 Mar 2002 16:00:08 +0100 Subject: hash(unicode(string)) == hash(string) sometimes References: <7dee885c.0203051843.36efa5c2@posting.google.com> <7xvgcabcti.fsf@ruckus.brouhaha.com> Message-ID: Skip Montanaro writes: > Veering off on a tangent, the question of raw_input failing for > latin-1 input came up on python-help in the last day. The suggested > solution was to change the system default encoding. If not that, > then what? Depends on what the problem is. In a terminal, raw_input() works fine for me. In IDLE, I'd say there is a bug somewhere. I'm not sure what it is: either raw_input should be allowed to return Unicode strings (which I'd like more), or IDLE should convert to the 'terminal encoding' which, on Windows, should be "mbcs". If there is a bug, it is ok to work around it with any means you find. It would be better to report it to SF, though. Regards, Martin From martin at v.loewis.de Sun Mar 31 05:16:54 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 12:16:54 +0200 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> Message-ID: "John Roth" writes: > I make it optimistically 180 functions. Given the reasonably > high quality of the standard library, "return None" almost > certainly means that the function does not have a return value, > not that the return value should be treated as False. Notice a subtlety, though: In a high-quality library, if the *function* has no return value, the return statement should be just "return". I'd always assume that the function would normally return an object, and that "return None" indicates that no object is available in this case. A quick glance shows that this indeed seems to be the case in the majority of the cases. Regards, Martin From jkraska at san.rr.com Sun Mar 3 16:27:31 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 03 Mar 2002 21:27:31 GMT Subject: C++, Python & Threads References: <1015181073.276455@seux119> Message-ID: >>(I need to kill threads without adding controls on them, and it >>seems not to be posible). ?? A thread should usually kill itself. This is generally accomplished by sending it a message of some kind. C// From chris.gonnerman at newcenturycomputers.net Thu Mar 7 08:58:25 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 7 Mar 2002 07:58:25 -0600 Subject: how to give an object as argument for a method References: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> <20020307101853.GA1326@lurkabove.darkstar> Message-ID: <002d01c1c5e0$2b225120$0101010a@local> ----- Original Message ----- From: "Marco Herrn" > On Thu, Mar 07, 2002 at 03:28:09PM +1300, Greg Ewing wrote: > > Marco Herrn wrote: > > > > > > hmm, do I have to implement that in _every_ method or just in > > > methods who use the 'self' statement? > > > > In every method. The instance is always passed in > > as the first parameter, so there must be a parameter > > there to receive it, even if it's not used inside > > the method. > > Is there a reason why this is just a convention? It seems (because it is > such a _strong_ convention) that this should be a real feature of the > language. I mean that there could be a reserved word "self" which is > there all the time, so that one doesn't hast to do this himself. Python is by nature a pragmatic language, and one design philosophy which is considered very important is "Explicit is better than implicit." This particular feature, namely that the first method argument is "self", is simply how it is in the language. You can use "I" as one poster suggested, or "me" as another mentioned some time ago; readability isn't harmed much. I'm pretty lazy, but four characters isn't that much work even if you have to type them over and over in some cases. Isn't it Java that uses an implicit "this" variable, or is that Javascript? Python programmers prefer explicit declarations. From peter at engcorp.com Fri Mar 29 11:18:13 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 11:18:13 -0500 Subject: chat server References: <3CA4544D.6646CB30@q-survey.be> Message-ID: <3CA493C5.6FCE20@engcorp.com> Henning Peters wrote: > > > Don't reinvent the wheel. Use asyncore.py and asynchat.py, it's > > part of the standard Python library. > > hmm, but it's fun for me to make my own way... Fun, maybe, but if you don't figure it out for yourself it won't be very fun. And if you ask for help and the suggestions are along the lines of "why bother? here's a better solution that doesn't involve us spending lots of time showing you how to write something unnecessary", then you should probably either follow those suggestions or go back and figure it out on your own, the fun way... -Peter From eric.brunel at pragmadev.com Fri Mar 29 04:47:04 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 29 Mar 2002 09:47:04 +0000 Subject: Program termination problem References: Message-ID: Garyr wrote: > I have a program that displays a Tkinter Text widget. I would like to be > able to place text in the window via the clipboard. I found the following > clipboard code in a Google post: > > import win32clipboard as clip > ... > clip.OpenClipboard(0) > if clip.IsClipboardFormatAvailable(clip.CF_TEXT): > newText = clip.GetClipboardData(clip.CF_TEXT) > textwidget.insert(END, newText) > clip.CloseClipboard() > > This works but it causes the program to hang on exit. mainloop() returns > but the DOS window is frozen. The problem is associated with the clipboard > functions; i.e., commenting the insert line has no effect. I've already noticed that mixing Tkinter with calls to win32 functions often ends up with crashing or freezing programs. To do what you want to do, you'd better use the built-in clipboard management methods in Tkinter. With these methods, what you're trying to do may be written (untested code): try: newText = yourTopLevelWindow.selection_get(selection='CLIPBOARD') textwidget.insert(END, newText) except TclError: ## Nothing or incompatible data in clipboard pass For copy operation, use the methods clipboard_clear and clipboard_append on your top-level window. HTH - eric - From peter at engcorp.com Fri Mar 29 18:18:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 18:18:45 -0500 Subject: List problem References: <3CA4E7C6.EDE85B98@engcorp.com> Message-ID: <3CA4F655.4956016@engcorp.com> Terry Reedy wrote: > > "Peter Hansen" wrote in message > news:3CA4E7C6.EDE85B98 at engcorp.com... > > Jon Cosby wrote: > > > > lword = len(firstword) > > You missed that lword *is* the length of firstword, not firstword > itself, making D'oh! I'll fall back on my claim that with inadequate commenting, it was pretty hard to figure out what was going on. ;-) From BPettersen at NAREX.com Wed Mar 13 17:51:43 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 13 Mar 2002 15:51:43 -0700 Subject: [ANN] istring 1.0.1 released; announce list created Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158D99@admin56.narex.com> > From: Bengt Richter [mailto:bokr at oz.net] > > On Wed, 13 Mar 2002 21:30:47 +0300, Oleg Broytmann > wrote: > > >On Wed, Mar 13, 2002 at 08:15:39PM +0100, Andreas Kostyrka wrote: > >> And what about: > >> db.query("""SELECT foo, bar > >> FROM %(table)s > >> WHERE rsrc_id = %(rsrc_id)d > >> AND name = '%(name)s'""" % locals()) > >> > >> pure standard Python :) > > > > This will fail if name = "O'Hara". Or name = 'Tutti"""Frutti'. > > > Ok, then how about: > --- > >>> table = 'theTable' > >>> rsrc_id = 1234567 > >>> class QEsc: > ... def __init__(self,s): self.sesc = > "\\'".join('\\"'.join(s.split('"')).split> ("'")) > ... def > __str__(self): return self.sesc > ... > > >>> for badname in ["O'Hara", 'Tutti"""Frutti']: > ... name = QEsc(badname) > ... print """SELECT foo, bar > ... FROM %(table)s > ... WHERE rsrc_id = %(rsrc_id)d > ... AND name = '%(name)s'""" % locals() > ... > SELECT foo, bar > FROM theTable > WHERE rsrc_id = 1234567 > AND name = 'O\'Hara' Except that's not how SQL is quoted (It should have been 'O''Hara'). Besides, anyone not using bound variables must be crazy -- bjorn From ajs at ix.netcom.com Sun Mar 17 19:41:22 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Sun, 17 Mar 2002 19:41:22 -0500 Subject: bug reporting Message-ID: <001301c1ce15$a444ec60$0334fea9@carol> In thread "Still same bug even with email ver. 1.2" Martin writes - >If you think you found a bug, submit a bug report. It could waste time of the developers to have to weed through false alarm bug reports. One of the roles of this list is to vet some of these issues. I had posted up behavior that I thought could be anything from my own misunderstanding of fundamentals to a bug in the core. Their was only one response on the list - to the effect that the behavior could be duplicated on his machine, with the implication that it was unanticipated behavior from his point of view as well. The issue was related to overloading operators in a class subbed from the 'complex' built-in - not exactly a high traffic lane, I suspect. Is the recommendation to submit it as a maybe bug? >If you know how to fix it, submitting a patch would be even >more appreciated. I'm holding out for check-in rights ;) Art From tim-dated-1016821077.7a095e at catseye.net Fri Mar 15 13:17:56 2002 From: tim-dated-1016821077.7a095e at catseye.net (Tim Legant) Date: 15 Mar 2002 12:17:56 -0600 Subject: Why I think range is a wart. In-Reply-To: References: <7UYj8.31929$l93.6269941@newsb.telia.net> Message-ID: <86zo1966gb.fsf@skitty.catseye.net> Peter Dobcsanyi writes: > Oops, you are right! I fixed it and ran the test again. > > 3000 times, Python 2.2, Linux: > > i in range(len(ls)): 2.03 > x in ls; i+= : 2.28 > lambda x:zip(range(len(x)), x): 3.76 > Iter class: 10.18 > > 10000 times: > > i in range(len(ls)): 6.68 > x in ls; i+=1 : 7.55 > lambda x:zip(range(len(x)), x): 12.56 > Iter class: 35.56 > > Interestingly, "range(len(ls))" is still faster. Cool. And you're right, it's very interesting. I wonder why /F thought the bar() version would be faster. The results seem to suggest that adding 1 to a number is slower than indexing a list (the one generated by range). Tim From eppstein at ics.uci.edu Mon Mar 4 20:26:16 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 04 Mar 2002 17:26:16 -0800 Subject: Status of PEP's? References: Message-ID: In article , James_Althoff at i2.com wrote: > [David Eppstein] > > It seems like it should be really easy to modify the parser to > > parse > "for" expression ":" > > and then check whether the expression is an "in" or a > > comparison... > > You might want to think this through a bit more since neither arbitrary > "expression" nor arbitrary "conditional" is supported in the suggestions > posted so far. I didn't suggest that it would be. I suggested that this would be a way to implement the parser for for-loops, if for some reason it's too much work to make it parse only the expressions allowed in a for-loop. From tdelaney at avaya.com Mon Mar 4 20:19:38 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 5 Mar 2002 12:19:38 +1100 Subject: Status of PEP's? Message-ID: > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > For the same reason that > for item in list > works but > for dictionary.has_key(item) > doesn't: The for-loop syntax only allows a very restricted set of Just realised something for PEP 276. If it passes, for i in dictionary.has_key(item): would then be valid ... as it would return 0 or 1. This may or may not be considered a bad thing - it would be equivalent to: if dictionary.has_key(item): for any condition that does return 0 or 1. Tim Delaney From grante at visi.com Sat Mar 9 09:58:47 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 09 Mar 2002 14:58:47 GMT Subject: Turn string into function call References: <1f5252d4.0203080545.3861adec@posting.google.com> Message-ID: In article , Aahz Maruch wrote: > In article , > Grant Edwards wrote: >>In article <1f5252d4.0203080545.3861adec at posting.google.com>, N Becker wrote: >>> >>> What's the best way to turn a string naming a function into a function call? >>> >>> I used this: >>> eval (funcname + '()') >> >>This really ought to go into the FAQ. It's been asked (and >>answered) at least 3 times in the past week or so. > > Okay, here's a proposed FAQ entry, for section 4: > > How do I convert a string to a function/method call? > > There are two basic techniques: > > * Use a dictionary pre-loaded with strings and functions. The primary > advantage of this technique is that the strings do not need to match the > names of the functions. This is also the primary technique used to > emulate a case construct: > > def a(): > pass > > def b(): > pass > > dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs > > dispatch[get_input()]() # Note trailing parens to call function > > * Use the built-in function getattr(): > > import foo > getattr(foo, 'bar')() > > Note that getattr() works on any object, including classes, class > instances, modules, and so on. I think it would also be good to mention the eval() method, and the locals() method (and the problems with both). I started to write up a FAQ yesterday but didn't get very far... -- Grant Edwards grante Yow! I predict that by at 1993 everyone will live in visi.com and around LAS VEGAS and wear BEATLE HAIRCUTS! From rjones at ekit-inc.com Wed Mar 20 18:05:09 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 21 Mar 2002 10:05:09 +1100 Subject: bug tracking system In-Reply-To: <3C9836DF.1E877634@engcorp.com> References: <3C9836DF.1E877634@engcorp.com> Message-ID: <200203202305.XAA21573@crown.off.ekorp.com> On Wed, 20 Mar 2002 18:14, Peter Hansen wrote: > mohamed lazreg wrote: > > Dear pythoners, > > > > Are you aware of any free bug tracking system written > > in python? > > Several based on Zope... (http://www.zope.org) Note that Roundup has a Zope interface allowing you to access Roundup trackers through Zope. http://roundup.sf.net/ Richard From djc at object-craft.com.au Mon Mar 25 08:45:44 2002 From: djc at object-craft.com.au (Dave Cole) Date: 26 Mar 2002 00:45:44 +1100 Subject: [albatross-users] Re: Python embedded like PHP References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> Message-ID: >>>>> "Duncan" == Duncan Booth writes: Duncan> Dave Cole wrote in Duncan> news:mailman.1016855556.16177.python-list at python.org: >> You are forced to embed programming logic which is used to >> dynamically alter the presentation of the interface directly inside >> the presentation elements. I have a feeling that this makes the >> whole template unduly fragile and resistant to change. Duncan> I would have said you are forced to remove almost all Duncan> programming logic from the template entirely and wrap it up in Duncan> a separate script. All that is left in the template is the Duncan> display logic. That is the best way to go IMO. ZPT seems fine to me except in the coarser aspects of template programming. Control flow in particular just does not look right to me. >> The idea that an HTML developer who does not understand ZPT will be >> able to ignore the ZPT attributes and just change the interface in >> isolation is a fantasy. The ZPT attributes define an executable >> program - their correct placement is critical to the functioning of >> the template. Note that the same is true of Albatross tags, but >> you can change the HTML in isolation to the Albatross tags. Duncan> I agree with you here up to a point. I would break down the Duncan> roles into html developer who needs to know some ZPT, Duncan> presentation developer who just needs to know what not to Duncan> touch, and content developer who just needs to know which Duncan> parts of the page require content. Are you suggesting that there are three different people would work on the same template file? IMO there would be some sort of graphic design done which may not necessarily produce useful HTML - that design would be taken by the content developer who would then build the template. Duncan> You can even edit ZPT using Microsoft Frontpage, and mostly Duncan> things don't break. If someone is simply adding content to a Duncan> specified cell in a table, then they can edit happily within Duncan> that cell. It would be nice though if the HTML editor could Duncan> somehow be told to make the rest of the template readonly. I expect that most HTML editors are pretty good when they encounter stuff that they don't understand. Duncan> I think that until I actually used ZPT, it wasn't obvious just Duncan> how good a job it does of separating the logic, the Duncan> presentation, and the content. You are talking my language there. One of the things which makes me dislike PHP is that there is little effort to perform separation. Sort of what you would expect from a perl for web pages. Duncan> In particular the CMF skins help a lot. I haven't looked at CMF skins. - Dave -- http://www.object-craft.com.au From cbbrowne at acm.org Mon Mar 11 11:58:07 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 11 Mar 2002 11:58:07 -0500 Subject: Is Python an object based programming langauge? References: Message-ID: In an attempt to throw the authorities off his trail, drevenhaug at hotmail.com (Graz Bukanoff) transmitted: > Is Python an object based programming langauge? Most languages involve manipuation of some form of "object," so that even COBOL could be claimed to be an "object based programming language." You might want to be more specific about what you mean by "object," otherwise people could say "yes" or "no" with equal legitimacy as they intend different meanings of "object." -- (reverse (concatenate 'string "gro.gultn@" "enworbbc")) http://www3.sympatico.ca/cbbrowne/wp.html From dale at riverhall.NOTHANKS.co.uk Fri Mar 22 20:07:52 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 23 Mar 2002 01:07:52 +0000 Subject: Develop-test-debug cycle References: Message-ID: <46ln9u4mi1f9vkjbob8lgkhm9kmgsb3m9a@4ax.com> "John Roth" wrote: >I don't. I got bit by the XP bug a while back, and now I >write all unit tests in advance, using the 'unittest' module. >I keep the editor (PythonWin) open, save the module >I've just changed, and invoke a script at the command line >to run the current test set. Works like a charm, and has the >additional advantage that I don't have to worry about >breaking things with changes - the unit tests are persistant, >so they'll tell me. > >I don't have to go into the debugger very much to figure >out a problem, so reloading the module from scratch >isn't a significant issue. That's fine for small systems - and I do the same - but for large systems the supporting environment for a single object is too complex. We are working on a system of >50 modules you simply can't run most modules in isolation. -- Dale Strickland-Clark Riverhall Systems Ltd From ianb at colorstudy.com Sun Mar 24 15:00:08 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 24 Mar 2002 14:00:08 -0600 Subject: [albatross-users] Re: Python embedded like PHP In-Reply-To: References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> Message-ID: <1017000019.3094.31.camel@localhost> On Fri, 2002-03-22 at 21:50, Dave Cole wrote: > I had a crazy idea a while ago which would stop us having to do the > thing that you pointed out: > > "> > > The idea, which I am still not sold on, goes a bit like this: > > > > > > The first bit of template attaches an attribute name and value to an > attribute id. This attribute association would be stored in the > execution context so you could define values in your Python code if > you wished. Albatross tags would then retrieve values from the > association by using the same id attribute. > > This would allow Albatross templates to be much more flexible. > Consider the tag. At the moment you have to staticly decide > the name of the iterator. This means that you cannot reuse a bunch of > template code which paginated a sequence in a macro since you would be > using the same iterator for multiple sequences. With the above you > could do this (not really a good example): > > > > blah blah > > > > > > spam > > > > eggs > > The functionality would require an extensive reworking of the tags > code. There are some advantages to the approach but I am still a > bit concerned that it is too obscure. For this problem, I think the solution is in the interpreter -- your macros are just hard to work with (from what I can see), because they are dynamically scoped and being used in lieu of real functions. It's not a syntax issue. > Andrew has since mentioned changing the way that the we name the > Albatross processed attributes to make them more functional and > consistent. Something like: > > > > > I am starting to think that this would be an excellent idea. > > Ian> Of course there's the ZPT approach, which isn't bad, but then you > Ian> might as well use ZPT. But I guess there's no reason you can't > Ian> use something like ZPT just for changing attributes, like: > > Ian> > > I have a few concerns about ZPT. > > You are forced to embed programming logic which is used to dynamically > alter the presentation of the interface directly inside the > presentation elements. I have a feeling that this makes the whole > template unduly fragile and resistant to change. > > The idea that an HTML developer who does not understand ZPT will be > able to ignore the ZPT attributes and just change the interface in > isolation is a fantasy. The ZPT attributes define an executable > program - their correct placement is critical to the functioning of > the template. Note that the same is true of Albatross tags, but you > can change the HTML in isolation to the Albatross tags. I'm not sold on all the benefits of ZPT either, but I think it's a natural fit for the particular case of replacing an attribute value. To me, rows on new lines it will be easier to read in source. You may find it useful even if no one else sees it. Nice look, however old Netscape will sometimes not show empty table cells properly unless you at least put a non-breaking space (  IIRC) in them. Plain blanks between won't do it. I didn't look at your program yet. I think you will enjoy Python. Have fun. Regards, Bengt Richter From djc at object-craft.com.au Wed Mar 6 23:29:37 2002 From: djc at object-craft.com.au (Dave Cole) Date: 07 Mar 2002 15:29:37 +1100 Subject: Web scripting with Python (1st post here, also :-) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: >>>>> "Julio" == Julio Nobrega writes: Julio> Hi! I am used to do web scripting using PHP. As a new Julio> adventure, I am trying to learn Python. I really wished I could Julio> write 'desktop' apps with Python, but from what I read (and Julio> from what I am planning), that's a little far away from my Julio> current trouser snake knowledge (I also heard you all like Julio> those kind of quotes ;-) Julio> So, I am looking for examples that might help me. Yes, I saw Julio> Zope. Waaaaay too much. Also read Web Programming Topic Guide Julio> on python.org, way less practical than I like. Picky, ain't I? Julio> :-) Julio> I searched for complete (yet simple), or incomplete (yet with Julio> explanations) apps on cgi-resources, parnassus and hotscripts, Julio> but I don't have background to decide what's good or bad Julio> Python. And surely I don't want to start with the wrong foot Julio> :-) Have a look at our toolkit. It comes with around 120 pages of documentation - the first half of which is a guide to building applications. http://www.object-craft.com.au/projects/albatross/ Some of the templating and session behaviour was inspired by PHP so you should feel at least partially at home. - Dave -- http://www.object-craft.com.au From gcordova at hebmex.com Wed Mar 6 19:24:14 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 6 Mar 2002 18:24:14 -0600 Subject: Code Bash!!! (CacheDictionary) Message-ID: <19650FF08A99D511B19E00B0D0F06323060B45@SRM201002> Howdy everyone. I've been tinkering aimlessly for a few days; the miniXML module is sitting in the backburner for now, I'm trying to design a way for it to request more text ("Feed Me Seymour!!") without it breaking the current simple, toyish design, and at the same time, having the parser "not notice" that new text has been inserted. Anyhow, I subclassed the "dict" class, to make one with some cache functionality, such as item timeouts, automatic purging of old elements, and maximum length / LSU dropping. So here's an afternoon of tinkering, for your enjoyment. It's quite simple, and running the script without any parameters runs a few tests on it. The class can be subclassed, so your program can catch when an item is being dropped either because it's the oldest and the LRU catcher got it, or because it's being dropped along with all the other timed-out items. Have a nice evening! pd: man, python's cool. :-) -- Gustavo C?rdova Avila > gcordova at sismex.com ? 8351-3861 | 8351-3862 -------------- next part -------------- A non-text attachment was scrubbed... Name: CacheDictionary.py Type: application/octet-stream Size: 5678 bytes Desc: not available URL: From siegfried.gonzi at kfunigraz.ac.at Tue Mar 12 08:15:39 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Tue, 12 Mar 2002 14:15:39 +0100 Subject: Question about scientific calculations in Python References: Message-ID: <3C8DFF7B.7EF0EAC6@kfunigraz.ac.at> Martin Kaufmann wrote: > Now my questions: Would it be best to > > (a) write the whole program in C/C++ (I know only the basics of C but > it would be a good "excuse" to learn it...)? > (b) write the main program in Python but the heavy calculations in C > (I played today with scipy.weave -- the speed is much better but I > didn't really understand what I was doing...)? > (c) program it in Python and don't care about speed (or buy a new > workstation...)? I once did a similar project in Yorick. It was not aimed at diffraction patterns for electrons, but I have calculated the Fresnel-integral and Zernike-polynomials via the FFT for a 1024x1024 grid in order to test the diffraction pattern of a telescope. Yorick worked fine and I could made some nice postscript outputs. Projecting this experience to Python. I would assume (but without any detailed study) that Python in combination with the numeric library will serve you very well. But it depends whether you can use a straightforward algorithm (like the FFT) or you must solve your own integral. > Are there any libraries or other resources that would help? I used the > Scientific Python library for the histogram but it was much slower > than my DIY approach. How much slower? A performance penalty of 100 would be of great concern; a factor of 5 should not mind you (but this is my personal view). Okay, if you have to wait in C or C++ 1 hour then even a factor of 5 is somewhat bothersome. Regards, S. Gonzi From jimd at vega.starshine.org Sun Mar 17 19:18:32 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 18 Mar 2002 00:18:32 GMT Subject: select.select() on Regular Files? References: Message-ID: In article , Paul Wright wrote: >In article , >Jim Dennis wrote: >> O.K. so what can I do for asynchronous I/O notification on >> regular files? How can I efficiently block and wake up when >> I/O is available on any of my file descriptors? >> Don't tell me I have to go into a sleep and poll stat() or >> seek() loop! It's hard to imagine that UNIX got this far >> without offering a better solution than that! > If you run strace on "tail -f somefile", you'll find that sleeping and > stat'ing is what it's doing, so I don't think there's a better way. > Paul Wright | http://pobox.com/~pw201 | Alright, I'll 'fess up. I had run strace tail -f ... before I wrote my original post. But I was hoping that I was looking at some legacy of compatibility/portability, or laziness! I guess the newer versions of FreeBSD are ahead of Linux in this category. Hopefully Ben LaHaise' AIO work will get merged in soon and in a few years we can relegate "while (1) { nanosleep(); stat(); }" to the history books. From ykingma at accessforall.nl Wed Mar 13 14:24:46 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Wed, 13 Mar 2002 20:24:46 +0100 Subject: Another socket/thread question References: Message-ID: <3C8FA777.8A5B07D1@accessforall.nl> Ken wrote: > > Hey everyone.. > > I've got a thread that continously listens to a socket, and reports what it > receives. Blocking is turned on, and I would like it to stay that way since > the only thing the thread has to do, is listen to the socket. > > My question is when the socket needs to be closed (program shuts down, or > that user is being disconnected by the server) is it possible to interupt a > socket.recv ()? When you close the socket from another thread or by the server, the pending socket.recv() should terminate with some error condition. It's best to test both situations, however. Have fun, Ype From nospam at [127.0.0.1] Sat Mar 16 11:28:00 2002 From: nospam at [127.0.0.1] (Chris) Date: Sat, 16 Mar 2002 16:28:00 +0000 Subject: This may seem a slightly strange problem ... References: Message-ID: In article , Emile van Sebille writes >If that interests you, take a look at trying to duplicate something >like: >http://www.hypersolutions.org/images/rgbhex.gif as html. You could also >use python to generate the html. I like that. And the idea of using Python to generate HTML is interesting. Is that easy enough for a beginner? -- Chris From opengeometry at DELETE.yahoo.ca Sun Mar 3 19:27:23 2002 From: opengeometry at DELETE.yahoo.ca (William Park) Date: 4 Mar 2002 00:27:23 GMT Subject: Text Search Engine that works with Python References: Message-ID: Doug Farrell wrote: > Hi all, > > I'm wondering if anyone knows of a text search engine that works with > Python? What I'm looking for specifically is something that will > compress the text and still allow searches and retrievals that can be > exact matches or proximity based. The text I want to compress and > search is huge (70 megs) and should compress down to half, not > including any index files that might be required by the search engine. > Anyone know of anything like this or any ideas? > > Thanks, Doug Farrell Perhaps, you can illustrate your problem with some concrete examples. Otherwise, you'll be getting "use Linux" or "use gzip/bzip2" answers which wouldn't be too useful for you (judging by the fact that you had to ask in the first place). -- William Park, Open Geometry Consulting, 8 CPU cluster, NAS, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Tin From wurmy at earthlink.net Fri Mar 8 11:31:22 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Fri, 08 Mar 2002 16:31:22 GMT Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: <3C88E7B4.A910D281@earthlink.net> N Becker wrote: > > Back in 1999, I asked "where is quote?". I was looking for > a way to quote a function (delay evaluation). Python is not Lisp... It would be interesting to have lazy evaluation though... I'm not sure if it's possible to implement, or if it will be useful at all. It sure makes sense in functional languages, but in Python? Hm. > I wonder if there is anything new. It looks to me that the > best answer is to use lambda. > > example: > > def f(): > return lambda: os.chmod(""/root/.rhosts", 0644) > > def g(): > f() Writing your code like this is asking for trouble. Not only does it make your code less clear, but it also introduces a Lisp-ish idiom, which is fine when you're writing Lisp, but in Python there are certainly better ways to do what you want, depending on what you are trying to do. (Unless you're writing an entry for the Obfuscated Python Contest... ) -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From boomshanka at wp.pl Sun Mar 24 19:56:24 2002 From: boomshanka at wp.pl (boomshanka at wp.pl) Date: Mon, 25 Mar 2002 00:56:24 +0000 (UTC) Subject: 100% in one month!!! 8320 Message-ID: http://www.magicmoneygame.com/default.asp?referrer=0852016798 Register, deposit money, buy nr 11 stocks, get 100% in one month :)) Regards, Marcin eqfbwlwzgzrpunphmlllotvkizcbigrnqojbtkkgdpgpqkbctqvejquyjrqshiopdrcmnylfbgbecsgvkwku From bergeston at yahoo.fr Thu Mar 21 10:44:18 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Thu, 21 Mar 2002 16:44:18 +0100 Subject: Returning an element from a C struct References: <3C9772AB.1691D362@saic.com> <3c990582$0$29676$ba620e4c@news.skynet.be> Message-ID: "Armin Rigo" wrote in message news:3c990582$0$29676$ba620e4c at news.skynet.be... > > How about > > > > def __getattr__(self,name): > > try: > > return self.__dict__[name] > > except KeyError: > > return getattr(self.ptr, name) > > It even looks like the first 'return' is not needed. If the attribute is > found in the instance then __getattr__() is not called at all. > > Armin > ... but AFAIK in Python 2.2, if __getattribute__(self, key) is implemented, it is called anyway. From gleki at gol.ge Mon Mar 4 17:03:48 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Mon, 04 Mar 2002 14:03:48 -0800 Subject: more functional programming Message-ID: <3C83EF44.A44E595C@gol.ge> Hi all! Please, accept my appologies for this naive question. I have taken a careful look on the operator module docs. The module enables one to make procedures as lists. That's too good. However, is there already something like scheme's "define" abstractor? This'd be used as the first element of such list, yielding the result of the procedure... Is this, or anything similar, already present in Python? If not, does someone of the Python gurus plan to do so? Thank you very much for your time. Greetings, Giorgi PS. Is a genetic programming library written in/for Python available? From irmen at NOSPAMREMOVETHISxs4all.nl Tue Mar 26 02:06:47 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Tue, 26 Mar 2002 08:06:47 +0100 Subject: Client/Server Tutorial? References: <83u1r43zav.fsf@panacea.canonical.org> Message-ID: "Kragen Sitaker" wrote in message news:83u1r43zav.fsf at panacea.canonical.org... > "Irmen de Jong" writes: > > > Is there any good tutorial for creating advanced client/server apps > > > (like online games) out there? i tried to make one 2 times, and both > > > > May I suggest you take a look at Pyro; http://pyro.sourceforge.net > > It may be just what you want/need for easy distributed application development. > > You don't have to do any network programming when using Pyro. > > I don't think Pyro is suitable for online games. It's an RPC layer. > Yes, but what is wrong with that? Your game clients communicate with a game server, voila, RPC. A single or a few Pyro objects could perfectly be the game server, can't they? Your server publishes game state updates. Voila, Pyro's event service. Irmen From scott2237 at yahoo.com Sun Mar 10 20:35:32 2002 From: scott2237 at yahoo.com (googlePoster) Date: Mon, 11 Mar 2002 01:35:32 GMT Subject: python as gvim scripting lang -- examples please Message-ID: I would like to see some example python gvim scripts so I could get started with some simple stuff -- need access to runtimepath, range, etc From mcfletch at rogers.com Fri Mar 22 13:04:59 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 22 Mar 2002 13:04:59 -0500 Subject: python/wxPython opengl question References: Message-ID: <3C9B724B.8020201@rogers.com> I'm guessing GLUT's exit function is making a call to the C equivalent of sys.exit. Best approach would be to use a wxPython OpenGL context, instead of the GLUT one. You can find a demo of creating a wxPython OpenGL context in the wxPython demo. HTH, Mike alan scales wrote: > i have a python app (using wxPython). from it i create a top level > window (frame) using python opengl. this works: i have my app > running, and alongside it the gl graphics window. > > however, when i close the opengl window, it closes my wxPython app > (and the python console) - i.e. everything. > > i don't want this behavior. is there any way to prevent it? > > for the gl window i am just making a standard > glutCreateWindow(title)call. > > alan scales _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From fdrake at acm.org Sun Mar 24 13:58:35 2002 From: fdrake at acm.org (Fred L. Drake) Date: Sun, 24 Mar 2002 13:58:35 -0500 (EST) Subject: [development doc updates] Message-ID: <20020324185835.2D25928696@beowolf.fdrake.net> The development version of the documentation has been updated: http://python.sourceforge.net/csstest-docs/ This is the experimental formatting for the documentation. This version should work better for Opera users; it should work fine for Opera 6, and works (slightly) better than it did for Opera 5. There's probably no change for other browsers. From emmanuelgagniere at wanadoo.fr Sat Mar 30 05:48:07 2002 From: emmanuelgagniere at wanadoo.fr (Emmanuelgagniere) Date: Sat, 30 Mar 2002 11:48:07 +0100 Subject: GUI programming References: Message-ID: wxpython is the best one Umesh Persad a ?crit dans le message : mailman.1017437568.25402.python-list at python.org... > Hi, > I am doing an assignment using python - > making a turkish checkers game. > > --------------------------------------- > | | > | | > | | > | checker board area | > --------------------------------------- > | | > | text fileds and buttons area | > | | > --------------------------------------- > > I wanted to have a user interface where > I can draw the game board as well as take > in text input below the board with some text > felds and buttons. I see there are many GUI toolkits > available. I am wondering which one should I use > (tkinter, wxpython?) that will be simple enough > to get me up and running qiuckly. Also are there > any examples that I can look at? > > Also, if any one is familiar with Tkinter, > how do I put up a window with a size > that I want? Also how do I place a canvas > on the window at a predefined size? > > Thanks a lot, > Umesh > > From rjones at ekit-inc.com Sat Mar 30 06:08:00 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sat, 30 Mar 2002 22:08:00 +1100 Subject: GUI programming In-Reply-To: References: Message-ID: <200203301108.LAA04305@crown.off.ekorp.com> On Sat, 30 Mar 2002 21:48, Emmanuelgagniere wrote: > wxpython is the best one No, Qt is the best one, by far. Richard From opengeometry at NOSPAM.yahoo.ca Sun Mar 17 13:57:26 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 17 Mar 2002 18:57:26 GMT Subject: a text processing problem: are regexpressions necessary? References: Message-ID: Sandy Norton wrote: > Hi, > > I thought I'd share this problem which has just confronted me. > > The problem > > An automatic way to tranform urls to articles on various news sites to > their printerfriendly counterparts is complicated by the fact that > different sites have different schemes for doing this. (see examples > below) > > Now given two examples for each site: a regular link to an article and > its printer-friendly counterpart, is there a way to automatically > generate transformation code that is specific to each site, but which > generalizes across all article urls within that site? You already identified the central issue. Each site is different, but presumably consistent within the site. I guess you can build up Sed scripts... > http://news.bbc.co.uk/hi/english/world/africa/newsid_1871000/1871611.stm > http://news.bbc.co.uk/low/english/world/africa/newsid_1871000/1871611.stm sed -e 's,http://news.bbc.co.uk/hi/,http://news.bbc.co.uk/low/,' > http://www.economist.com/agenda/displayStory.cfm?Story_ID=1043688 > http://www.economist.com/agenda/PrinterFriendly.cfm?Story_ID=1043688 grep 'http://www.economist.com/' | sed -e 's,[^/]*\.cfm\?,PrinterFriendly.cfm?,' > http://www.nationalreview.com/ponnuru/ponnuru031502.shtml > http://www.nationalreview.com/ponnuru/ponnuruprint031502.html grep 'http://www.nationalreview.com/' | sed -e 's,\([0-9]\+\)\.shtml$,print\1.html,' > http://www.thenation.com/doc.mhtml?i=20020204&s=said > http://www.thenation.com/docPrint.mhtml?i=20020204&s=said grep 'http://www.thenation.com/' | sed -e 's,\.mhtml\?,Print&,' -- William Park, Open Geometry Consulting, 8 CPU cluster, NAS, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Tin From ykingma at accessforall.nl Sun Mar 10 14:12:23 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sun, 10 Mar 2002 20:12:23 +0100 Subject: Use apply() or not, and raising multiple exceptions (co-routines?) References: Message-ID: <3C8BB00C.12A3F4E1@accessforall.nl> Roy, You wrote: > > I've got some code which performs a series of integrety checks against a > data set. The way I've set things up, I put each check in its own method > and keep a list of all the methods: > > checks = [] > > def check1 (self, data): > do stuff > checks.append (check1) > > def check2 (self, data): > do other stuff > checks.append (check2) > > and so on. This makes it easy to add and delete bits of policy over time. > I cycle over the checking functions by doing: > > for check in self.checks: > check (self, data) > > I could have also written this as: > > for check in self.checks: > apply (check, [data]) Sounds familiar. > > is there any particular reason to prefer one style over the other? Having > walked a few people through the code, I'm starting to think that the latter > is a little more self-explanitory (especially for junior pythonistas). On > the other hand, I suspect it's slighly less efficient. > > A related question is how best to have the check methods do more than one > thing. Right now, I just have each method print an error message when it > finds a problem. A given method might check for more than one related > problem. I'd like to pull the printing out of the functions themselves, > and go to an exception based system, where I'd do something like: > You might start thinking in terms of 'testing' instead of 'checking'. > for check in self.checks: > try: > check (self, data) > except IntegrityCheckError, message: > print 'failed check:', message > > The problem is I'd only catch the first problem found by a given check > method. The way around that would be to make the check methods each look > for one, and only one, problem, but that wouldn't be inefficient > (especially since some methods would share a lot of code and repeat a lot > of work). Is there some way to stack exceptions, so a given method can > raise two or more of them in sequence, or something having the same effect? > There is a way to do that, see below. > The only thing I can see is to have each check method return a list of > problems it found. Then, the main loop would look like: > > for check in self.checks: > for problem in check (self, data): > print 'failed check:', problem > > but that implies pushing a lot of scaffolding down into the check methods, > making them build and manipulate error lists to return. I'm trying to keep > them as clean as possible, so they're easy to write and debug. > Right. > It would be kind of neat if after doing the except clause, my method picked > up again at the statement after the raise. I guess what I'd have then is > the caller and callee acting as co-routines. Is there a way to do anything > like that? Definitely. Software testers have exactly the same set of problems you describe. You test data, but what's the difference in OO? That's why I think you are going to really like PyUnit. It does everything you need, and probably more. It's in the standard distribution nowadays, but still it's wortwhile to have a look at http://pyunit.sourceforge.net/ The battery is included here: http://www.python.org/doc/current/lib/module-unittest.html There is a bit of learning curve, but PyUnit is really worth it. Since you have already encountered the basic problems of designing tests you'll probably get the point in no time. It will help you to let things fall into their place. Ype From donn at u.washington.edu Mon Mar 4 12:47:12 2002 From: donn at u.washington.edu (Donn Cave) Date: 4 Mar 2002 17:47:12 GMT Subject: what I would like to see in python to make a better "glue" language (Newbie) References: Message-ID: Quoth Anthony Baxter : | >>> Anthony_Barker wrote | > 1. LDAP module should be included in the base distro. Active Directory | > is already available via com (nice) | | I'm not convinced that this should be in the base distribution. Aside from | anything else, it often requires particular LDAP libraries to install. I | do think it should be easier to find and auto-install packages, but the | standard answer to this is, as ever, "send code". What do you think of the odds on a pure Python solution? The C library requirement is very awkward, especially on unusual platforms, and I'm thinking a Python implementation might actually come out better. Could have some advantages in situations where you want to go deeper into the system, like between the BER encoding and the LDAP protocol itself for debugging purposes. Maybe if the text processing turned out to be a serious performance issue, some decoding and parsing parts could be optionally implemented in C. I see the old 3.3 libldap adds up to 14K lines of code, but that's C, everyone knows Python can do the job in a lot less code. Donn Cave, donn at u.washington.edu From jon+usenet at unequivocal.co.uk Wed Mar 6 15:17:35 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Wed, 06 Mar 2002 20:17:35 -0000 Subject: Web scripting with Python (1st post here, also :-) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: In article <40c3f5da.0203061114.18f7fea6 at posting.google.com>, Julio Nobrega wrote: > So, I am looking for examples that might help me. Yes, I saw Zope. > Waaaaay too much. Also read Web Programming Topic Guide on python.org, > way less practical than I like. Picky, ain't I? :-) You could try the system I have just released on: http://jonpy.sourceforge.net/ Warning: it is alpha release but it's Way Cool (TM) From grante at visi.com Fri Mar 8 16:48:56 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Mar 2002 21:48:56 GMT Subject: newbie socket/thread question References: <3C8928E3.4B55769D@hotmail.com> Message-ID: In article <3C8928E3.4B55769D at hotmail.com>, Ken wrote: > Hey everyone.. > > I'm messing around with Python, trying to learn the language, by > building a simple network chat program that uses threads and sockets. > > I'm trying to set it up so that if the server receives a keyboard > interupt from console, it'll shut everything down. Which seems to work > fine for the most part. The problem is that after a user connects and > the server is stopped, the server cannot start up again right away. It > gets the error: > > socket.error: (48, 'Address already in use') By default you can't reuse a port immediately after it's been closed -- you have to wait a few minutes just in case there are any packets from the old connection still wandering around the network. It could cause problems if those packets from the old connectionarrive after you've bound a new socket to that address. If you want to disable that feature, you need to set the SO_REUSEADDR option on the socket before you do the bind() operation. -- Grant Edwards grante Yow! Inside, I'm already at SOBBING! visi.com From dale at riverhall.NOTHANKS.co.uk Sun Mar 24 06:14:21 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sun, 24 Mar 2002 11:14:21 +0000 Subject: MS Sql Server References: <788n8.60257$bj1.19179906@news02.optonline.net> Message-ID: "Chase" wrote: >Hi... > >Wondering what the most accepted practice is, for communicating to Sql >Server Databases. Is it the ODBC module ? mxODBC ? Is there an ADO module ? > >Any hints/help appreciated. > You don't say where the client is running. If it's on Windows, ADO is fine using the COM interface provided by Win32All but you do need to watch out for all the performance tweaks if you're going to be hitting it hard. Search this ng's recent history ('ADO' in the subject) for some interesting posts on the subject. -- Dale Strickland-Clark Riverhall Systems Ltd From usenet at thinkspot.net Tue Mar 19 14:43:46 2002 From: usenet at thinkspot.net (Sheila King) Date: Tue, 19 Mar 2002 11:43:46 -0800 Subject: bug reporting References: Message-ID: On Tue, 19 Mar 2002 19:58:59 +1000 (est), Andrew MacIntyre wrote in comp.lang.python in article : > On Sun, 17 Mar 2002, Sheila King wrote: > > > On Sun, 17 Mar 2002 19:41:22 -0500, "Arthur Siegel" > > wrote in comp.lang.python in article > > : > > {...} > > > report after all. It may end up to be a problem in my own code. :/ > > Bug reports can be closed ;-) Though I'm not sure that SF actually allows > anyone other than project developers to do so, a followup that explains > that it should be closed with no further action would result in closure > with minimum wastage of effort. I did close it, later the same day that I opened it. Still, sometimes feedback and discussion is nice. I don't like to report false alarms, and I'm sure that in an ideal world, the developers would rather not deal with false reports, as well. 's OK now, though. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From deltapigz at telocity.com Sat Mar 9 17:33:32 2002 From: deltapigz at telocity.com (Adonis Vargas) Date: Sat, 9 Mar 2002 17:33:32 -0500 Subject: Tkinter + Button widget Message-ID: <3c8a9185$1_1@nopics.sjc> when i start a button widget, it automatically fires the command? def HideNewClient(self, frame): frame.configure(bd=0, width=0, height=0) return pdb_btnSearch = Button(pdb_frmCommands, text="Search", relief=GROOVE, font=("Tahoma", 10), width=16, command=self.HideNewClient(pdb_frmNewClient)) any help would greatly be appreciated. Adonis From jgardn at alumni.washington.edu Fri Mar 1 20:57:08 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Sat, 02 Mar 2002 10:57:08 +0900 Subject: Useful, robust shell utilities References: Message-ID: <%8Wf8.518$Az6.2357@news.hananet.net> Donn Cave scribbled with his keyboard: > Quoth Jonathan Gardner : > | I tried to use the shutil module... and to tell you the truth, it > | stinks. Is there an effort to make a robust, useful shutil module that > | has the equivalent of the unix shell utilities? > > Go ahead. Then keep an eye out on comp.lang.python, and after some > years pass finally someone will mention it: "it stinks", they'll > say, with no particular explanation. =) I didn't mean to be particularly offensive. It was just that the copytree function has this little comment: The source code for this should be considered an example rather than a tool. And it also won't copy to a directory that already exists... this is very different than what 'cp' does. > > | I think it would be nice to make things like 'grep' even... > | > | Here is my wish list. Each of these should implement a significant > | portion of what the GNU utils do. They should be robust, and give > | reasonable results, and reasonable exceptions. > | > | touch, chmod, chown, chgrp, touch > | df, du > | cp, dd, install, mv, rm, shred > > Some of them are essentially POSIX 1003.1 functions, hence supported in > the posix module (which we usually call "os" so it will appear that these > functions are supported on all platforms, whether they really are or not.) > > chmod == chmod() > chown == chown() > chgrp == chown() > rm == unlink() > mv == rename() > dd ~= read(), write(), lseek() > df == fstatvfs() > They do in fact appear in the 'os' module, but they are rather limited to the forms of input they take. For instance, you have to use (octal) numbers for chmod(). There would be a big benefit to see something like: res = chmod("-c", "-R", "u=rwx,g=rx,o=", a_file, another_file, a_directory) Even having a function reference you pass in that returns true or false in answer to questions like, "Shall I delete this directory?" would be very useful. Well, it looks like I'd better get started. I think 'cp', 'rm' and such will be the easiest to implement. Any ideas for a module name? > Donn Cave, donn at u.washington.edu Jonathan (jgardn at u.washington.edu) From Oschler at earthlink.net Tue Mar 5 11:04:20 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 5 Mar 2002 11:04:20 -0500 Subject: Get reference to "owner" References: <20020305072655.GA1525@lilith.hqd-internal> <625h8.3294$tg2.206482@e3500-atl1.usenetserver.com> <3C84E34B.1010009@bigfoot.de> Message-ID: You're being generous by saying "we", I merely asked the question, it was your solution. Seeing as you used the word "baby" already a simple name would be the GetParent pattern. Gerhard H?ring wrote in message news:3C84E34B.1010009 at bigfoot.de... > Robert Oschler wrote: > > Gerhard, > > > > Excellent!!! Never expected to find a language that could do this and it > > something I've wanted very badly for a long time. Yes that's exactly what I > > meant. B knows about the A that owns it without having to artificially pass > > a reference of A to B during construction. > > So, if we're really the first ones to invent and implement this pattern, > how do we name the baby? > > The Borg name seems to be already taken ;-) > > Gerhard > From syver-en+usenet at online.no Mon Mar 11 18:00:49 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 11 Mar 2002 23:00:49 GMT Subject: starting Comands from Python References: <3C8CFE72.80108@web.de> Message-ID: Werner Hartnagel writes: > Hi > > Im a Python newbie and starting a small Project to learn Python > better. > > Its a GUI for the Image Magick Convert Tool. > The Application has a GtkCList with the Files to Convert. > > My Problem is I dont understand how to start a Application (convert) > as > > a new Process. I use "posix.system(cmd_str)" to Test the Program, and > of > > course the GUI freeze :-( I think you should use os.system (It's the same but portable). > It should wait for finish converting the File and start start again if > > not "Cancel" is selected. Put the code starting the process in a threading.Thread derived object and let the gui set some flag that the thread can read and abort when the user hits cancel. Check out the threading module documentation to see how to use it. -- Vennlig hilsen Syver Enstad From quinn at hurl.ugcs.caltech.edu Sun Mar 31 16:08:06 2002 From: quinn at hurl.ugcs.caltech.edu (Quinn Dunkan) Date: 31 Mar 2002 21:08:06 GMT Subject: getting infos from a website References: <3CA61187.C0548FD5@cam.org> <3CA614B8.2C5C25E4@cam.org> Message-ID: On Sat, 30 Mar 2002 16:00:23 -0500, Zutroi Zatatakowski wrote: >But another thing... Now that I can capture a website html and output it >into a file, I have to remove all html tags (I guess replacing '<>' by ' >') or, but I don't know if it's possible, instead of capturing the HTML >source of the page, could I retrieve only the text, like basic ASCII >copy/paste? Depends on what you want to do with it. If you just want to read it, download w3m, save the text to a tmp file and capture the output of 'w3m -dump tmpfile'. If you want to extract some part of the page you could look for a landmark, and write a simple regexp. Otherwise there are some HTML parsing bits in the stdlib. Or you could pick apart the w3m output. How fragile your code is to page changes depends on the page and how you do things. From morton at dennisinter.com Thu Mar 28 14:37:14 2002 From: morton at dennisinter.com (damien morton) Date: 28 Mar 2002 11:37:14 -0800 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: <4abd9ce7.0203281137.7caef540@posting.google.com> You could go a lot further with this case statement First thing is to allow for variable length list unpack: (a, b, *c) = (1,2,3,4,5,6,7) a <- 1 b <- 2 c <- (3,4,5,6,7) Second thing is to allow non-binding literals in a list unpack: (1, a, b) = (1, 2, 3) matches/unpacks with a=2, b=3 (1, a, b) = (2, 3, 4) fails ('fred', a, b) = ('fred', 'was', 'here') matches/unpacks with a='was',b='here' ('fred', a, b) = ('joe', 'was', 'here') fails Then, introduce a simple case statement: case var: 20: print 'var is 20' 30: print 'var is 30' else: print 'we have fallen though' A slightly more complex case statement: case: if var < 20: print 'var is < 20' if var = 25: print 'var is 25' if var > 30: print 'var is > 30' else: print 'we have fallen though' An even more complex case statement: case someobject: (X, Y): print 'macthes any list/tuple of length 2' print X, Y (X, Y, *Z) if X<32 and Y=="abc" and len(Z)>4: print 'would match (1,"abc",3,4,5,6,7) print 'X <- 1' print 'Y <- "abc"' print 'Z <- (3,4,5,6,7)' print X, Y, Z (X, Y, *Z): print 'matches any list/tuple of length 3 or more' print X, Y, Z X if isinstance(X, file): print 'matches any file object' print X else: print 'final condition matches anything' translated into current python: (assuming that variable list unpack is included in the python core) try: (X, Y) = someobject except ValueError: try: (X, Y, *Z) = someobject except ValueError: X = someobject if isinstance(X, file): print 'matches any file object' print X else: print 'final condition matches anything' else: if X<32 and Y=="abc" and len(Z)>4: print 'would match (1,"abc",3,4,5,6,7) print 'X <- 1' print 'Y <- "abc"' print 'Z <- (3,4,5,6,7)' print X, Y, Z else: print 'matches any list/tuple of length 3 or more' print X, Y, Z else: print 'macthes any list/tuple of length 2' print X, Y "Ken Peek" wrote in message news:<3ca33c88 at news.mhogaming.com>... > Well-- OK, my new ISP doesn't have a news server, but I found one > that I could use to post this with. If you reply to my email, do > the 'nospam' thing first to my email address... > > I really am interested in what people think about this. I have > looked at all the other c.l.py posts on this construct, but I > don't think anyone proposed this format. > > BTW-- the 'until' thing in the original letter was already posted, > so please disregard that part of this post- (I left it in for > accuracy.) > > -----Original Message----- > From: Guido van Rossum > Sent: Thursday, March 28, 2002 04:45 > To: Ken.Peek at SpiritSongDesigns.NOSPAM.com > Cc: Marc-Andre Lemburg > Subject: Re: PEP 0275 > > If you really want to discuss this, it's better to post to c.l.py. > > --Guido van Rossum (home page: http://www.python.org/~guido/) > > -----Original Message----- > From: Ken Peek [mailto:Ken.Peek at SpiritSongDesigns.NOSPAM.com] > Sent: Thursday, March 28, 2002 01:05 > To: Marc-Andre Lemburg > Cc: Guido van Rossum > Subject: PEP 0275 > > How about: > > match some_object: > > ("I dream of Jeanie",): > print "with the light brown hair" > > (1,3,5,7): > > print "some odd numbers" > > # 'break' leaves the entire match structure > if (time_to_leave): break > > # 'continue' jumps to the first > # statement in the next clause > continue > > (123,456,789): > > print "some bigger numbers too" > > (19,56,22): > > print "some random numbers" > > (1001,2002,3000): > # YES! It IS possible we want to do NOTHING! > pass > > any: > print "we got here because there were no matches" > > This is kind of a neat construct because you can put multiple > tests on one line, and it doesn't look too messy (like C's > 'switch' would look.) Also-- we are not limited to matching up > only integers. This is very clean code compared to a long string > of "if/elif/elif/elif/else" clauses... I like READABLE code-- > which is why I like Python! > > Note that the aggregate of the tuples must have unique values and > types-- (this allows for efficient implementation, and for future > optimization.) A match is found only when BOTH the type and > value are the same. 'some_object' can be any object, but it > would be wise to not use floating point numbers or other things > that do not guarantee a valid '==' compare. I suppose these > ambiguous types could be flagged with an error from the compiler, > but I would hate to see a run time check (which would slow things > down, just to accommodate a bad programmer.) > > The match clauses do not 'fall through' automatically like a "C - > switch" statement-- (this is the source of many errors in 'C'.) > A clause can be forced to 'fall through' with the use of a > 'continue' statement, which jumps to the first statement in the > next match clause (because 'falling through' IS useful > sometimes.) I suppose the interpreter/compiler could flag an > error "UnreachableCode" (or 'BadIndentation') if 'continue' was > used by itself, and there were statements after it at the same > indentation level... > > The 'any' keyword could be changed to 'else' I suppose, but I > think the word 'any' "just plain sounds better when you say it", > and I like the 'match' keyword better than anything I have seen > or can think of... > > ================================= > > I have also been mulling over a new 'until' keyword-- it works > the same as 'while', but the body of the loop is executed first > before the conditional test is made the first time, and the sense > of the test is opposite (ie- the test must be FALSE for the body > of the loop to be executed again.) 'continue' jumps directly to > the conditional test, and 'break' jumps out of the loop (as expected): > > until something_becomes_true: > > print 'here we are in the body of the loop' > print 'which was executed at least once' > print "before the 'something_becomes_true'" > print 'test was made.' > > # we can skip to the test now with a 'continue': > if bad_programming_practice == TRUE: continue > print 'nope-- no continue' > > # we can get out of the loop with a 'break': > if another_bad_programming_practice: break > > # we probably need to stop the loop someday: > something_becomes_true = do_some_check() > > ================================= > > I doubt if any of this will ever make it into Python (well-- > maybe Python 3000)-- but it's fun to think about. > > Well, what do you think? > > --Ken Peek > Ken.Peek at SpiritSongDesigns.NOSPAM.com > (This letter is released to the public domain-- KP.) From bokr at oz.net Sun Mar 10 17:48:33 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 22:48:33 GMT Subject: financial calculations References: Message-ID: On 10 Mar 2002 08:39:09 -0800, aahz at panix.com (Aahz Maruch) wrote: >In article , >tc wrote: >> >>Is there a python module for financial calculations ? Using floats would >>give me too much problems with rounding errors. > >Not financial calculations per se, but your best bet until I finish my >BCD module is Tim Peters's FixedPoint.py. Unfortunately, the old FTP >link appears to be broken, so I've put up a copy on my Starship pages: >http://starship.python.net/crew/aahz/FixedPoint.py Now that you can subclass builtin types, are you going to take a different approach for >= 2.2 ? Regards, Bengt Richter From gh_pythonlist at gmx.de Wed Mar 13 12:12:21 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 13 Mar 2002 18:12:21 +0100 Subject: cgi xmlrpc anyone? In-Reply-To: References: Message-ID: <20020313171221.GC2611@lilith.hqd-internal> Le 13/03/02 ? 15:57, Robin Becker ?crivit: > Has anyone got a cgi version of an xmlrpc server? By that I mean a cgi > script which simulates being an xmlrpc server. We are allowed to do cgi > by our ISP, but not to run long running processes or to start up our own > servers etc. Rewind your newsreader a little, and you'll find http://groups.google.com/groups?q=group:comp.lang.python+xml-rpc+cgi+server&hl=de&selm=mailman.1014485857.32093.python-list%40python.org&rnum=1 I haven't tried it, only remembered reading the thread. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 16.3 ?C Wind: 2.0 m/s From george_planansky at harvard.edu Fri Mar 15 01:21:12 2002 From: george_planansky at harvard.edu (George Planansky) Date: 15 Mar 2002 01:21:12 -0500 Subject: Good book on Python? Message-ID: These two are uncommonly well-executed. Both have fine, insighful "Intro to Python" material. Both also have fine, insightful topical coverages. As a bonus, these two publishers use terrific layouts, fonts, ... so these are nice books to the eye and mind. The Quick Python Book 1999 Daryl Harms and Kenneth McDonald Manning Python Web Programming 2002 Steve Holden with David Beazley New Riders From gerson.kurz at t-online.de Tue Mar 5 02:25:41 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Tue, 05 Mar 2002 07:25:41 GMT Subject: I've got the unicode blues Message-ID: <3c846d80.95456984@news.isar.de> I have a C++ tool that takes two Windows .REG files and computes differences in them. The tool needs some reworking, so I thought why not rewrite that in Python, after all, Python Is Cool (TM). The trouble starts with Windows 2000: REGEDIT files are now UNICODE. Now, I have never had to dig very deep into UNICODE, so let me first recap my knowledge of that. Coming from a lowlevel assembler/C background, the most intuitive way of understanding the whole messy thing is this: ASCII characters are one byte each, UNICODE characters are two byte each. That is not correct, but its a pragmatic way of viewing things that has worked so far on the Windows implementation of UNICODE. (There are several variants of UNICODE strings in use in windows, most notably the difference being that the NT kernel strings have their length encoded in the first word; however, all UNICODE strings seem to be two bytes each, probably because that is most easy and fastest way to process them). Lets take a look at a hexdump of such a REGEDIT generated file. 000000: FFFE5700 69006E00 64006F00 77007300 ..W.i.n.d.o.w.s. 000010: 20005200 65006700 69007300 74007200 .R.e.g.i.s.t.r. ... (and so on)... The first two initial bytes look suspicious, but all bytes after that are like expected: two bytes per character, and the latin letters look like their ASCII counterpart. Some searching at http://www.unicode.org reveals that the first two bytes are identifiers for UNICODE files like this, called "BOM". See http://www.unicode.org/unicode/uni2book/u2.html, Chapter 2.7 for "BOM - Byte Order Marks") So, the "old" C++ programm, when it sees that the first two bytes are 0xFFFE, converts the rest of the file to ASCII characters, using a Windows function (WideCharToMultiByte), and then uses the normal C string functions on ASCII characters. Of course, the international characters UNICODE was invented for in the first place will get lost in such a situation, but it seemed to work fine for my needs. You can see the original C++ solution including the sourcecode here: http://www.p-nand-q.com/tools/regdiff.htm OK, that is basically my knowledge on the subject. Limited, granted, but it has sufficed so far in my pythonless past. Task 1: Reading in (such) a UNICODE file. I've asked that before a long time ago, see http://groups.google.de/groups?selm=ku4rzpsb67.fsf%40lasipalatsi.fi&output=gplain. Back then, in the times of 2.1, two solutions were proposed, neither of which work: >>> unicode(open('test.reg').read(), 'utf-8') Traceback (most recent call last): File "", line 1, in ? UnicodeError: UTF-8 decoding error: unexpected code byte and >>> import codecs >>> encode, decode, reader, writer = codecs.lookup('utf-8') >>> f = reader(open('test.reg')) >>> print f.readlines() [] OK, after a bit of searching I suspect I might have to go for utf-16, because that seems (to my limited UNICODE knowledge) like its the two-byte-codec I was looking for: >>> encode, decode, reader, writer = codecs.lookup('utf-16') >>> f = reader(open('test.reg')) >>> print f.readlines() [] Those are unexpected results in my view. I suspect the reason is the BOM is not handled by those functions. This is a working solution: def ReadLinesFromAnything( filename ): file = open(filename) data = file.read() file.close() if data[:2] == '\xff\xfe': return unicode(data[2:],"utf-16").split("\n") else: return data.split("\n") print ReadLinesFromAnything("test.reg") My take on this is, that the builtin file-readlines() *should* really know about BOM and return UNICODE strings if the file has a BOM. After all, if you call readlines() on a file, you expect it to contain lines of strings (either oldskool or UNICODE). You don't call readlines() on a binary file in the first place. I volunteer to patch the readlines function, if some other people out there feel that this is right, too. (Of course, with my -thanks to c.l.p.- newgained knowledge on using subclassed file objects, I can always use my own fileclass; so I would like to argue that at the very least some such fileclass should be part of the standard python lib). Task 2: Writing out (such) a unicode file. My first foolish attempt: lines = ReadLinesFromAnything("test.reg") file = open("test.out","wb") assert(type(lines[0])==types.UnicodeType) file.write(lines[0]) file.close() gives me the first line, all right, but in ASCII, not UNICODE! The same result for both file.write(u"test1") and file.write(unicode("test2","utf-8")) The data is ASCII, not (the-two-byte-kind-of-)UNICODE. Again, this is an unexpected result. Next, I tried file.write(unicode("test3","utf-16")) which raises the following exception: File "D:\Scripts\2002\02\read-unicode-lines.py", line 20, in ? file.write(unicode("test3","utf-16")) UnicodeError: UTF-16 decoding error: truncated data when I desperately try this: data = unicode(lines[0],"utf-16") file.write(data) I get the exception File "D:\Scripts\2002\02\read-unicode-lines.py", line 20, in ? data = unicode(lines[0],"utf-16") TypeError: decoding Unicode is not supported which a) supports my belief that exceptions suck, and b) is a stupid error message, because "decoding Unicode is not supported" is simply not true as a general statement about python. At this point, I'm quite frustrated with the joint union of (the way python handles UNICODE, the UNICODE standard, my knowledge of UNICODE, and the documentation on this in the Python help). The tutorial has a very brief section on UNICODE strings, but that is of no help. So I look up the Python Unicode Tutorial at http://www.reportlab.com/i18n/python_unicode_tutorial.html Finally I get an idea that seems to work: file.write(u"Hello".encode("utf-16")) The hexdump looks OK, too. But, when I try to write multiple strings, I run into trouble again, because each string is prefixed with the BOM, and not the file only: lines = ReadLinesFromAnything("test.reg") file = open("test.out","wb") for line in lines: file.write(line.encode("utf-16")) file.close() gives me a 0xFFFE for each line, which, to me, is an unexpected result again. The original REGEDIT generated file had just one at the beginning of the file. Of course, I can always join the strings and write them as one, but, to sum up my possibly-selfrighteous-complaints, I feel that there should be - *much* better support for UNICODE Textfiles in python - a *much* better documentation on this in python. So now I already feel much better :) From ChrisE at lantech.com Wed Mar 6 15:42:38 2002 From: ChrisE at lantech.com (Christopher Encapera) Date: Wed, 6 Mar 2002 15:42:38 -0500 Subject: CP4E was Re: Deitel and Deitel Book... Message-ID: As someone who just learned (a little) Python and wrote my first useful Ap a few days ago, I would like to jump in here with my 1.5 cents. Perhaps another limitation to this analogy is, it seems to me, that programming IS syntax and it's manipulation, and meaning is to be found in the (meaningful) manipulation of the data. A child, or adult, is inherently flexible when it comes to syntax, but a computer is (inherently) not. Thus: A child: I want da purtee pituur or Give me give me give me give me or Will you show me the pretty picture please? Whereas a computer accepts only (or some strict variant): # Pseudo code for opening an imaging app, and sending output to print device... ... ... ... Thus, the need for jumping right into syntax immediately (if you want to produce anything even remotely meaningful) Also concerning logic, I think it would be (perhaps) more accurate to say that people think (and solve most of their problems) at a higher level of abstraction - more in the realm of "meanings" and "relationships" where many different kinds of knowledge and inter-connectedness come into play. The thought world of formal logic and mathematics is too rigid to be the sole (or even a major factor) in most thinking. For example, my wife "thinks" that my desk is "too messy" and that I need to "organize it", but what she does not realize is that every pile is an organization (of sorts), and that I...etc. etc (until the end of our hopefully "meaningful" lives :) Christopher Encapera Lantech.Com chrise at lantech.com 502-267-4200 -----Original Message----- From: Geoff Gerrietts [mailto:geoff at gerrietts.net] Sent: Wednesday, March 06, 2002 1:32 PM To: python-list at python.org Subject: Re: CP4E was Re: Deitel and Deitel Book... Quoting Ramkumar Kashyap (rkashyap at sympatico.ca): > This is extremely non-intuitive to most people. Most 5,6,7 year olds > can speak fluently in their native languages, but how many of them could > tell you about vowels, consonants, nouns, verbs, adjectives. In fact > quite a few of them speak multiple languages, can easily differentiate > sentence structures in those languages, but would be hard-pressed to > give defintions of the above. > > So how come in programming, we ALWAYS jump into the constructs of a > language, rather than just doing, gaining proficiency and then > understanding how it is put together? I think the analogy here is interesting and useful, and bears consideration. I think that what you're asking for -- a reexamination of the pedagogy surrounding computer programming -- is useful. I would hesitate to suggest that your methodology is exactly appropriate, though. Here's why: ... My belief is that most people find computer programming to be difficult because logic is not the natural way people think; it is a forced mode. People tend to think intuitively, using "gut feelings" and good guesswork. That's the way we tend to summarize the knowledge of our experiences: as gut feelings. Expressing things in a purely logical fashion is consequently difficult for people, and very few ever receive formal training in logic. What's worse is that trying to teach logic at the fundamental level doesn't immediately apply. Logic itself is a tool that a person must learn to use, and could easily fill several courses by itself. ... From sholden at holdenweb.com Thu Mar 28 10:36:48 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 28 Mar 2002 10:36:48 -0500 Subject: Declare list of large size References: Message-ID: "Corrado Gioannini" wrote [ ... ] > another way to build a mutable multidimensional array is simply > >>> list = eval(repr([[0] * 2] * 2)) > avoiding the problem of multiple references to the same list object > > do you find it too dirty, unpleasant or un-pythonic? > (i'm really asking, it's not an ironic question ;-] ) > Very dirty! Somewhat unpleasant. My own view of its pythonicity is about -0.5, though arguably it's a pragmatic solution for small data sets. Building and evaluating a huge string isn't terribly good practice when there are other ways to achieve the same end programmatically. regards Steve From skip at pobox.com Fri Mar 8 13:22:42 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 8 Mar 2002 12:22:42 -0600 Subject: why is python slow? In-Reply-To: References: Message-ID: <15497.370.433742.862460@beluga.mojam.com> Donn> ... I wonder if all of Python's performance problems are really so Donn> deep. A few weeks ago someone posted some performance Donn> measurements and, among other things, noted that version 2.2 took Donn> twice as long just to start up. Did that appalling statistic Donn> attract any investigation into the cause, ... I believe the bulk of the effort in the 2.x series up to this point has focused on functionality ahead of performance. I'm sure there are things that can be done. Why not file a bug report, investigate and solve the problem, then grab some of that fame and fortune I alluded in my post seeking new developers yesterday? (I'm not picking on Donn, he just happens to be the one who raised this issue and gave me the nice segue.) The group of people who actively beat on the code is still fairly small. I count 38 people currently with checkin privileges. Of those, I count six whose SF usernames I don't even recognize. There are probably another five to ten who don't regularly contribute to either checkins or python-dev discussions. That means the effective pool of developers is really quite small. That, in turn, means we need more eyeballs. You don't need checkin privileges to tackle an open bug or investigate a problem and report its cause (a proposed solution would be helpful, but it might go a long ways towards fixing a problem if you can narrow down the cause a bit). Donn> I believe I recall something similar in 2.0, due to a mistake in Donn> site.py that was discovered during the beta releases. Not a hard Donn> problem, just one that wouldn't be noticed until someone wondered Donn> why performance went downhill so fast. We can wave our hands and Donn> say performance is a tough problem, but it would be more Donn> convincing if it looked like it was getting the most minimal Donn> attention. Agreed. When can we expect that patch? ;-) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From aahz at pythoncraft.com Tue Mar 19 23:10:09 2002 From: aahz at pythoncraft.com (Aahz) Date: 19 Mar 2002 23:10:09 -0500 Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: In article , Nick Arnett wrote: > >Anybody have any experience generating word frequencies from short >documents with Python and Perl? Given a choice between the two, I'm >wondering what will be faster. And a related question... any idea >if there will be a significant performance hit (or advantage?) from >storing the data in MySQL v. my own file-based data structures? > >I'll be processing a fairly large number of short (1-6K or so) >documents at a time, so I'll be able to batch up things quite a bit. >I'm thinking that the database might help me avoid loading up a lot of >useless data. Since word frequencies follow a Zipf distribution, I'm >guessing that I can spot unusual words (my goal here) by loading up >the top 80 percent or so of words in the database (by occurrences) and >focusing on the words that are in the docs but not in the set retrieved >from the database. Well, well, well, long time no see. Why not just use Verity? ;-) Seriously, for this kind of work, it's quite likely that Perl can be coded to be a bit faster than Python, but if you're expecting to need to do a lot of iterative work on your algorithms, programmer time will count for a lot, and Python will probably win there. Given that it sounds like you want to create your own inverted word index and do some sorting/searching based on word counts, it'll be hard to get more bang for the buck than a real database. Unless you're on a shoestring, consider getting a commercial database; you should probably also check to see whether MySQL or PostgreSQL will give you better performance. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. --Aahz From niemeyer at conectiva.com Sun Mar 24 15:50:09 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sun, 24 Mar 2002 17:50:09 -0300 Subject: [embed] PyImport_Import cannot find xml.py In-Reply-To: References: Message-ID: <20020324175009.D20294@ibook.distro.conectiva> [...] > >>> mod > [...] > so that says that the module is locatable by the interpreter. but when i > compile and run the following program: That's probably because this module is not in the module search path. Try running the following, after Py_Initialize(): PySys_SetPath(Py_GetPath()); > modname = PyString_FromString("xml"); > mod = PyImport_Import(modname); You may use PyImport_ImportModule("xml"). > Does anyone have a working example of Pure Embedding? It's for my personal > private project - for fun, supposedly, well before it was, not my > assignment. I've embedded python in a couple of projects. But the best project you will find is python, since it's "embedded" in itself. ;-)) -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From bokr at oz.net Fri Mar 15 15:55:10 2002 From: bokr at oz.net (Bengt Richter) Date: 15 Mar 2002 20:55:10 GMT Subject: Windows NT shell + extended characters. Bug or what? References: <10095d00.0203150319.12f9cbf9@posting.google.com> Message-ID: On 15 Mar 2002 03:19:20 -0800, nsbase at yahoo.co.uk (Noel Smith) wrote: >I've been recently using the Python shell on Linux as a handy way to >get character numbers from various extended LATIN-1 characters. > >i.e. For UK pound and Yen currency signs: > >>>> print ord('?') >163 >>>> print ord('?') >165 > >Which are the correct values. > >However I've recently installed python 7.2 on Windows NT4 and found it >gives the following results when using the command line shell: > >>>> print ord('?') >156 >>>> print ord('?') >157 > >Which is clearly wrong although strangely enough when I type the same >thing into IDLE on Windows NT, it produces the correct results. > >Is this a bug or is there some windows character mapping going on >behind the scenes which I've missed out? Is there any configuration >that I've missed out? > The console version is using ascii, and IDLE is probably using Courier new 10 point with latin-1 encoding. You can edit \Python2x\Tools\idle\config-win.txt (x>=1?) and change the font name to "terminal" and that will make idle close to the console font, but not exactly. The encoding has to change from latin-1 (?) to "Windows Characters" to get all the '\x80' to '\x9f' characters. I don't know how to control python's output encoding to select "windows characters" To see the characters in question, try this in the console window vs IDLE. >>> print ''.join([chr(c) for c in xrange(0x80,0x9f+1)]) ??????????????????????????????P? (That's pasted from the console window with whatever encoding conversion windows and my news reader may be doing). >>> print ''.join([chr(c) for c in xrange(0x80,0x9f+1)]) ???????????????????????????????? (That's from IDLE with terminal font, copied and pasted. The boxes are where the characters show up as on console, with the ??'s showing where characters are left out because the encoding is still latin-1, not "windows characters". Maybe there is an terminal font to show ascii for latin-1 encoding somewhere? >Any help would be really appreciated. > I guess the problem is being worked on. Regards, Bengt Richter From usenet at thinkspot.net Wed Mar 20 14:52:21 2002 From: usenet at thinkspot.net (Sheila King) Date: Wed, 20 Mar 2002 11:52:21 -0800 Subject: Remove empty lines References: Message-ID: On Wed, 20 Mar 2002 10:33:55 -0800, "Nick Arnett" wrote in comp.lang.python in article : > The problem is here, I think. Split in Python appears to return the > separator, so the '\n' characters are still there. After posting my last article, I went back and looked at this thread more carefully, and saw that it was using the re module. So, here is an example, also, using re: >>> mystring = 'Hello.\n\nHow are you today?\nFine, thanks.\n\n\nBye.' >>> re.split('\n',mystring) ['Hello.', '', 'How are you today?', 'Fine, thanks.', '', '', 'Bye.'] >>> filter(None, re.split('\n', mystring)) ['Hello.', 'How are you today?', 'Fine, thanks.', 'Bye.'] >>> for line in filter(None, re.split('\n', mystring)): print line Hello. How are you today? Fine, thanks. Bye. >>> By the way, I wonder that it is even necessary to trot out the re module for something as simple as removing comments and empty lines from code. You should be able to do this with just string methods, and it should be faster that way. What is the characteristics to determine a comment in Java? (I haven't coded in Java, so I'm not certain...I could make guesses, but...) Would it by any chance be similar to comments in C++? comment starts with // and all following characters on the same line, Or enclosed within /* */ Something this simple shouldn't require re. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsavitsk at e-coli.net Mon Mar 11 18:10:51 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 11 Mar 2002 23:10:51 GMT Subject: COM traceback translation References: Message-ID: <%Paj8.9138$k5.3534461@newssvr28.news.prodigy.com> next time i will rtfm before posting. from pg 621 of python programming on win32 ... "Before a thread can use COM, it must call ... CoInitialize()" -d "dsavitsk" wrote in message news:Wu8j8.9099$k5.3517961 at newssvr28.news.prodigy.com... > can anybody help with this one? there is a module called test_write. when > it is imported from a python prompt and generate_doc() is called it works > fine. When it is invoked by a COM object it throws this error. > > thanks, > > doug > > > > Traceback (most recent call last): > File "X:\epsp2\server\bin\test_write.py", line 5, in generate_doc > wordApp = win32com.client.Dispatch('Word.Application') > File "C:\Python\win32com\client\__init__.py", line 94, in Dispatch > dispatch, userName = > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > File "C:\Python\win32com\client\dynamic.py", line 81, in > _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python\win32com\client\dynamic.py", line 72, in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', > None, None) > > From peter at engcorp.com Sun Mar 10 20:07:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 20:07:02 -0500 Subject: How "expensive" are Exceptions? References: <3c8bf3ef@nntp.server.uni-frankfurt.de> <3C8C01D2.F9CC7C73@engcorp.com> Message-ID: <3C8C0336.B79D95AA@engcorp.com> Peter Hansen wrote: > Never do this. :-) You have not specific which exception you ^^^^^^^^ D'oh! I mean _specified_. -type-slower-think-faster-ly yr's, Peter From gh_pythonlist at gmx.de Sat Mar 2 12:43:35 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 2 Mar 2002 18:43:35 +0100 Subject: Forwarding messages with the email package In-Reply-To: <20020204041714.GA2141@lilith.hqd-internal> References: <20020204041714.GA2141@lilith.hqd-internal> Message-ID: <20020302174334.GA6868@lilith.hqd-internal> Le 04/02/02 ? 05:17, Gerhard H?ring ?crivit: > I'm having some problems with the new email package in Python 2.2. I > guess the reason is that I don't really understand MIME and I fear my > head will explode when I try to make sense of the source code of the > email package. > > What I'm trying to do is forward an email message with MIME. I. e. not > inline. I'm trying to duplicate what my MUA does. It creates a > multipart/mixed MIME doc with a text/plain part and a message/rfc822 > part, that contains the email to forward. So, my current code is: > [snip buggy code] Hello Gerhard, maybe you'll find the following code useful: #!/usr/bin/env python2.2 # # Written by: Gerhard H?ring (gerhard at bigfoot.de) # License: none/public domain import sys, os, smtplib, email from email.Message import Message from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEMessage import MIMEMessage class Config: """Settings for Spamcop reports. You must at least change SUBMISSION_ADDRESS to match the one you got from Spamcop. You also need to provide a valid SMTP server address, localhost is just fine on many *nix systems.""" SUBMISSION_ADDRESS = "Spamcop " SMTP_SERVER = "localhost" MY_ADDRESS = "you at yournetwork.net" SUBJECT = "Spam report" BODY = "Dear Spamcop! Please analyze the following spam." def strip_spamassassin_markup(spam): infile, outfile = os.popen2("spamassassin -d -") infile.write(spam) infile.close() return outfile.read() def main(): forwarded_mail = strip_spamassassin_markup(sys.stdin.read()) me = Config.MY_ADDRESS to = [Config.SUBMISSION_ADDRESS] message = MIMEBase("multipart", "mixed") message["Subject"] = Config.SUBJECT message["From"] = Config.MY_ADDRESS message["To"] = ", ".join(to) message.attach(MIMEText(Config.BODY)) rfcmessage = MIMEBase("message", "rfc822") message_to_forward = email.message_from_string(forwarded_mail) rfcmessage.attach(message_to_forward) message.attach(rfcmessage) smtpserver = smtplib.SMTP(Config.SMTP_SERVER) smtpserver.sendmail(me, to, message.as_string(unixfrom=0)) smtpserver.close() if __name__ == "__main__": main() Hmm, maybe I should submit a patch to the docs of the email module. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 2.4 ?C Wind: 3.4 m/s From dale at riverhall.NOTHANKS.co.uk Sun Mar 31 06:31:06 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sun, 31 Mar 2002 12:31:06 +0100 Subject: GUI programming References: Message-ID: <4fsdauofmus28t630866pgf4cu3n6bp16m@4ax.com> "Charl P. Botha" wrote: >With wxPython, one has to get, configure and build wxWindows first (and this >does take quite a while). Nonsense. 1. Download 2. Run Setup 3. Use it. The whole operation takes less than 5 minutes. Well - it does on Windows, anyway. -- Dale Strickland-Clark Riverhall Systems Ltd From dalke at dalkescientific.com Sun Mar 24 01:11:58 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 23 Mar 2002 23:11:58 -0700 Subject: list comprehension question References: Message-ID: Tripp Scott asked: >can i generate this list: > > [1, 1.1, 2, 2.1, 3, 3.1] > >with a list comprehension in a form of this: > > [SOMETHING for x in 1,2,3] > >and without using side effects like this? There is no way with list comprehensions which is more elegant than the standard solution, which is result = [] for i in 1, 2, 3: result.extend([i, i + 0.1]) Andrew dalke at dalkescientific.com From niemeyer at conectiva.com Thu Mar 7 13:19:25 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Thu, 7 Mar 2002 15:19:25 -0300 Subject: Python/C - Memory-Management In-Reply-To: References: Message-ID: <20020307151925.A2974@ibook.distro.conectiva> [...] > If another function calls init_mem, it can use memory until free_mem > is called... I want to do the same now in Python, but it seems as if > the static memory isnt kept somewhere? When I try accessing it, I get > a Segmentation Fault... Any suggestions? o Wrap your functions as a C type method. o Keep a static reference counter of the number of objects of this type alive. o Increase the counter every time a new object is born. o Decrease the counter every time an object dies. o When the counter goes from 0 to 1, allocate your memory. o When the counter goes from 1 to 0, deallocate it. o Keep in mind that if these functions share a common memory area, they may overlap each other, and crash your application, depending on the kind of operation they're doing. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From cliechti at gmx.net Sat Mar 2 10:00:48 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Mar 2002 16:00:48 +0100 Subject: a simple 'else' decrease speed by 1000 times. References: <3C80BBAC.2060600@student.kun.nl> <3C80E535.7000407@student.kun.nl> Message-ID: husam wrote in news:3C80E535.7000407 @student.kun.nl: > Chris Liechti wrote: > >> husam wrote in news:3C80BBAC.2060600 >> @student.kun.nl: >> >>>One else statement decrease speed by 1000 times. Why is that? >>> >> ... >> >>> if prv == n[i][-1]: n[i].append(new) >>> print count, '\t', i , '\t',n[i] >>> count = count +1 break else: >>> n[i].append(0) >>> >> >> 'cause your not "break"-ing here? but you do in the "if-then" part... > > > It should not break here. Because imagin that the matching 'prv' is > somewhere in a line in the middle of the file, the code will break > immediately at the first non-matching line. yes, you're right but that means that the else part is executen many times and that will slow down your program. -- Chris From ron.l.johnson at cox.net Mon Mar 4 20:38:30 2002 From: ron.l.johnson at cox.net (Ron Johnson) Date: Tue, 05 Mar 2002 01:38:30 GMT Subject: Converting mailbox formats References: Message-ID: On 04 Mar 2002, 10:01:40, Stephen R. Figgins wrote: > In article , Ron Johnson wrote: > > Are there pythonic methods for converting the MH message header > > format to the mbox message header format? > > Does it need to be in Python? Check out the packf command which comes > with MH, it will pack your folders into mbox style. > > -Stephen Nope, doesn't _have_ to be in python. Thanks for packf. However, doing it in would be nice, as a learning tool for the various mail-related modules... -- +------------------------------------------------------------+ | Ron Johnson, Jr. Home: ron.l.johnson at cox.net | | Jefferson, LA USA http://ronandheather.dhs.org:81 | | | | 484,246 sq mi are needed for 6 billion people to live, 4 ! ! persons per lot, in lots that are 60'x150'. | ! That is ~ California, Texas and Missouri. ! ! Alternatively, France, Spain and The United Kingdom. | +------------------------------------------------------------+ From arun-public at sharma-home.net Sun Mar 10 23:33:07 2002 From: arun-public at sharma-home.net (Arun Sharma) Date: Mon, 11 Mar 2002 04:33:07 GMT Subject: Iterating over unicode strings References: <3C8C3136.9050507@sharma-home.net> Message-ID: <3C8C3258.9030200@sharma-home.net> Forgot to mention - using python 2.1 -Arun Arun Sharma wrote: > > I would like to iterate over the following unicode string one character > at a time. > > line = u"??|| ?????? ?????" > for c in line: > print c > > fails miserably. What is the right way to do it ? I would also like to > be able to slice the string i.e. line[i] to get the i'th character. > > Thanks in advance, > > -Arun > From mwh at python.net Mon Mar 25 07:07:30 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 25 Mar 2002 12:07:30 GMT Subject: Python-2.2.1c1 Build Problems on Linux and AIX. References: Message-ID: ralph at inputplus.demon.co.uk (Ralph Corderoy) writes: > Hi, > > > > With Python-2.2.1c1, I find `make test' fails on my old version of > > > Linux/x86 and it fails to build on an also old version of AIX. ... > > > I can see the problem with the AIX build. Linux SIGSEGVs in > > > test_calendar on a call to strftime. > > OK, I've raised all the AIX problems on SourceForge now. By working > around them I can get a python executable and most of the library. > (Modules/_cursesmodule.c fails to compile but I'm not sure if is > intended to be widely buildable.) I'll try to sort out the AIX mess to the best of my ability, but I think my priority is more not breaking any other platform... > The Linux/x86 problem has also been fixed and thanks to Tim an overall > improvement made, e.g. month_name[0]. Yep. > Thanks for everyone's help, Thanks for yours! Cheers, M. -- You're posting to a Scheme group. Around here, arguing that Java is better than C++ is like arguing that grasshoppers taste better than tree bark. -- Thant Tessman, comp.lang.scheme From frederic.giacometti at arakne.com Mon Mar 4 16:31:08 2002 From: frederic.giacometti at arakne.com (Frederic Giacometti) Date: Mon, 04 Mar 2002 21:31:08 GMT Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> Message-ID: <3C83E848.2BB58E2B@arakne.com> Aahz Maruch wrote: > In article <3C838150.97A86F52 at arakne.com>, > Frederic Giacometti wrote: > >Aahz Maruch wrote: > > > >More precisely, the point of stackless is to dispense from OS threads > >(and Python lock) overheads for running threaded Python bytecode. > >However, OS threads are still required to take charge of calls to > >blocking C function (usually from external C libraries) that one want > >to run asynchronously to the PVM; there is no turn around to this. > > Sure there is: just use Python's standard threading capabilities and > release the Global Interpreter Lock, just like you do now. I will grant > that it's not the most convenient thing in the world, and maybe we'll > want to fix this in the future, but I think that getting Stackless done > and squared away is more important than resolving this in the cleanest > possible fasion. ??? FYI, Python threads rely on the underlying OS thread switching + OS lock synchronization API.... It's not because you don't see it that it is not used :)) Furthermore, as everyone in this thread knows by now, stackless is a pre-requisite to Python microthreads. Thanks you for reminding it :)) FG From gcordova at hebmex.com Tue Mar 26 10:49:25 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Tue, 26 Mar 2002 09:49:25 -0600 Subject: Optimizations (was Re: reduce vs. for loop) Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689D5@SRM201002> > > > >Just out curiosity, > > >why is fact2 a bit faster than fact1? > > > > > >def fact1(n): > > > return reduce (operator.mul, range(1L,n + 1)) > > > > > >def fact2(n): > > > result = n * 1L > > > for i in range(1 , n): > > > result *= i > > > return result > > > > Try this: > > > > def fact3(n): > > mul = operator.mul > > return reduce(mul, range(1L, n+1) ) > > operator.mul will be evaluated only once in even in fact1, so this > shouldn't make any difference. > > Just And I re-ran the tests using the normal functions, and then again after applying psyco.bind() to them. Here's the times with n=10000: ===== TEST PRINTOUT ===== Running factorial tests (n=10000) fact1: 5.16 seconds. fact2: 4.73 seconds. fact3: 4.78 seconds. ** Applying psyco.bind() ** Rerunning tests. psyco: sys._getframe() not supported; support for warnings is only partial fact1: 4.77 seconds. fact2: 4.45 seconds. fact3: 4.78 seconds. Press to quit. ========================= Oh well. :-) -gustavo From stephen at xemacs.org Wed Mar 6 21:29:18 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 07 Mar 2002 11:29:18 +0900 Subject: The language vs. the environment References: Message-ID: <87y9h5m7pd.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Skip" == Skip Montanaro writes: Skip> There has been a huge amount of recent PEP activity related Skip> to further enhancements to the language. I think in general Skip> that if more of this energy was directed at the overall Skip> environment (library, support tools, installers, Skip> documentation, etc) we'd be better off in the long run. There are also proposed enhancements that are dangerous as additions to the language, while they would be unobjectionable (and serve the purpose equally well) as part of the environment. (Cf. PEP 263 discussion.) -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From philh at comuno.freeserve.co.uk Fri Mar 15 18:16:14 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 15 Mar 2002 23:16:14 +0000 Subject: Implementation Advice References: Message-ID: On Fri, 15 Mar 2002 10:28:10 -0800, Ken wrote: >Hey everyone.. > >I'm trying to create a system where users log in, and based on how they log >in or who they log in as, they get a different set of functionality. > >A really simple example would be a multi-room chat, where each room has some >common functionality (ie.send/receive messages) and some extras like >different color text. > >I'd like to keep the functionality for each room in a separate file. > >My question is, should each file have a class declaration (using inheritance >where appropriate) containing the necessary additional functions, >initialization, etc.. Or, should each file contain a series of functions? >One common to all files to initialize a room and then modify it and add >functions to it as necessary? I'd use classes. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From James_Althoff at i2.com Tue Mar 5 14:30:35 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 11:30:35 -0800 Subject: Status of PEP's? Message-ID: [Tim Delaney] > Just realised something for PEP 276. > > If it passes, > > for i in dictionary.has_key(item): > > would then be valid ... as it would return 0 or 1. On the other hand, if it *doesn't* pass dictionary.has_key(item) ** dictionary.has_key(item) will be valid . > This may or > may not be considered a bad thing - it would be equivalent to: > > if dictionary.has_key(item): > > for any condition that does return 0 or 1. As you point out, this oddity is odd in a relatively benign sort of way, at least . More seriously though, I think that this falls into the category of trade-offs that one deals with when taking advantage of Python's "less explicit, but more practical" choice of using domain values for true/false rather than using explicit boolean objects. Jim From trentm at ActiveState.com Mon Mar 18 16:09:16 2002 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 18 Mar 2002 13:09:16 -0800 Subject: Windows Installation In-Reply-To: ; from fperez528@yahoo.com on Fri, Mar 15, 2002 at 04:25:13PM +0000 References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: <20020318130916.A24888@ActiveState.com> [Fernando P?rez wrote] > Ah, thanks for the info. I assume those calls are basically wrappers for > clean access to those registry keys which ultimately hold the information, I assume so too. :) > > The bulk of what I had in mind (but didn't clearly express :) remains: you > can't just assume C:\Windows\Start Menu, you need to get the actual value > of that directory in some form (and your api solution is much better than > my registry access). Yup. Trent -- Trent Mick TrentM at ActiveState.com From threehounds at worldnet.att.net Wed Mar 13 22:35:12 2002 From: threehounds at worldnet.att.net (Matthew Austin) Date: Thu, 14 Mar 2002 03:35:12 GMT Subject: basic statistics in python References: Message-ID: RPy has not been ported to Windows yet. "Emile van Sebille" wrote in message news:a6on8n$frj93$1 at ID-11957.news.dfncis.de... > "dsavitsk" wrote in message > news:OvQj8.10177$k5.3810357 at newssvr28.news.prodigy.com... > > hi all, > > > > never having done numeric calculations in python* i am seeking advice > on how > > to best go about doing some basic statistics. in particular, i need > to find > > standard deviations and point bi-serial correlations**, and i am > seeking > > advice on the best way to go about it. i know how to do them, but i > am > > wondering if there are prebuilt modules that might simplify the task. > > You might want to take a look at rpy at > http://www.cmat.edu.uy/~walterm/rpy/ > > -- > > Emile van Sebille > emile at fenx.com > > --------- > From amoustafa at pobox.com Thu Mar 21 03:40:49 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Thu, 21 Mar 2002 08:40:49 GMT Subject: MySQL's applicability (was: Java and Python) References: <3C96DBB4.6040109@pobox.com> <3C984F44.1090001@pobox.com> <3C9887B9.6090603@thinkware.se> <82B3E32A4EFF0E57.126AAAECC4E2B809.F8613C4251DB7A4B@lp.airnews.net> Message-ID: <3C999C77.3010801@pobox.com> Cameron Laird wrote: > Undeniably. That's certainly the conclusion of "the first time > a computer publication has published database benchmark results > ...", as *eWeek* did in its 25 February 2002 issue. The subtitle > of the article was "Oracle9i and MySQL top the field ..." > > So, no, MySQL is NOT "related to small to mid-size web applica- > tions". They were measuring the response times. A file-based application may do the function with a response time in the same order which doesn't imply that a file-based app is comparable to Oracle 9i. Their test generated 200,000 orders, that is a small-size web application, right? Also, parts of the test used the nontransactional engine of MySQL! -- Ahmed Moustafa From emile at fenx.com Fri Mar 15 21:56:16 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 15 Mar 2002 18:56:16 -0800 Subject: Wrong transfer of data (ODBC) References: Message-ID: "Santiago" wrote in message news:a6tdj0$rfb$1 at vg170.it.volvo.se... > I was trying to use the 'Python ODBC Notes (Windows Only)' wrote by John > Dell'Aguila 2/11/98.(at the bottom you will see the program) > I used the ODBC using Python Database API. from the AS/400 database to the > PC Windows. > > But when I get the data from the AS/400 I get the string fields okay, but > the fields with decimals , like price, it appears with wrong decimals. > The price field in the AS/400 has eleven digits (9 integers and 2 decimals). > > For example, the data in the AS/400 is 15860.94 but what I get is > 15860.94000000001. http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp -- Emile van Sebille emile at fenx.com --------- From nikander at nc.rr.com Tue Mar 12 15:13:39 2002 From: nikander at nc.rr.com (Rob Nikander) Date: Tue, 12 Mar 2002 20:13:39 GMT Subject: Python embedded like PHP Message-ID: Are there any projects out there that allow you to embed python in HTML like PHP? I like the PHP-style of embedding the bits of program in HTML, but I'd like to use python... Something like: " for reptile in ["Crocodile", "Python", "Iguana", "Tortoise"]: print "
  • %s
  • " % reptile print "" ?> From kp87 at lycos.com Sat Mar 9 05:12:45 2002 From: kp87 at lycos.com (kevin parks) Date: 9 Mar 2002 02:12:45 -0800 Subject: Voss 1/f noise algo help References: <5e8bd451.0203080150.44a259ce@posting.google.com> Message-ID: <5e8bd451.0203090212.6c7a2434@posting.google.com> Thanks for your reply. I will try out your approach. However i am still hoping to get the above working as well as it doesn't require an FFT. I see you also do micro-tonal music. Nice to meet you. From boud at valdyas.org Sat Mar 2 12:25:26 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sat, 02 Mar 2002 16:25:26 -0100 Subject: PyQT and shaped windows in X References: <3c80ef25$0$90048$e4fe514c@dreader1.news.xs4all.nl> Message-ID: <3c80efbe$0$90048$e4fe514c@dreader1.news.xs4all.nl> Boudewijn Rempt wrote: > > Well, it certainly isn't very Qt specific. > I meant to type: PyQt specific. -- Boudewijn Rempt | http://www.valdyas.org From guido at python.org Sat Mar 30 18:36:07 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 18:36:07 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Your message of "Sat, 30 Mar 2002 17:44:12 EST." References: Message-ID: <200203302336.g2UNa8F10511@pcp742651pcs.reston01.va.comcast.net> > [Guido, on why operator.truth() should change to return True/False] > > Tim must be missing something. The obvious way to turn a bool b into > > an int is int(b). [[Tim, being difficult] > It's also an incorrect way for me, No it's not, note that I said "turn a bool b into an int". Clearly the assumption there is that b is a bool, not an arbitrary value in whose truth value we're interested. > because I meant "true/false expression" in the way Python has always > meant it, e.g. operator.truth([]) == 0, but int([]) raises an > exception. The alternative int(bool(b)) is not obvious (else you > would have thought of it first ), and becomes needed only if > operator.truth() is changed. IMO, bool(x) is the right way to "normalize" any value into a truth value. The way I think of operator.truth(x) is as something returning a normalized truth value. Since we're changing all places that return standard truth values from returning 0/1 to returning False/True, I don't see why operator.truth() should not follow suit. If we think that we can change comparisons, isinstance(), s.islower() and so on to return a bool without breaking much, I see no reason why we can't change operator.truth(). > > Having to import the obscure 'operator' module for this purpose is > > backwards. > > Under the PEP it's extremely easy to get a bool result (bool(b)), so > I favor presuming that anyone bothering to use operator.truth() will > do so because bool() doesn't do what they want; No, they do so because they wrote the code before bool existed. > and if they're using truth() in 2.2, are doing so because they > specifically want a 0/1 result. And since False==0 and True==1, that's what they're getting. I'm going to make this a BDFL pronouncement; I understand your argument but I don't agree with it. --Guido van Rossum (home page: http://www.python.org/~guido/) From camh at zip.com.au Tue Mar 12 17:30:40 2002 From: camh at zip.com.au (Cameron Hutchison) Date: Wed, 13 Mar 2002 09:30:40 +1100 Subject: Setting UNIX environment with a Python script References: <3C8D143A.17963385@all.com> Message-ID: On Tue, 12 Mar 2002 13:25:57 +1100, Grant Edwards wrote: > In article , Cameron > Hutchison wrote: > >> What you need to do instead is have your python program print on stdout >> the name of the ora_env file to source. Then you invoke your python >> script from your shell login script like this (bourne style shell >> assumed): >> >> eval "source ora_env.`get_ora_name`" > > Another common method is to have your Python program write the shell > commands to stdout, then execute them with something like > > eval `myPythonProgram` > While that would work fine, I dont think it's a terribly good idea. I think it would be cleaner to keep the shell syntax in a shell script and avoid having the python program assume the scripting environment it is returning to. From jbublitzNO at SPAMnwinternet.com Sun Mar 24 04:23:01 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Sun, 24 Mar 2002 09:23:01 GMT Subject: C++ Embedding Problem - Import Error References: <3C9C4D48.7010000@SPAMnwinternet.com> Message-ID: <3C9D9A1F.3010701@SPAMnwinternet.com> Gustavo Niemeyer wrote: > [...] >>Just to be clear, I'm linking libpython into another .so >>lib that's dlopened by an app. There is no possibility of >>linking Python directly with the app (or I wouldn't be >>writing a plugin in the first place). > You must open your plugin with RTLD_GLOBAL, otherwise the > symbols inherited from libpython.a won't be available for the > dynamic loaded modules. I was afraid that might end up being the case. Since I don't have control of the code that loads the library, I'll probably have to load that part in my code. Thanks. Jim From claird at starbase.neosoft.com Fri Mar 1 09:56:32 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 1 Mar 2002 08:56:32 -0600 Subject: Useful, robust shell utilities References: Message-ID: In article , Erno Kuusela wrote: >In article , Jonathan Gardner > writes: > >| Is there an effort to make a robust, useful shutil module that has the >| equivalent of the unix shell utilities? ... >| nice if they ended up being compatible with Windows and Macintosh - give >| them some powerful tools they didn't even know existed! > >you can get the real things for windows with cygwin. macintoshes are >natively unix-based these days. > >if you decide to go ahead with it, you could look into > for ideas and inspiration. ... Also . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jkraska at san.rr.com Sun Mar 10 21:34:39 2002 From: jkraska at san.rr.com (Courageous) Date: Mon, 11 Mar 2002 02:34:39 GMT Subject: How "expensive" are Exceptions? References: <3c8bf3ef@nntp.server.uni-frankfurt.de> Message-ID: <6b6o8u46eqbf0l4u01ais4es3j47bsqr1o@4ax.com> >Hi, given the fact that excpetion handling can be very >expensive in languages like C++ - is python similar in >this aspect? No. In Python, exceptions are practically free in comparison. They are implemented internally by sending back the appropriate return code and setting an error node. C// From hst at empolis.co.uk Fri Mar 1 08:06:21 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Fri, 1 Mar 2002 13:06:21 -0000 Subject: SAX-Parser entity Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220AEE@hendrix.empolisuk.com> I would guess that your document is in ISO 8859/1 (otherwise known as latin-1). XML parsers must be able to parse utf-8 and utf-16 and may support other encodings. If your parser supports latin-1 then modify the XML declaration. Otherwise use the codecs module. > -----Original Message----- > From: fabi.kreutz at gmx.de [mailto:fabi.kreutz at gmx.de] > Sent: 01 March 2002 12:43 > To: python-list at python.org > Subject: SAX-Parser entity > > > Hi, > > I spend the last 3 hours browsing FAQs and Mailinglist - > without success - > but have nevertheless the feeling, that this is a very easy question: > > I try to use the minidom XML-Parser to parse my little file > in order to > generate HTML Code. > Being german, I really like to use Umlauts but minidom does not. > Traceback (most recent call last): > File "", line 1, in ? > File > "/usr/lib/python2.0/site-packages/_xmlplus/dom/minidom.py", > line 908, in parse > return _doparse(pulldom.parse, args, kwargs) > File > "/usr/lib/python2.0/site-packages/_xmlplus/dom/minidom.py", > line 900, in _doparse > toktype, rootNode = events.getEvent() > File > "/usr/lib/python2.0/site-packages/_xmlplus/dom/pulldom.py", > line 251, in getEvent > self.parser.feed(buf) > File > "/usr/lib/python2.0/site-packages/_xmlplus/sax/expatreader.py" > , line 92, in feed > self._err_handler.fatalError(exc) > File > "/usr/lib/python2.0/site-packages/_xmlplus/sax/handler.py", > line 38, in fatalError > raise exception > xml.sax._exceptions.SAXParseException: :29:19: not > well-formed > > where Character 19 in Row 29 is the occurence of an ?. > > After browsing the FAQs I changed the default encoding in site.py to > iso-8859-1, which had some nice effect, but not on minidom. > Some more browsing let me tell pulldom to use StringIO > instead of cStringIO, > still no success. > > Since I want to use the text in HTML it would be enough, if I > could use > the ü instead, but parse gives me in this case > ... > File > "/usr/lib/python2.0/site-packages/_xmlplus/sax/handler.py", > line 38, in fatalError > raise exception > xml.sax._exceptions.SAXParseException: :29:19: > undefined entity > > where 29:19 is the &. > I tried to protected it with an \ or / but still no success. > > Can anybody help me with this? > > -- > The irony of the Information Age is that it has given > new respectability to uninformed opinion. > - John Lawton > -- > http://mail.python.org/mailman/listinfo/python-list > > _____________________________________________________________________ > This message has been checked for all known viruses by Star Internet > delivered through the MessageLabs Virus Scanning Service. For further > information visit http://www.star.net.uk/stats.asp or > alternatively call > Star Internet for details on the Virus Scanning Service. > _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From whale at mycameo.com Thu Mar 7 01:20:40 2002 From: whale at mycameo.com (whale) Date: Thu, 7 Mar 2002 14:20:40 +0800 Subject: Problem with opening PCX image Message-ID: When I opened PCX images with PIL, most images work fine. However, there is one image I opened it with the same procedure, the exception occured. I can view this image with different image viewer. I am not sure how does this happen? Is this the bug existing in PIL module? I put a problematic image online at http://www.mycameo.com/download/fromQA.PCX Please take a look at it. Thanks a lot. PythonWin 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - see 'Help/About PythonWin' for further copyright information. >> import Image >> im = Image.open("fromQA.PCX") >> im.load() Traceback (most recent call last): File "", line 1, in ? File "D:\Python21\Image\PIL\ImageFile.py", line 166, in load raise IOError, "decoder error %d when reading image file" % e IOError: decoder error -1 when reading image file From dale at riverhall.NOTHANKS.co.uk Tue Mar 26 15:19:00 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Tue, 26 Mar 2002 20:19:00 +0000 Subject: running python on win2k References: <3CA0C734.59DB3CE3@ccvcorp.com> Message-ID: Jeff Shannon wrote: >From the command line, simply type "python", or "python myscript.py". If >you have .py files registered as executable, you can simply type >"myscript.py" as well -- I know that ActiveState's distribution will do >this on installation; I haven't tested whether PythonLabs' installer >automatically does this, but it's likely. It does but it doesn't register the Python exentions as runnable. If you register the correct extensions you can run a program just by typing the name (without the extension) at a command prompt, as long as the module is in your path or current directory. To register the Python extensions, you need to add the following to you PATHEXT environment variable: .py;.pyc;.pys;.pyw Permanent changes to PATHEXT can be made from the properties of My Computer in Win2K and NT4 -- Dale Strickland-Clark Riverhall Systems Ltd From phd at phd.pp.ru Sat Mar 16 15:48:24 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sat, 16 Mar 2002 23:48:24 +0300 Subject: SocketServer.ThreadingTCPServer question In-Reply-To: ; from spokra@home.com on Sat, Mar 16, 2002 at 12:34:17PM -0800 References: Message-ID: <20020316234824.A10025@phd.pp.ru> On Sat, Mar 16, 2002 at 12:34:17PM -0800, Steven Pokrandt wrote: > trying to use the threading tcp server class. It all works right from > a quick look. But when I run top I see many processes leading me to > think it is really forking. Linux shows threads as separate processes in top/ps/etc. But they are threads. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From garret_mcgraw at yahoo.com Fri Mar 1 09:40:54 2002 From: garret_mcgraw at yahoo.com (garret_mcgraw) Date: Fri, 01 Mar 2002 14:40:54 -0000 Subject: I am not getting group messages Message-ID: I am not getting any group messages. Could any body tell me why? GM From fredrik at pythonware.com Tue Mar 19 15:27:00 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Mar 2002 20:27:00 GMT Subject: Extending Python/Tkinter References: <5acdbd0c.0203190838.20c3733e@posting.google.com> Message-ID: Cris Eck wrote: > Initially I thought I could get a drawable, display and graphics > context from the Tk C API. Then I saw that Tkinter is using the > Tcl interpreter and not calling the Tk routines directly. well, the fact that there's a Tcl interpreter involved doesn't mean that you won't end up in the Tk library when it's time to draw something... one way to implement this is to use the Tkinter 3000 WCK to take care of the Tkinter interface bit, and call your widget code from relevant ui_handle methods, e.g: # tkinter 3000 framework from tk3 import Widget # import map widget driver import _mapwidget class MapWidget(Widget): def ui_handle_resize(self, width, height): _mapwidget.resize(self.winfo_id(), width, height) def ui_handle_repair(self, draw, x0, y0, x1, y1): window = self.winfo_id() _mapwidget.redraw(self.winfo_id(), x0, y0, x1, y1) in the _mapwidget extension, use the window handle to get the display (etc) using ordinary Tk calls. more info here: http://effbot.org/tkinter From cliechti at gmx.net Thu Mar 21 14:30:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 21 Mar 2002 20:30:01 +0100 Subject: IntSpan? References: <3c97c886@news.nwlink.com> <3C99F049.5A78B149@metaslash.com> <3c9a1ae9$1@news.nwlink.com> Message-ID: "Jeff Bienstadt" wrote in news:3c9a1ae9$1 at news.nwlink.com: > "Neal Norwitz" wrote in message > news:3C99F049.5A78B149 at metaslash.com... >> Jeff Bienstadt wrote: >> > I'm looking for something that inteligently handles and manipulates >> > spans of integers, such as: 2-356,456,458-500 >> >> I'm not familiar with IntSpan, but have you looked at the builtin >> range()? >> >>> print range.__doc__ >> range([start,] stop[, step]) -> list of integers >> > Yes, I knew about range, but that's not quite what I'm looking for. > > Using range to create the full list of integers seems prohibitively > expensive --- spans in the range 1-400000 are not at all out of > line. > ... > I can see from your reply how range could be useful in the > implementation, for creating temporary lists of values to work > with but again, since the spans could be quite long, this > seems expensive. in ypthon 2.2 you could do that with a generator. >>> form __future__ import generators >>> def spanning(): ... for i in xrange(3,10): ... yield i ... yield 99 ... for i in xrange(20,30): ... yield i testing: >>> for i in spanning(): print i using xrange instead of range does not allocate a list but generates the vaulues when they're needed. chris -- Chris From thoa0025 at mail.usyd.edu.au Sun Mar 24 15:10:22 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 24 Mar 2002 20:10:22 GMT Subject: [embed] PyImport_Import cannot find xml.py Message-ID: I've located the problem down to this. i have a file "xml.py" which has a function "getProjects()" which i would like to access from c. In the interpreter i execute the following commands: Python 2.1.2 (#2, Jan 18 2002, 11:23:35) [GCC 2.95.2 19991024 (release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> modname = "xml" >>> mod = __import__(modname) >>> mod >>> so that says that the module is locatable by the interpreter. but when i compile and run the following program: #include int main (int argc, char *argv[]) { // declare variables PyObject *modname = NULL; PyObject *mod = NULL; // init Py_Initialize(); modname = PyString_FromString("xml"); mod = PyImport_Import(modname); if (mod == NULL) printf("mod is null\n"); Py_XDECREF(mod); Py_XDECREF(modname); Py_Exit(0); } it prints out "mod is null" meaning it cant find the module. Does anyone have a working example of Pure Embedding? It's for my personal private project - for fun, supposedly, well before it was, not my assignment. Please :( Cheeeeeeeeeeers -- Trung Hoang Final year Undergraduate of Computer Science and Technology University of Sydney, Australia. From logstx at bellatlantic.net Sat Mar 30 18:00:17 2002 From: logstx at bellatlantic.net (logistix) Date: Sat, 30 Mar 2002 23:00:17 GMT Subject: list of functions References: <01rp8.34168$tg4.401910@vixen.cso.uiuc.edu> Message-ID: <5srp8.1166$AE1.554@nwrddc03.gnilink.net> Is this what you want? x = (1,2,3) #create a tuple apply(list_of_functions[0], x) #apply args to function #or list_of_functions[0](*x) -- - "John" wrote in message news:01rp8.34168$tg4.401910 at vixen.cso.uiuc.edu... > > Hi, > > I was glad to find that Python allows the following: > > def addone(a): return a+1 > list_of_functions=[addone] > list_of_functions[0](1) --> returns 2 > > However, what if the functions require more than one arguments? say > def addall(a,b,c): return a+b+c? > Though list_of_functions[0](1,2,3) works, I'd like to make (1,2,3) as > variables.. How do I pass the variables to such functions? > > From logiplexsoftware at earthlink.net Tue Mar 26 13:43:30 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 26 Mar 2002 10:43:30 -0800 Subject: personel CDDB In-Reply-To: <4a7fde99.0203251840.2aafdf58@posting.google.com> References: <4a7fde99.0203251840.2aafdf58@posting.google.com> Message-ID: <20020326104330.3fca8859.logiplexsoftware@earthlink.net> On 25 Mar 2002 18:40:01 -0800 Ryan wrote: > I'm thinking about writting a personel CD database that links into RDB > so you can put in a cd and have python link to crdb and make a > personel database to keep track of your cd's (and maybe rip mp3s from > it and store them in the database to) I'm wondering if many people > would have an interest in this so I will know whether to just write it > so it works, or write it the right way, (ie. pure python and a gui > using anydb). If it's just for me it won't be nearly as robust and > will use a lot of win32 extensions (for speed). If there is enough > interest I may even post to source-forge. Be sure and check the vaults first, as there are already some projects that address things related to this (accessing CDDB, reading ID3 tags, etc), so you can save yourself some work and make someone else happy by using their code ;) http://www.vex.net/parnassus/ -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From thoa0025 at mail.usyd.edu.au Sun Mar 24 02:28:50 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 24 Mar 2002 07:28:50 GMT Subject: even a typing noob :) References: Message-ID: because absolutely :) -- Trung Hoang Final year Undergraduate of Computer Science and Technology University of Sydney, Australia. From ingoogni at CUT.THIS.OUT.home.nl Fri Mar 29 08:10:50 2002 From: ingoogni at CUT.THIS.OUT.home.nl (ingo) Date: Fri, 29 Mar 2002 13:10:50 GMT Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> <3CA3D86A.7080806@yahoo.com> <67abb823.0203290500.3a3a7da1@posting.google.com> Message-ID: in news:67abb823.0203290500.3a3a7da1 at posting.google.com Sloth wrote: > On the other hand, less is more in > this scenario and, frankly, now I'm just being stubborn and trying to > get Python to act as its own CGI server. ---%<------%<--- from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler import os port = 80 serv = HTTPServer(('', port), CGIHTTPRequestHandler) print "Running Web Server at port: ", port serv.serve_forever() ---%<------%<--- Then point your browser to http:\\localhost\somehtmlfile.html Ingo From martin at v.loewis.de Thu Mar 7 03:58:37 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Mar 2002 09:58:37 +0100 Subject: Passing Unicode strings to Database References: Message-ID: Mikhail Astafiev writes: > runes is array.array('H') containing Unicode string. > > Database string field has "ntext" type. How can I overcome this > problem? I recommend to use Python 2.x, and use Unicode objects to represent Unicode strings. For Python 1.5, if you are using the Win32 extensions, you can also try to use Mark's Unicode type. Regards, Martin From tdi01fhu at syd.kth.se Tue Mar 26 14:23:08 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Tue, 26 Mar 2002 20:23:08 +0100 Subject: stop Message-ID: ah, the joy. thank you. /fredrik >>> "Brian Quinlan" 03/26/02 20:22 PM >>> Fredrik wrote: > Ok, so I'm going to be quite honest, I dont write perfect code, so today > while working in PythonWin I imported a file. Problem was that the file > happened to contain an infinte loop, which the interpreter gladly ran, > untill I killed the entrire program. Annoying. Is there no %&/!#ing stop > button in PythonWin? When PythonWin is running, there should be a PythonWin icon in the tray bar. Right click on that and select "Break into running code". Cheers, Brian From tim-dated-1015966132.70491e at catseye.net Tue Mar 5 15:48:51 2002 From: tim-dated-1015966132.70491e at catseye.net (Tim Legant) Date: 05 Mar 2002 14:48:51 -0600 Subject: Python song? (Re: Python isn't necessarily slow) In-Reply-To: References: Message-ID: <86n0xmg2q4.fsf@skitty.catseye.net> writes: > On Tue, 5 Mar 2002, Greg Ewing wrote: > > > Siegfried Gonzi wrote: > > > > > > Python isn't necessarily slow: > > > > That sounds like a great title for a Python > > song: "It Ain't Necessarily Slow!" > > Hmm... 'necessarily' is a bit cumbersome. The "ain't" makes me think of > country songs from the U.S., so how about "Just cuz I slither, it don't > mean I'm slow"? Oh, are you from across the pond? It was either Bronski Beat or the Communards who did an interesting cover of Ain't Necessarily So in the early '80s - I think both groups were Brits.... It's in more of a Broadway musical style than country, though. Anyhow, the chorus of the song, which is the part I was spoofing, goes It ain't necessarily so. It ain't necessarily so. Things that you're liable To read in the bible Ain't necessarily so. Tim From michele at diee.unica.it Mon Mar 25 14:40:50 2002 From: michele at diee.unica.it (Michele Marchesi) Date: Mon, 25 Mar 2002 20:40:50 +0100 Subject: XP2002 - Call for Participation Message-ID: <3C9F7D42.3080506@diee.unica.it> ---------------------------------------------------------------- Apologize if you receive this announcement more than once. ---------------------------------------------------------------- CALL for PARTICIPATION XP2002 - http://www.xp2002.org/ 3rd Int.l Conference on XP and Agile Processes in Software Engineering May 26-29, 2002 - in beautiful Alghero, Sardinia, Italy The Third International Conference on XP and Agile Processes in Software Engineering, XP2002, is a consolidated international forum to learn, discuss and advance the state of the art of the theories and the practices related to Extreme Programming and other agile techniques for software development! The Conference Schedule includes Workshops, Tutorials, Activity Sessions, Panels, Presentations, to accommodate the different needs of participants: * 6 Workshops and 23 Tutorials on every aspect of XP and other agile methodologies, given by world leading researchers, * 6 invited talks from undisputed authorities of software engineering and agile processes, including Dave Parnas and Kent Beck, * panels and presentations of experiences and ideas * studies from researchers and practitioners from all over the World. XP2002 WORKSHOPS are open for enrollment: - Bringing Structure to Experience With Agile Development - XP & Database Administration (afternoon) - Testing in XP - Distributed Agile Software Development - Experience Exchange II - Design & Refactoring The participation to XP2002 is limited to 300 people for space reasons... register early. The deadline for reduced fees is April, 1, 2002. For more information and registration see: http://www.xp2002.org or contact: Prof. Michele Marchesi, Program Chair, XP2002 michele at diee.unica.it ---------------------------------------------------------------- Apologize if you receive this announcement more than once. ---------------------------------------------------------------- From usenet at thinkspot.net Tue Mar 5 16:49:04 2002 From: usenet at thinkspot.net (Sheila King) Date: Tue, 05 Mar 2002 13:49:04 -0800 Subject: Problems importing anything using _socket References: Message-ID: If this is of any help to you, here is the record of how I managed to install Python 2.1 on a Linux server, initially having problems with the socket library, and eventually ironing it out. http://www.aota.net/forums/showthread.php?s=&threadid=8972 -- Sheila King http://www.thinkspot.net/sheila/ "When introducing your puppy to an adult cat, restrain the puppy, not the cat." -- Gwen Bailey, _The Perfect Puppy: How to Raise a Well-behaved Dog_ From aahz at pythoncraft.com Sun Mar 31 09:49:53 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 09:49:53 -0500 Subject: Most important extensions? References: <3CA6ADEC.80859964@engcorp.com> Message-ID: In article <3CA6ADEC.80859964 at engcorp.com>, Peter Hansen wrote: >Aahz wrote: >> >> I'm teaching Python for [Perl] Programmers at OSCON this July. I've >> already decided to mention mxODBC, NumPy, and PIL, plus PythonPoint (aka >> ReportLab) gets a mention on my title page. I'd like this group to vote >> on the most important extensions for me to add to this list. Please vote >> for no more than three. > >I take it PyXml and PyUnit no longer qualify as "extensions"? You got it. >(Not that the idea of unit testing would necessarily appeal >to Perl programmers anyway.) Let me make clear that one of my goals for this tutorial (despite my occasional snarks here on c.l.py) is to have NO advocacy and NO war. After all, people who show up for that class have paid good money to learn Python (or at least their company's money), and for all that there are significant differences between Python and Perl, the fundamental goal for both languages is the same: programmer productivity. I think it's great that there are different approaches to that goal, even if Python is a better approach. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From eppstein at ics.uci.edu Fri Mar 8 13:34:29 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 08 Mar 2002 10:34:29 -0800 Subject: Is current integer for-loop syntax a wart? In-Reply-To: References: Message-ID: <16450184.1015583669@[192.168.1.100]> On 3/8/02 10:26 AM -0800, Cromwell, Jeremy wrote: > PEP 276 (Simple Iterator for ints) and PEP 284 (Integer for-loops), among > others, are written from the perspective that the current integer for-loop > syntax > > for i in range(10): > > is a wart. Is this true? I think this is an inaccurate characterization of PEP 284 -- although it describes a unified syntax for all integer for-loops, the wart it's primarily addressed at is multi-parameter (not single-parameter) range. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From python at rcn.com Mon Mar 4 20:55:20 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 4 Mar 2002 20:55:20 -0500 Subject: [ANN] PEP 279 version 1.5 Message-ID: PEP 279 -- Enhanced Generators has been updated: http://python.sourceforge.net/peps/pep-0279.html Additional comments are solicited before it is sent to Guido for pronouncement. Raymond Hettinger Changes: -- Added link to a pure python reference implementation and example code -- indexed() proposal compared and contrasted to PEP 212 -- added pros and cons of built-ins vs. a separate module -- discussion of restartability factored-out to separate section -- generator comprehensions presented without restartable class wrapper -- 'yield' to be an expression rather than statement -- .throw syntax revised to exactly match 'raise' -- try/finally prohibition in generators as another argument for .throw() -- alternative names for 'throw' listed -- referenced Oren Tirosh's work in the XLazy library -- minor wording, spelling, and formatting changes through-out From skip at pobox.com Fri Mar 1 18:05:59 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 1 Mar 2002 17:05:59 -0600 Subject: 16-bit grayscale images In-Reply-To: <6c585112.0203011453.2fd2a13f@posting.google.com> References: <6c585112.0203011453.2fd2a13f@posting.google.com> Message-ID: <15488.2391.822273.937850@12-248-41-177.client.attbi.com> Jeff> With Python/Tkinter is there a way to read in, write out, and Jeff> display 16 bit grayscale images? I suggest you check out PIL and VTK: http://www.pythonware.com/downloads/index.htm#pil http://public.kitware.com/VTK/ Completely different approaches, but I suspect there will be code in both that does what you want. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From wealthychef at mac.com Fri Mar 15 22:14:49 2002 From: wealthychef at mac.com (wealthychef) Date: 15 Mar 2002 19:14:49 -0800 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: <2b57f654.0203151914.63c38490@posting.google.com> > Rich, I thought Grant identified your real problem (calling select > wrong) in his first followup. I added some comments relevant to > the above issues in other followups. Did you miss all that stuff? > That was indeed my "real problem," but now I want to make sure I know how to do this read() thing correctly. Please see my reply to your other comments, thanks. From phr-n2002a at nightsong.com Tue Mar 5 14:48:46 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 05 Mar 2002 11:48:46 -0800 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: <7xbse3j3u4.fsf@ruckus.brouhaha.com> Message-ID: <7xwuwqn6ch.fsf@ruckus.brouhaha.com> huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) writes: > 2. Is there a configure option to guarantee -lieee? > > Changing pyconfig.h.in to #define HAVE_LIBIEEE 1 does not make -lieee > appear in the Makefile, even though it get into pyconfig.h. The configure script should probably be changed to test for the presence of libieee and use it if available. > 4. Is there an easier way to debug such problems? > > Maybe a C test program should be included in the configure script or in > the Tools directory so that people can easily report various conditions? > Such environmental testing is essential if Python is defining its own > numerical behavior indenpendent of IEEE or C. (but see below) Does anybody care about running Python on non-ieee platforms these days? If not, it should try to use ieee arithmetic all the time. The exception might be some embedded platforms with software floating point, but for those systems it should be acceptable to leave the overflow/underflow behavior up to the floating point emulation system if there even is one. > 5. How is 1e200**2 handled? > > Since both 1e-200**2 and 1e200**2 produce the same errno all the time, > but Python still raises OverflowError for 1e200**2 when linked with > -lieee, there must be a separate mechanism at work. What is that and how > can I override it? I know this is by design, but I think the design is > dumb (to put it politely). What do you want it to do? From donn at u.washington.edu Wed Mar 6 13:09:00 2002 From: donn at u.washington.edu (Donn Cave) Date: 6 Mar 2002 18:09:00 GMT Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> <3C84E363.6020106@olen.to> <3C84EBED.8090607@bath.ac.uk> <3C8651E9.493CDA64@olen.to> Message-ID: Quoth Joonas Paalasmaa : | Simon Willison wrote: |> Joonas Paalasmaa wrote: |>> Simon Willison wrote: |>>| I've written a simple Python script to scan a bunch of URLs for "live" |>>| sites and grab the title of those pages. It works by using popen() to |>>| call lynx and analyse the HTTP response: |>>| |>>| ----------------------------------------------------------------- |>>| |>>| command = "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~"+user+"/" |>> |>> |>> Use: |>> |>> command=["/opt/bin/lynx","-mime_header","http://www.bath.ac.uk/~"+user+"/"] |>> |>> for better security. |> |> I'm a Python newbie :) How does that makes things more secure? | | If you pass a string to os.popen as the first argument, the process is | envoiked | by by running the argument in shell. That can cause problems if the | string is composed from non-safe variables. Imagine situation where | variable 'user' is "; rm -fR ~/; echo ". That causes command | "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~; rm -fR ~/; echo /" | to be run in shell. | But if a list is passed to os.popen, os.popen will run a program named | in the first item of | the list with the rest of the list as arguments. TypeError: popen() argument 1 must be string, not list You meant os.popen2(), not os.popen(). Donn Cave, donn at u.washington.edu From abou at cam.org Sat Mar 30 16:00:23 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Sat, 30 Mar 2002 16:00:23 -0500 Subject: getting infos from a website References: <3CA61187.C0548FD5@cam.org> <3CA614B8.2C5C25E4@cam.org> Message-ID: <3CA62767.8D9D1042@cam.org> Zutroi Zatatakowski wrote: > > By the way, I can c.write() without any problem into the file though... > That's really puzzling me, I can write but cannot read. I know it's a > newbie problem but eh, so I am. :) Ok, it was pretty stupid, I was just not putting 'print' in front of it. But another thing... Now that I can capture a website html and output it into a file, I have to remove all html tags (I guess replacing '<>' by ' ') or, but I don't know if it's possible, instead of capturing the HTML source of the page, could I retrieve only the text, like basic ASCII copy/paste? -- Zutroi Zatatakowski Commando PACU http://pacu.cjb.net From tejarex at yahoo.com Sun Mar 31 19:49:13 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Mon, 01 Apr 2002 00:49:13 GMT Subject: PEP 285: Adding a bool type References: Message-ID: "Tim Peters" wrote in message news:mailman.1017597529.7660.python-list at python.org... > [Ralph Corderoy, to Guido] > > What do you think of `truth(x)' for all the good reasons listed > > elsewhere in the thread? You used truth yourself instead of Boolean > > above. > > Actually, he didn't. Actually he did. The 'above' quote Ralph is referring to is "IMO, bool(x) is the right way to "normalize" any value into a truth value." Note the second to last word: 'truth', not 'Boolean'. The point is that if Guido spontaneously phrased it this way, the suggestion to go with that phrasing is not completely crazy. Terry J. Reedy From martin at v.loewis.de Thu Mar 21 01:03:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Mar 2002 07:03:51 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: <83sn6udbxu.fsf@panacea.canonical.org> Message-ID: Kragen Sitaker writes: > martin at v.loewis.de (Martin v. Loewis) writes: > > That is certainly possible; freeze would be the obvious choice for > > such a mechanism (IMO). Alas, distutils is unmaintained, so don't wait > > for anybody else to implement it for you. > > That's rather shocking. How did distutils get to be unmaintained? Mainly by the initial authors not having enough time to do the full-time job that distutils maintenance means. They didn't run away, nor did they stop working on it when they find time. It just means that if you report a bug or request a feature, that somebody will look at your report in this millenium. Regards, Martin From sdm7g at Virginia.EDU Thu Mar 21 11:21:37 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Thu, 21 Mar 2002 11:21:37 -0500 (EST) Subject: "Zope-certified Python Engineers" [was: Java and Python] In-Reply-To: <852630CB444A0E88.1C47E73805633E2D.6D8C67A72D42A034@lp.airnews.net> Message-ID: On 21 Mar 2002, Cameron Laird wrote: > So, for example, I've heard that Python isn't as serious > as Java because it's not possible to hire "Zope-certified > Python Engineers". Sun does that for Java, Zope doesn't > for Python, therefore Python isn't as trustworthy as > Java. In the light of earlier discussion on this thread, here's my suggestion: Rather than just giving another test, let someone pull out a significant non-trivial task from the Python "to-do" list for each applicant for certification. After review of satisfactory completeion of 3 tasks in different categories, you get certified. Review might include having to write up something on why you did it that way, or some other explaination -- basically an essay question. Some organization ( Zope? PSA? Python.org ? ) will have to be responsible for final review and approval, but largely it will be through "community review" -- i.e. submitting to SourceForge, posting to mailing-list/newsgroup for discussion, etc. -- although perhaps a little more formalized, like the PEP procedure. ( Or maybe this begs for a Slashdot like system to distribute the review, grading and selection of projects. ) -- Steve From kedai at kedai.com.my Tue Mar 26 23:14:23 2002 From: kedai at kedai.com.my (kedai) Date: 26 Mar 2002 20:14:23 -0800 Subject: turning a python script to windows service References: <3CA014BC.6090204@skippinet.com.au> Message-ID: Mark Hammond wrote in message news:<3CA014BC.6090204 at skippinet.com.au>... > > When run as a service, the print statements go nowhere useful - they run > in the background. Try looking up info in win32traceutil - this will > allow you to see your print statement when running as a service. thanks for the pointer, and the book too. i see that print does show up in the traceutil. so it works as a service. is there anything special that i need to do if i wanted to do more stuff; for example, i tried copying files but nothing was copied. snippet: os.system('copy file filedst') #instead of print statement a simple, doing something service example would be good :) or pointers to docs i should read before asking again thanks > > Mark. From theller at python.net Thu Mar 21 02:49:38 2002 From: theller at python.net (Thomas Heller) Date: Thu, 21 Mar 2002 08:49:38 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: "Magnus Lie Hetland" wrote in message news:slrna9im44.6ii.mlh at vier.idi.ntnu.no... > What I said was 'an "uninstall" command', which has nothing to do with > building packages or installers for other systems (such as RPM). I'm > talking about being able to do > > python setup.py install > > and then later > > python setup.py uninstall > > Assuming that the same script was used for installation, it seems that > Thomas's command (which he refers to as a hack ;) works quite > nicely... But I guess it might not be robust enough. I've thought a little bit more about this. IMO PEP 262 (database of installed packages) should be implemented, so that the database is updated by distutil's install command - then we can write a robust uninstall. Thomas From greg at cosc.canterbury.ac.nz Sun Mar 3 20:01:50 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 04 Mar 2002 14:01:50 +1300 Subject: Status of PEP's? References: <1cef615e.0203021254.6bf3658@posting.google.com> Message-ID: <3C82C77E.6B9FA688@cosc.canterbury.ac.nz> "Hernan M. Foffani" wrote: > > indici(x) will replace the odd xrange(len(x)) idiom and address the problem > of open intervals where the length of the set is not known in advance. I like this a lot! But... where the **** did the word "indici" come from? Could we please call it either "indexes" or "indices"? According to spell, those are both English words, whereas "indici" is not. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From magnus at thinkware.se Wed Mar 20 07:59:37 2002 From: magnus at thinkware.se (Magnus =?ISO-8859-1?Q?Lyck=E5?=) Date: Wed, 20 Mar 2002 13:59:37 +0100 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> <3C984F44.1090001@pobox.com> Message-ID: <3C9887B9.6090603@thinkware.se> Hi, as a Java coder you might want to look into Jython and combine your skills. That would for instance enable you to quickly prototype Java programs in Python. Ahmed Moustafa wrote: > May I ask you what the scal for your webapp was? (Because MySQL is > related to small to mid-size web applications). Is it the same case with > Python? Not at all. But I think both MySQL and Python scales well. MySQL has some shortcomings, and since the purchase cost is so low :) it's a good choise for systems with a small budget. But don't dismiss is as a weak database in larger settings. In places where you have many more reads than transactions, MySQL might well be the fastest choise. Python code doesn't compile to native machine code, only to byte code, so in some situations it can't compete with C. But you should be aware that - Python integrates well with C, and possible bottle necks can be coded in C and used as extension modules. Such a solutin might well be much faster than a pure Java solution. - In most web apps it's often other factors such as network and databases that are the bottle necks. - Since the development time will be shorter, you will have more money left for hardware. From a design point of view Python has the constructs that you need to build big applications. Classes, namespaces, modules and packages etc. Since Python code is typically much shorter (3-10 times) than C, C++ or Java, and more easy to read, it's a good language for high demands. I don't know what size you are thinking of. My current app is maybe 5 000 lines of code if you remove comments and empty lines. It's about 140 classes. I would guess that it would have been at least 15 000 lines of Java. I don't worry a bit about this getting out of hand. There are many big web apps written in Python. - Zope is an web application server. See www.zope.com for some customer references. - ReportLab (www.reportlab.com) has large installations. Their main piece of code is open source, but for those who don't trust freeware they have a commercial XML solution that costs from $10 000. Demos on the site. - Google runs a lot of Python code. Among other Python programs we can mention the use for animations in the latest Star Wars film, and here in Scandinavia a lot of manipulations of metereological data and images are done with Python. See http://www.thinkware.se/cgi-bin/thinki.cgi/PythonUsers for some more examples of Python use. /Magnus From jimd at vega.starshine.org Wed Mar 27 22:18:25 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 28 Mar 2002 03:18:25 GMT Subject: Sorting distionary by value References: Message-ID: In article , Artur Skura wrote: >Duncan Booth wrote: >> Artur Skura wrote in >> news:slrna9lqj1.9n1.arturs at aph.waw.pdi.net: >>> Is there an idiom in Python as to sorting dictionary by value, >>> not keys? I came up with some solutions which are so inefficient >>> that I'm sure there must be a simple way. >> How do you know they are inefficient? Have you profiled your application >> and found this to be a bottleneck? >No, and it seems the problem is not with sorting. >I wanted to write a compact word counting script (well, in shell >it can be done in a 5 lines or so), just for fun. Just about a week ago I posted a word frequency counting script which counted "words," filtered out some common contractions and "non-words" and tracked "known words" (as per entries from /usr/share/dict/words) and then generated listing by highest frequency first. I also posted a modified version that would shove its results into a PostgreSQL database table (a couple of days later, it only took four lines). I could mail it to you if you like, but I'd be surprised if it's not still floating around. (BTW: for performance, it handles almost 1800 man pages, averaging 7Kb each, in less than 2 minutes on my mid-range (dual 650Mhz Pentium) desktop box)). The whole thing in only about 85 lines long and the core function is less than ten. As so many people have suggested in this thread, it simply uses a dictionary (awk calls them associative arrays, perl calls them "hashes"). The core loop is something like: freq = {} for line in file: for word in line.split(): if word in freq: freq[word] += 1 else: freq[word] = 1 (assuming Python2.2 for file interation and dictionary membership support using "in." I *really* like those 2.2 features! They make my psuedo-code so executable!) From garyr at fidalgo.net Sun Mar 31 12:02:57 2002 From: garyr at fidalgo.net (Garyr) Date: Sun, 31 Mar 2002 09:02:57 -0800 Subject: Thread blocking problem Message-ID: I have a program consisting primarily of a simple Tinker GUI and in separate thread some code that invokes a function in a C++ extension module that blocks on WaitForSingleObject most of the time. The Python code is a producer and the C++ code the consumer, a sound card driver. Shouldn't the GUI be responsive when the code in the thread is blocked? In this program it appears that processing outside of the thread occurs only when the code in the thread executes briefly. That is, whenever the sound card accepts another chunk of data. If I comment the function call that passes the data to the sound card and stick in a delay processing appears to be normal. The sound card driver (which I did not write) worked very well in the C++ program that I got if from Does anyone have any thoughts on what might be going on here? From pearu at cens.ioc.ee Thu Mar 28 16:51:58 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Thu, 28 Mar 2002 23:51:58 +0200 Subject: Weave... In-Reply-To: References: Message-ID: On 28 Mar 2002, Vincent A. Primavera wrote: > Hello, > Does anyone know where I can find Weave which used to be located at the > address below(or any good alternatives...)? > > Thank you, > > Vincent A. Primavera > > http://www.scipy.org/site_content/weave > Currently SciPy site seems to have Zope problems but try later again. Regards, Pearu From tl_news at nexgo.de Fri Mar 1 15:29:05 2002 From: tl_news at nexgo.de (Tino Lange) Date: Fri, 01 Mar 2002 21:29:05 +0100 Subject: Ping References: Message-ID: On Fri, 1 Mar 2002 18:21:13 +0100, "Riss Nicolas" wrote: >Bonjour, >on ma dit que je pouvais ?crire en francais alors j'?crit en francais. Je >voudrais pouvoir v?rifier toutes les 5 min que une machine ping une autre >machine et si elle ne ping pas qu'elle execute un script. Comment faut il >faire avec python pour pinger une machine et v?rifier qu'elle r?pond?? > >Merci de votre aide. > Hi Riss! The best solution IMHO is to use the external "ping" provided by the underlying operating system and to catch and parse its output. So you don't have the possible suid and/or implementation problems. If you really want to use a pure "Python-Ping" you have to be familiar with (low-level) socket/network-programming. Have a look at http://mail.python.org/pipermail/python-list/2001-November/070944.html (the last two links will provide you with two working "Python-Pings") Best regards Tino From emile at fenx.com Sat Mar 2 15:05:38 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 2 Mar 2002 12:05:38 -0800 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: "Carel Fellinger" > Emile van Sebille > > "Carel Fellinger" > >> You specify that the > >> integer to iterate over should be possitive, why not allow for > >> negative values and do the sensible thing, like: > >> > >> >>> [i for i in -3] > >> [-1, -2, -3] > > > If you change the sensible thing to mean: > > > [-3, -2, -1] > > > I'd like it better. ;-) > > I noted the smiley, but just in case someone might think you have a > point: what would be the benefit of that? Syntactic consistency with slice notation: 5 :: [:5] as-3 :: [-3:] or maybe it should be: ;-) 5 :: [:5] like -3 :: [:-3] > It just let you loop over a > sequence in the standard order, but now with negative indici. And the > range call to get this isn't that hard either: range(-3,0). > > My proposal makes iterating in *reverse* order simple. On anything with a len. > The tutorial could introduce it like: > > In python integers are objects too. And objects know how to do > things, e.g. integer objects know how to add and just recently > they learned how to count. Positive integers count from zero > upto but not including the number itself, whereas negative > integers count from -1 downto and including the number itself. My my... I think you've converted... ;-) > > A common place where this feature of integers is used is in for > loops and list comprehension. e.g. > > >>> s = "silly walk".split() > >>> print " ".join([s[i] for i in len(s)]) > silly walk > >>> print " ".join([s[i] for i in -len(s)]) > walk silly > > Although the first print statement is generally written as: > > >>> print " ".join([x for x in s]) Couldn't we overload the '-' to reverse by itself? ;-) >>> print " ".join([x for x in -s]) My point, repeated a few times here , is that while I have no objections to (or say in) adding features in ways that allow for pratical use, I'd prefer that there be syntactic consistency so that each new feature doesn't add to the learning curve. Arguments in favor of producing 0,1,2 for 'for i in 3' have included that it's the same as range(3), and that it maches slice notation, ala range(10)[:3]. For negative numbers, it seems a natural extension for me to think in terms of range(-3,0) and range(-10,0)[-3:]. Your reversing the sequence just doesn't feel right. ;-) But, like >>, I'd get used to using it if it were there. Further, because there will always be different opinions of consistency, a decision will ultimately be made in favor of one of the opposing opinions. The decision for (for i in 6), requires an iter to be added to ints. From a practical perspective, I don't see the harm in adding it just because one group of people don't like iterating over integers. We've simply provided an answer to 'What does it mean to iterate over an integer?' The three Pythonic opinions on this seem to be 'why not', 'an int's not a collection and can't be iterated over', 'why bother', and 'find a better way'. I fall somewhere between the first and last of these. I illustrated with my sample dexing class the functionality I'd like to see, although I won't be surprised to never see that in python. For those who don't like iter(int), don't use it, or at least, . ;-) use it as often as you use '>>'. Bonus-points-for-each-point-found-here-ly y'rs, -- Emile van Sebille emile at fenx.com From peter at engcorp.com Mon Mar 25 19:19:22 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 19:19:22 -0500 Subject: Memory sizes of python objects? References: <3C9E06A0.EC4D51E3@engcorp.com> <3C9E2BA1.E500BE4A@engcorp.com> Message-ID: <3C9FBE8A.1BB3A0AF@engcorp.com> Erno Kuusela wrote: > > In article <3C9E2BA1.E500BE4A at engcorp.com>, Peter Hansen > writes: > > | I don't get that behaviour. On my machine, with Python 2.2, for > | all intents and purposes the memory allocated stays constant. > | Did I overlook something? > > hard to say. how did you measure it? [w/red face] With Windows.... I'll think twice about checking something like this on that p3e of s2t operating system next time... Thanks Erno. -Peter From wurmy at earthlink.net Mon Mar 11 18:01:57 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Mon, 11 Mar 2002 23:01:57 GMT Subject: augmented arithmetic operations References: Message-ID: <3C8D37C7.A06D889D@earthlink.net> Mike Carifio wrote: > > According to the language ref section "Emulating numeric types" > (http://www.python.org/doc/current/ref/numeric-types.html), > I can use special name methods to overload operations. When creating > "augmented operations" like __iadd__ (for "+=") is it considered > "bad form" to create a intermediate value and then assign parts of > self to the intermediate value? Or is this just an implementation detail? > > For example, suppose I introduced Point as a kind of number: > > class Point: > def Point(self, x, y): > self.x = x; self.y = y > def __add__(self, rhs): > return Point(self.x + rhs.x, self.y + rhs.y) > def __iadd__(self, rhs): > intermediate = self + rhs # bad form? > self.x = intermediate.x; self.y = intermediate.y > > p11 = Point(1,1) > p22 = Point(2,2) > p33 = p11 + p22 # p11.__add__(p22) > p33 += p11 # p33.__iadd__(p1) makes p33 (4,4) > > I'd like to reuse __add__ without having to introduce an intermediate > object... This code has a few problems... 1. The constructor's name is __init__, not the name of the class. 2. Indeed, you don't need the intermediate object, since += is for changing an object in place. So you can do self.x = self.x + rhs.x self.y = self.y + rhs.y 3. But don't forget return self or the += operator won't work! After " p33 += p11 ", p33 will be None. Here's what I would make of the code: >>> class Point: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, rhs): return Point(self.x + rhs.x, self.y + rhs.y) def __iadd__(self, rhs): self.x = self.x + rhs.x self.y = self.y + rhs.y return self >>> p11 = Point(1,1) >>> p22 = Point(2,2) >>> p33 = p11 + p22 >>> p33.__dict__ {'y': 3, 'x': 3} >>> p33 += p11 >>> p33.__dict__ {'y': 4, 'x': 4} HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From john at yahoo.com Sun Mar 31 16:49:56 2002 From: john at yahoo.com (John Warney) Date: Sun, 31 Mar 2002 21:49:56 GMT Subject: newbie question on lists, getting an error on basic addition References: Message-ID: <541fau8nne8hgoquiqbq926ij3p3pa9bep@4ax.com> Ah, ok, thanks, it works fine now On Sun, 31 Mar 2002 17:28:56 GMT, "Emile van Sebille" wrote: >John Warney >> >>> alist = [1, 2, 3, 4] >> >>> counter = 0 >> >>> answer = 0 >> >>> alist >[snip] >> >>> while counter < 6: >> ... answer = answer + alist[counter] >> ... counter = counter + 1 >> ... >> Traceback (most recent call last): >> File "", line 2, in ? >> IndexError: list index out of range >> >>> answer >> 10 >> >> why am i getting this error when it works??? >> Rob > >You get the error because you're trying to loop six times through a list >of four elements. What you've displayed is the accumulated total while >the loop worked. From gargravarr at whoever.com Wed Mar 20 16:04:13 2002 From: gargravarr at whoever.com (gargravarr at whoever.com) Date: Wed, 20 Mar 2002 21:04:13 GMT Subject: Unicode problem References: <3c98f206.24909027@news.tiscali.no> Message-ID: <3c98f9a9.26864108@news.tiscali.no> Thanks for the help! It worked! Tom >if you don't tell Python what 8-bit encoding you want >to use for a Unicode string, Python will assume ASCII. > >to convert to an 8-bit string with a known encoding, >use the encode method: > > s = i.firstChild.data.encode("iso-8859-1") > >you should probably escape < > & too; consider using >something like: > > from cgi import escape > > def encode(s): > if not s: return "" > return escape(s.encode("iso-8859-1")) > > body.write('

    %s

    \n' % encode(i.firstChild.data)) > > > > deadlock thomas -- Thomas Guettler http://www.thomas-guettler.de From python at chajadan.net Fri Mar 8 15:38:44 2002 From: python at chajadan.net (chajadan) Date: Fri, 08 Mar 2002 12:38:44 -0800 Subject: Tkinter question: master? In-Reply-To: References: Message-ID: <5.1.0.14.0.20020308123805.027e2ec0@63.118.78.184> Thanks :-D --chajadan At 11:08 AM 3/8/02 +0000, Eric Brunel wrote: > > >chajadan wrote: >[snip] > > class Application(Frame): > > > > def __init__(self, master): > > Frame.__init__(self, master) >[snip] > > in "def __init__(self, master):", self refers to this class, i.e. > > Application (though how those are inherently linked [by name or arguement > > position--assuming position] I have no clue. master will be set equal to > > whatever the next arguement is, which seems to be Frame... > >Nope: "self" does *not* refer to the class, neither do "master" refer to >Frame. "self" refers to the instance being built. There's no link at all >between the arguments in the __init__ method and what you specified in the >class declaration (Application(Frame)), which describes the inherited >classes. > >Consider this far simpler example: > >class C1: > def __init__(self, a, b): > self.x = a + b > >class C2(C1): > def __init__(self, a, b, c): > C1.__init__(self, a, b) > self.y = c > >C1 does not inherit from anything, so you define it like above: "class C1" >with nothing behind. The method __init__ is defined with two parameters, >that will be passed as arguments when the object is built. So if you have >to build an instance of C1, you'll have to do that: > >o1 = C1(2, 4) > >(Try to pass any other number of arguments, and you'll see it fails...) > >Now C2 inherits from C1, so its definition is written "class C2(C1)". But >its __init__ method takes 3 parameters, so when you create an instance of >C2, you'll write: > >o2 = C2(1, 3, 5) > >I see what you find confusing: in the class definition C2(C1) means >"inheritance", but in object creation, C2(1, 3, 5) means "call to the >__init__ method". The notations are similar, but the meaning are different. >Which is indeed even more confusing when you inherit from one class and the >__init__ method has one argument, like in your example. > > > the (Frame) in the class definition must just be for > > inheritance purposes and have ~NOTHING~ to do with arguements > >You're right on that. > >HTH > - eric - > >-- >http://mail.python.org/mailman/listinfo/python-list From morton at dennisinter.com Mon Mar 4 16:56:18 2002 From: morton at dennisinter.com (damien morton) Date: 4 Mar 2002 13:56:18 -0800 Subject: Text Search Engine that works with Python References: Message-ID: <4abd9ce7.0203041356.39491249@posting.google.com> "Doug Farrell" wrote in message news:... > Hi all, > > I'm wondering if anyone knows of a text search engine that works with > Python? What I'm looking for specifically is something that will compress > the text and still allow searches and retrievals that can be exact matches > or proximity based. The text I want to compress and search is huge (70 megs) > and should compress down to half, not including any index files that might > be required by the search engine. Anyone know of anything like this or any > ideas? > > Thanks, > Doug Farrell Have you looked at mg. Its written in C, but useable from the unix command line. http://www.mds.rmit.edu.au/mg/ From phr-n2002a at nightsong.com Mon Mar 4 22:33:43 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 19:33:43 -0800 Subject: Status of PEP's? References: Message-ID: <7xwuwrofhk.fsf@ruckus.brouhaha.com> David Eppstein writes: > While we're picking minor nits, I would consider the natural numbers to > include zero. Usually the term "natural numbers" don't include zero. http://mathworld.wolfram.com/NaturalNumber.html From jochen at unc.edu Tue Mar 19 21:51:51 2002 From: jochen at unc.edu (Jochen =?iso-8859-1?q?K=FCpper?=) Date: 19 Mar 2002 21:51:51 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 (Took out numpy, really isn't related anymore.) On Tue, 19 Mar 2002 21:20:43 -0500 Tim Peters wrote: >> Why isn't it possible to have a single python-2.2 branch which one >> could follow to get all the stuff that's incorporated into that >> version? Tim> That's what the release22-maint branch is supposed to be (and, Tim> AFIAK, is). Ah:) >> There are huge differences between release22-maint and r221c1, Tim> What makes you think so? I just did when I did cvs up -A cvs up -r release22-maint cvs up -r r22c1 I got multiple screens (>40 lines) of patched and updated files on the last step. Tim> cvs diff -r release22-maint -r r221c1 Ok, here too now. It apparently was a cvs problem:) Tim> And thanks for checking that your problem is fixed in 221c1. Had Tim> anyone tried this stuff in 22a1 or 22a2 or 22a3 or 22a4 or 22b1 Tim> or 22b2 or 22c1 (yes, we actually cut 7 full prerelease Tim> distributions for 2.2!), it would have worked in 2.2 out of the Tim> box. Keep that in mind when 2.3a1 comes out. Let's see:) Greetings, Jochen - -- University of North Carolina phone: +1-919-962-4403 Department of Chemistry phone: +1-919-962-1579 Venable Hall CB#3290 (Kenan C148) fax: +1-919-843-6041 Chapel Hill, NC 27599, USA GnuPG key: 44BCCD8E -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6-cygwin-fcn-1 (Cygwin) Comment: Processed by Mailcrypt and GnuPG iEYEARECAAYFAjyX+UgACgkQiJ/aUUS8zY4wGgCfbv2O4x61AHNKmBlfVhjZDzRx A24An15ictH20DEpR4n9Batxm6iMRpwP =/B11 -----END PGP SIGNATURE----- From jason at jorendorff.com Fri Mar 1 01:54:19 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 1 Mar 2002 00:54:19 -0600 Subject: PEP 276 (was Re: Status of PEP's?) In-Reply-To: Message-ID: > some-people-don't-even-like-listcomps-ly y'rs - tim Detour: I still haven't decided whether I like list comps (although I *use* them all the time) but today I found something surprisingly similar scribbled in a notebook of mine, perhaps a few years old. { file f | f.parent = '/home/jason' } ... the same code in something more like prolog ... set { file f | f in folder '/home' } It was really disconcerting to see this in my own handwriting, considering my mixed feelings on Python's list comps. Hmm. :) ## Jason Orendorff http://www.jorendorff.com/ From anthony at interlink.com.au Wed Mar 20 21:21:59 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 21 Mar 2002 13:21:59 +1100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) In-Reply-To: Message from Kragen Sitaker of "20 Mar 2002 19:03:25 CDT." <83sn6udbxu.fsf@panacea.canonical.org> Message-ID: <200203210222.g2L2M0r15562@mbuna.arbhome.com.au> >>> Kragen Sitaker wrote > martin at v.loewis.de (Martin v. Loewis) writes: > > That is certainly possible; freeze would be the obvious choice for > > such a mechanism (IMO). Alas, distutils is unmaintained, so don't wait > > for anybody else to implement it for you. > > That's rather shocking. How did distutils get to be unmaintained? Because Greg Ward burned out on it, and no-one's been willing to step up and continue work on it. Note that "unmaintained" is a bit strong - bugs are going to be fixed, but at the moment no-one's actively adding stuff to it. Anthony -- Anthony Baxter It's never too late to have a happy childhood. From martin at v.loewis.de Wed Mar 6 13:09:20 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Mar 2002 19:09:20 +0100 Subject: distutils question References: <3C8655CA.7080008@wi.mit.edu> Message-ID: Brian Kelley writes: > So the real question is, how do people distribute documentation and > example code? For PyXML, I use a different install_data command; feel free to use (it's in xml/setupext/install_data.py of the CVS on sf.net/projects/pyxml). That supports adding data files in a MANIFEST style manner, including a directory structure. Regards, Martin From skip at pobox.com Wed Mar 27 10:49:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Mar 2002 09:49:18 -0600 Subject: instrumenting Python code In-Reply-To: References: <15521.50103.968819.131319@12-248-41-177.client.attbi.com> Message-ID: <15521.59902.657216.982543@12-248-41-177.client.attbi.com> Dave> The hotshot module doesn't appear to have any documentation Dave> yet. That's true. Here's my simple usage scenario: import hotshot profiler = hotshot.Profile("/home/skip/tmp/csv2csv.prof") profiler.run("main()") profiler.close() stats = hotshot.Stats("/home/skip/tmp/csv2csv.prof") stats.print_stats() -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From pedronis at bluewin.ch Tue Mar 12 22:31:04 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 13 Mar 2002 04:31:04 +0100 Subject: mildly related (was: Has Mark Hammond attained pariah status yet?) References: <3c8e0911_1@news.bluewin.ch> <3c8ec411$1_5@news.bluewin.ch> Message-ID: <3c8ecb06$1_1@news.bluewin.ch> mildly related, on the issues of relationship with the press: http://amywohl.weblogger.com/2002/03/04 The generally valuable point is the how-to one can have personal resorts to get things straight, e.g. a weblog. regards. From aahz at panix.com Mon Mar 11 09:38:03 2002 From: aahz at panix.com (Aahz Maruch) Date: 11 Mar 2002 06:38:03 -0800 Subject: PEP 2, Procedure for Adding New Modules References: Message-ID: In article , Martijn Faassen wrote: >Aahz Maruch wrote: >> >> The maintainers also possess primary responsibility for determining >> whether bugfixes should be backported to previous Python releases as >> discussed in PEP 6. > >Thanks; I'm adding some phrases on this to PEP 2. PEP 6 claims it's a >'draft' PEP by the way, what is its status? Looking at the status of other PEPs, it should be "Active", I think. I'm cc'ing Barry on this to get his opinion. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From aaron.ginn at motorola.com Mon Mar 18 17:44:14 2002 From: aaron.ginn at motorola.com (Aaron Ginn) Date: 18 Mar 2002 15:44:14 -0700 Subject: Declare list of large size Message-ID: Perhaps I've just glossed over this in the documentation, but what is the simplest way to declare a list of large size? Is there something analogous to the following in C: int list[100]; I can do this by doing the following: list = [] i=0 while i < 100: list.append[0] i = i + 1 which will give me a list 100 elements long with all values initialized to 0, but I'm assuming there has to be an easier way to do this? Am I correct in this assumption? Thanks, Aaron -- Aaron J. Ginn Phone: 480-814-4463 Motorola SemiCustom Solutions Pager: 877-586-2318 1300 N. Alma School Rd. Fax : 480-814-4058 Chandler, AZ 85224 M/D CH260 mailto:aaron.ginn at motorola.com From akjmicro at yahoo.com Wed Mar 20 10:40:51 2002 From: akjmicro at yahoo.com (Aaron Johnson) Date: Wed, 20 Mar 2002 10:40:51 -0500 Subject: Chcago Area Python Interest group Message-ID: Hello, I was wondering wheter any Chicago python users out there would be interested in organizing a group..... Write me back..if we get enought critical mass, we could post an announcement on python.org Cheers, aaron. -- From sdrake at freenet.edmonton.ab.ca Sun Mar 17 08:06:27 2002 From: sdrake at freenet.edmonton.ab.ca (Steve Drake) Date: Sun, 17 Mar 2002 13:06:27 GMT Subject: Help Required References: Message-ID: When I tried this in IDLE there were spaces between the items. Is there something else you have to do to create the list with no spaces. Regards, Steve Drake On Sat, 16 Mar 2002 04:16:53 GMT, Courageous wrote: >d1,uid2,uid3....and so on.( Notice there is no space) >> >>However when i am trying to create the uid list it gives >>uid1, uid2, uid3,...and so on. > >The interpreter is your friend: > >>>> mylist = [] >>>> for i in range(1,10): > mylist.append( "myitem" +`i` ) > > >>>> mylist >['myitem1', 'myitem2', 'myitem3', 'myitem4', 'myitem5', 'myitem6', 'myitem7', 'myitem8', >'myitem9'] >>>> > >C// From usenet at thinkspot.net Thu Mar 14 23:30:28 2002 From: usenet at thinkspot.net (Sheila King) Date: Thu, 14 Mar 2002 20:30:28 -0800 Subject: hey everyone!! References: Message-ID: On Fri, 15 Mar 2002 04:05:40 -0000, "j45729" wrote in comp.lang.python in article : > hey everyone!! i don't know what to say...PYTHON ROCKS!! its so much > fun it really is a fun language... > I can only concur. :D -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sacchi at nospamfreemail.it Sat Mar 9 20:36:16 2002 From: sacchi at nospamfreemail.it (Sacchi) Date: Sun, 10 Mar 2002 02:36:16 +0100 Subject: newbie needs help with tkinter Message-ID: <1Myi8.13667$%d1.409160@twister2.libero.it> I've just learned the main rules of python(I already knew both java and C). Now I'm trying to get something out of Tkinter, but while running this sample program (made by myself) I encountered a problem. I wanted that by clicking on the "configura" command under the "File" menu the frame would get yellow and that a label would appear on it. The function works(the line "print "hello!"" gets executed) but the gui window doesn't change. I even tried to use the widget redraw methods but with no success... anyone can help me please? Thanks in advance Marco --------- Program Code ---------------------- from Tkinter import * class Application(Frame): def __init__(self,master=None): Frame.__init__(self,master) menubar=self.addmenubar() master.config(menu=menubar) menubar.mainloop() def addmenubar(self): menubar=Menu() filemenu=Menu(menubar) menubar.add_cascade(menu=filemenu,label="File") #these lines got shifted by the newsreader program, but all belong to #the addmenubar function filemenu.add_command(label="Configura"command=self.configframe) filemenu.add_command(label="Lavora") return menubar def configframe(self): self.set(bg="yellow") w=Label(self,fg="blue",text="prova") w.grid() self.update_idletasks() print "hello!" #main root=Tk() applicazione=Application(root) root.mainloop() -- ----------------------------------------------------- remove "nospam" from email address to answer ----------------------------------------------------- From pinard at iro.umontreal.ca Thu Mar 21 20:17:26 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 21 Mar 2002 20:17:26 -0500 Subject: __file__ for relative imports In-Reply-To: References: Message-ID: [Ken Seehof] > > Robin Becker writes: > > > > > Is there an obvious reason why modules imported from the current > > > directory don't have an absolute pathname for __file__? > I keep bumping into that one too. [...] There is another tiny bit in that area which might be debated as well. `__file__' is not defined for the `__main__' module. But `sys.argv[0]' in that case contains the information one might have hoped out of `__file__'. I would like if `__file__' was just dependably defined in all circumstances, the best the Python interpreter can. If this was done, the programmer would then not have to resort anymore to convoluted code for finding the directory and file for the current module. Or maybe there is trick I do not know? The only reason that would come to mind for not having `__file__' defined is that some other platforms or systems (I'm only experienced with Python on Linux) might have a hard time getting that information. But even then, if it is the case, is really sticking to the least common denominator the proper approach? Maybe `__file__' being set to the empty string in such cases might be better than letting it undefined. On the other hand, I would understand there is a difficulty with `__file__' within a script read by the interpreter from standard input, or compiled from the contents of a string. I'm not sure what is the best approach in those cases. I still think the best would be that `__file__' be always defined, in the most sensible way, whatever that may mean! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From johnroth at ameritech.net Sat Mar 30 18:30:52 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 30 Mar 2002 18:30:52 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: "Carel Fellinger" wrote in message news:a85es5$a95$1 at animus.fel.iae.nl... > Terry Reedy wrote: > > ... > > Proposed amendment: call the new type 'truth' instead of 'bool' and > > change the title of the PEP to "Formalizing a Python truth type". > ...lots of arguments snipped > > A *very* good idea. Agreed. John Roth From sholden at holdenweb.com Tue Mar 26 12:55:26 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 26 Mar 2002 12:55:26 -0500 Subject: list comprehension question References: Message-ID: "Tim Peters" wrote ... > [Neil Schemenauer] > > PS. tell the bot I'm sorry I doubted the correctness of his code > > No problem, Neil! He had already projected both the depth and sincerity of > your sorrow to six significant digits, and seemed quite pleased that doing > so didn't exhaust his supply of available zeroes. He's off factoring primes > again (I think he's on to something humans may have missed), so all is well. > > Tim: This pathetic fiction that you and the bot have separate identities won't fool anyone. Come clean, before the supply of available ones runs out and you are left with only zeroes. even-the-mc6809-has-its-limits-ly y'rs - steve From James_Althoff at i2.com Fri Mar 1 17:19:05 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 14:19:05 -0800 Subject: Status of PEP's? Message-ID: [Timothy Delaney] > For the record (I've said this before), I like the idea of integers > being iterable (and I'm not a set theory wonk). [Alan Daniels] > That's fine if you like the idea. I don't. The only validations > I've seen for it are obscure references to set theory, or the vague > notion that it looks neat since it would make Python read more like > Haskell (or insert whatever favorite research langugage here). I have > yet to see any meaningful explanation on how it fixes some gap in > Python, or improves it other than saving the need to type the word > "xrange". The actual PEP has a "rationale" section. Neither set theory nor Haskell come into play in the rationale. If you are happy with xrange when dealing with the indices of indexed-collections, then you will not be swayed by the rationale for PEP 276. Not everyone has thought xrange to be ideal, though. > While I'm at it, two problems with it that I haven't yet seen > addressed: > > 1) If you have a class that defines both __int__ and __getitem__ > methods, and iterate over an instance of it, which method "wins" > comes iteration time? The usual, or the "for i in 5" trick? PEP 276 doesn't propose any tricks. It suggests adding an iterator to the int class. If you define your own class with an instance x, and do "for i in x" the for-loop will try to get an iterator from your instance x -- just because that's what the for-loop does. PEP 276 doesn't affect this behavior in any way. > Maybe this is covered in PEP 276. I've read through it once when > it was first introduced and didn't see any mention on how this > would be handled. I'd read it through again, but it's late and > frankly reading it makes my skin crawl. Don't worry, I have some ointment for you . (Seriously though, is that kind of comment really necessary? I understand that you strongly dislike the proposal. But throwing in zingers isn't very considerate). > 2) Anyone new to the language will wonder exactly why it is that they > can iterate over ints, strings, tuples, lists, dictionaries, > files, generators, and indeed, any class instance that implements > an iterable interface... > > ...but not floats. Hey, if "for i in 5" means something, then > obviously "for i in 5.0" should mean something too, right? That's > what a newbie will think, and what good reason answer will anyone > be able to give them? Play with some code and see if you can come up with a meaningful, useful, practical, and reasonable-to-implement definition for a sequence of numbers related to a given floating point number x. I suspect that you will find a lot of tricky issues. > As I've come to think of it, the whole point of > "iterating" is that the programmer is walking through a collection: Others clearly agree with this perspective. I think that it is overly-restrictive to say that the *only* thing that you can iterate is a collection. > I can NEVER bring myself to see an integer as a collection, > not outside of a lecture on number theory, anyway. There's no requirement to think about number theory or to view integers as collections here. All that is suggested is a slightly-less cluttered (than current) way to iterate the indices of an indexed-collection. If you are happy with range/xrange, so be it. > Sorry to rant, but this is the only idea for Python I've seen > in a VERY long time, since the 1.5.2 days, where rather than > capturing my interest and giving me something to contemplate, just > strikes me as ugly, and stays ugly no matter how long I look at it. Well then, I guess you'll be giving PEP 276 high marks for "originality" . Jim From James_Althoff at i2.com Fri Mar 1 19:23:55 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 16:23:55 -0800 Subject: Status of PEP's? Message-ID: [Jim] > Another issue that I have is that the syntax does not work outside of a > for-loop header. I want to be able to create integer intervals anywhere in > my code, not just in the header of a for-loop. [David Eppstein] > [x for 3 <= x < 10] Agreed, the for+relational syntax works in list comp.s. (Again, I was lumping list comp.s in with for-loops). I was thinking in a more general sense: I would like to create an iterator with start, end, and step values and pass it into a function without first actualizing it as a list (like one would have to do using for+relational in conjunction with list comp.s). And use the same construct in for-loops, list comp.s, etc. (For those just tuning in: I realize that I can create a class for this -- actually, I already have. I'm refering to proposals for new idioms in Python for iterating intervals of integers.) Jim From brian at rk-speed-rugby.dk Wed Mar 6 02:07:48 2002 From: brian at rk-speed-rugby.dk (Brian Elmegaard) Date: 06 Mar 2002 08:07:48 +0100 Subject: PDF solutions? References: Message-ID: "Steven D. Arnold" writes: > (2) I need to be able to merge multiple PDF files together. This may be done with pdflatex and the pdfpages package. An example on http://www.et.dtu.dk/staff/be/latex/pdfpages. -- Brian (remove the sport for mail) http://www.rk-speed.dk http://fiduso.dk http://sunsite.auc.dk/dk-tug \TeX, tak. From huaiyu at gauss.almadan.ibm.com Tue Mar 5 22:23:42 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 6 Mar 2002 03:23:42 +0000 (UTC) Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: On Tue, 5 Mar 2002 12:17:28 -0800, James_Althoff at i2.com wrote: >> However, I still think the potential for unintended effects >> (bugs) is too big when a one-element sequence behaves substantially >> different from the element itself. Imagine if Python had a character >> type and that >> "abc" == ['a', 'b', 'c'] == 'd' != "d" >> >> Even though it can be explained, what utter confusion it would >> result in actual use! > >Sorry, I'm a little confused by this one. Example: "for x in ['spam']" is >not the same as "for x in 'spam'". Isn't that a case "when a one-element >sequence behaves substantially different from the element itself" in this >context? OK, I used the wrong words here. I meant to say that an element of a sequence being functionally equivalent to another sequence of the same type but different. This excludes cases like "d"[0]=="d". But if "d" produces the same effect as "abc" under some circumstances, it would be very confusing. Likewise if "spam" produces the same effect as ["spam", "egg"]. The reason is not philosophical. It's just that human minds are easy to confuse on these matters, so we want exceptions in all such cases: "spam".append("eggs") x, y, z = "d" x, y, z = 3 [f(x) for x in (4 in 3) in (2 in 3) if x in (x+1 in x*2)] # just for fun. :-) >> Here's another example of a similar nature. In Matlab there is a >> fuction sum(x) that would return sum of elements of x, if x is a >> (row or column) vector, or a row vector of columnwise sums of x, >> if x is a matrix. This is very handy when used in isolation, but >> a pain in programs, because the behavior on (1xm) matrix has a >> different semantics. Suppose x is a (5x4) matrix. Then (using >> Python syntax instead of Matlab's) >> sum(a[0:n:, :]) >> would give a (nx4) matrix for n in 5, 4, 3, 2, but for n==1, >> it gives a scalar which is the sum of x as a row vector. > >Not really following that example either. Sorry. OK, I have to admit that this does not really apply. Syntacitically (6,) is quite different from (6). So it is not like the Matlab situation where a 1xn matrix is treated as a row vector. So you could argue that they are not neighbors and there is no discontinuity. However, in terms of human behavior (typo frequency) they are indeed close to each other. This is similar to the relation between "=" and "==". On the other hand, in the special case where 0 and 1 are used as logical values your proposal is in fact consistent. This is a plus. Huaiyu From joonas at olen.to Sat Mar 23 04:17:21 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Sat, 23 Mar 2002 11:17:21 +0200 Subject: load html frameset out of Python script References: <30cf5082.0203221039.791cab07@posting.google.com> Message-ID: <3C9C4821.E33D36CF@olen.to> Andreas wrote: > > Hello everybody, > > I am trying to set up a html site with frames. I want to load the > frameset out of a Python script. > Frameset definition: > [html snipped] > > I load this with the following code: > > File = "%s" % ('frameset.html') > PageHandle = open(File, "r") > PageInput = PageHandle.read() > PageHandle.close() > Display(PageInput) > > ...the html file will be found but I can see just an empty page. > > What can I do to realize this problem? > Is it possible to write in a specific frame from my scripts? What does that function Dispay do. Can you show the whole script, not just a part of it. From mwh at python.net Mon Mar 25 15:25:16 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 25 Mar 2002 20:25:16 GMT Subject: RELEASED: Python 2.2.1c1 References: Message-ID: Michael Hudson writes: > Depending on how many problems are found in this release, 2.2.1 > final or a second release candidate will follow next week. It will be 2.2.1c2 and it will be released in about 22 hours time. Cheers, M. -- 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 oc at opencontact.org Wed Mar 27 10:35:32 2002 From: oc at opencontact.org (William Levin) Date: Wed, 27 Mar 2002 15:35:32 GMT Subject: OpenContact.org Message-ID: <3CA1E66E.1070205@opencontact.org> Hello, This is an invitation for Open Source enthusiasts and contact management software developers to join OpenContact.org, a new online forum for the discussion of contact management systems. The ultimate goal of OpenContact.org is to explore options for integrating a centralized contact management database into the operating system; and to develop an extensive set of standard fields (akin to vCard) for universally compatible contact management. This would allow every third-party application on a computer to access the same contact data set, and eliminate the need to import and export contact data on a single system. More information is available at http://opencontact.org The site is in its infancy, and will greatly benefit from your knowledgeable contribution! Additionally, if your company would like to be affiliated with the OpenContact.org initiative, we will gladly exchange links on our site. Sincerely, William Levin -- http://OpenContact.org From alf at logilab.fr Wed Mar 27 06:15:44 2002 From: alf at logilab.fr (Alexandre Fayolle) Date: Wed, 27 Mar 2002 11:15:44 +0000 (UTC) Subject: Python Web Programming Book? References: Message-ID: Simon Brunning wrote: > Steve Holden's "Python Web Programming" sounds *exactly* right for you - it > covers web programming (both client & server side) *and* database > programming in some depth. > +1 ! Excellent book. Alexandre Fayolle -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Narval, the first software agent available as free software (GPL). From aahzpy at panix.com Thu Mar 21 19:25:49 2002 From: aahzpy at panix.com (Aahz) Date: 21 Mar 2002 19:25:49 -0500 Subject: mutlifile inheritance problem References: <9896e047.0203211303.741f695a@posting.google.com> <3C9A680A.F00216D2@hotmail.com> Message-ID: In article <3C9A680A.F00216D2 at hotmail.com>, Marc wrote: > >I have the reload in there because I'm developing this program now and >I want to be able to change different files without tracking down all >of the dependencies each time. That's not a problem. reload() is only useful in some limited contexts where you can't stop a running program; if your program exits between runs, there is no reason whatsoever to use reload(). I have no clue why you're having a problem with reload(), but I've never had a reason to use it myself and therefore am not familiar with its intricacies. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From logiplexsoftware at earthlink.net Tue Mar 26 15:03:20 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 26 Mar 2002 12:03:20 -0800 Subject: wxPython and wxFlexGridSizer problem In-Reply-To: <3CA0D05D.B42BF0E1@ccvcorp.com> References: <3C9FBE22.A72B4A27@ccvcorp.com> <3CA0D05D.B42BF0E1@ccvcorp.com> Message-ID: <20020326120320.5c29cc38.logiplexsoftware@earthlink.net> On Tue, 26 Mar 2002 11:47:41 -0800 Jeff Shannon wrote: > > > Cliff Wells wrote: > > > Also, I notice that your calls to gridSizer.Add are incorrect. The second > > argument is supposed to be a boolean flag indicating whether the widget > > should be expanded in the sizer's primary direction (in the case of a > > wxFlexGridSizer, I'm not sure what that means, but you still need the > > argument, at least as a placeholder). The wxALL and wxALIGN_* flags should > > be the third argument. > > Oooh, I missed that, the first time through. Actually, though, the second > argument isn't a boolean, though, it's an integer, which represents the > weighting given to that item when expanded. (If you add item 1 with weight 2, > item 2 with weight 0, and item 3 with weight 1, then any expanded space will be > split up, with 2/3 of it going to item 1 and 1/3 going to item 3...) Ah. I think that when I first started using wxPython I read that but for some reason couldn't get it working right (sizers can be as painful as they are helpful) and simply started using 1 or 0 and over time my mental prototype for this method "corrected" itself to match. I'll have to give this another try as it would be a useful feature. Is the meaning of this flag consistent across the different types of sizers, or is this only for wxBoxSizer? Thanks. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From phr-n2002a at nightsong.com Mon Mar 4 18:44:19 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 15:44:19 -0800 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: <7xbse3j3u4.fsf@ruckus.brouhaha.com> huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) writes: > So my question now is: What do I do to tell Python to compile with -lieee? I just edited the makefile and found the LIBS line and added -lieee. I didn't uncomment that #define that you found. From thomas at gatsoft.no Thu Mar 14 07:55:07 2002 From: thomas at gatsoft.no (Thomas Weholt) Date: Thu, 14 Mar 2002 12:55:07 GMT Subject: XML-RPC Question References: Message-ID: I'm not sure about this, but I think SimpleXMLRPCServer only provide access to the methods of the object you "publish", in your example the methods of MyClass, nothing else. system.listMethods() comes from .... .NET ?? I migth be wrong, and if so, please let me know. Thomas "Jesper Olsen" wrote in message news:cf0ad9fb.0203140407.2356290b at posting.google.com... > Has anyone used the SimpleXMLRPCServer class? > > Setting up a server goes something like this: > > from SimpleXMLRPCServer import * > > class MyClass: > def helloWorld(self): > return "Hello World!" > > def echo(self, text): > return text > > myob=MyClass() > > server=SimpleXMLRPCServer(("",50000)) > server.register_function(myob.helloWorld) > server.serve_forever() > > The server can now be accessed by a client, e.g.: > > import xmlrpclib > > srv=xmlrpclib.Server("http://localhost:50000") > > try: > print srv.helloWorld() > print srv.system.listMethods() > except xmlrpclib.Error, v: > print "Error", v > > The first srv.helloWorld() call succeeds, but srv.system.listMethods() results > in a "Fault 1" exception "system.listMethods" is not supported... > > Is there something wrong here, or does SimpleXMLRPCServer, not support > the listMethods() call? > > Cheers > Jesper From mlh at vier.idi.ntnu.no Thu Mar 7 14:27:52 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 7 Mar 2002 19:27:52 +0000 (UTC) Subject: Integers class...? Message-ID: With all this talk about iteration etc. I just thought I'd chuck in another idea. It is similar to several earlier ideas (and may even have been proposed in exactly this form before -- I just haven't seen it, or at least can't remember it). One of the interval syntaxes (e.g. for for-loops) I'd like is something like [0, 2 .. 10], similar to Haskell. This would require syntax changes in Python, which is a bit unrealistic, but we already have the three-dot Ellipsis, which is legal when indexing stuff. Creating an Integers class with a standard-named instance 'ints', one could do stuff like this (assuming for the moment that it's found in a separate module): from ints import ints for x in ints[0, 2, ..., 10]: print x The exact semantics (open/closed end etc.) would need to be decided on, of course, but the implementation is trivial -- with iterators it would be very simple to have infinite, lazy sequences too, like this: for x in ints[0, ...]: foobar(x) Yes, this is just syntactic sugar (which for some might be "line noise" -- a matter of taste, as always) for range(), but I think the ellipsis notation is quite intutitive. Dropping the name in front of the square brackets would be nice, of course, but that's less realistic, I guess :) Perhaps we could even make range indexable? -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From theller at python.net Wed Mar 20 04:43:04 2002 From: theller at python.net (Thomas Heller) Date: Wed, 20 Mar 2002 10:43:04 +0100 Subject: py2exe 0.3.1 hangs trying to remove build under Win98SE References: <88bc63c6.0203191142.1926b089@posting.google.com> Message-ID: "Doug Farrell" wrote in message news:88bc63c6.0203191142.1926b089 at posting.google.com... > Hi all, > > I'm trying to package up a Python2.2 program that uses wxPython with > the py2exe system and I'm having no luck. I open up a DOS window (I'm > running Win98SE) and run the following command line: > > python pyexe.py myscript.py > > The pyexe.py setup script is something I got from ASPN that is a > generalized setup script for this purpose, I've listed it below: > > from distutils.core import setup > import sys, os, py2exe > > name = sys.argv[1] > sys.argv[1] = 'py2exe' > > sys.path.append(os.path.dirname(os.path.abspath(name))) > > setup(name=name[:-3], scripts=[name]) > > > At the end of processing, I get the message: > removing 'build\bdist.win32\winexe' (and everything under it) > > At this point the DOS window hangs and never returns. In fact I have > trouble killing it with the Task Manager. In addition, at this point > Windows Explorer no longer runs, it comes up, but the window frame is > empty. I have to reboot my machine to get full control back. > Doug, I cannot reproduce this (at least with a trivial script under Win98SE). One thing I noted when I tried this: the build script cannot have the name 'py2exe.py', because in this case 'import py2exe' imports your compile script! You should rename it to something like 'compile.py', and be sure to delete any py2exe.pyc or py2exe.pyo which may have been created. I think this was mentioned in the ASPN recipe. > The script does create the dist directory where I expect it and there > is a myscript.exe and accompanying DLL's and such there. But if I try > to run that program, a DOS window comes up with various tracebacks in > it about not being able to import various modules. The myscript.py > file runs fine in the interpreter. Anyone have any idea what's going > on here? I'm runnig py2exe version 0.3.1, so I have the latest. > Depending on the modules your script uses, py2exe may have problems finding them. You should specify them to be included with the --includes or --packages flag. Thomas From theller at python.net Fri Mar 22 06:22:05 2002 From: theller at python.net (Thomas Heller) Date: Fri, 22 Mar 2002 12:22:05 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: <3C9A5C93.4DF63794@ccvcorp.com> Message-ID: "Jeff Shannon" wrote in message news:3C9A5C93.4DF63794 at ccvcorp.com... > > > Problems with freeze, IMO, are that it requires a C-compiler, > > > which most people on windows do not have... > > > > In the context of distutils, absence of a compiler may not be a > > problem: people building packages with distutils will need a compiler, > > atleast if the package contains extension modules. > > Yes, but it is entirely possible that someone may be building a pure > Python application, and wish to distribute that as a single file. It > would be desirable (though probably not essential) to require a C compiler > only in those cases where custom C extension modules are used. This may still (at least on windows) require extension modules: there are a lot of modules in separate dlls - just look into your python\DLLs directory. > > For instance, I'm working on an application that uses wxPython and > win32all, but all of my own code is pure Python. It's an internal > utility, so ease-of-packaging isn't a big priority (it's not too big of a > deal for me to install ActivePython + wxPython + my own bdist_wininst > package on each of the half-dozen machines that will need it), but I can > easily imagine a case in which it would be preferable to have a > single-file installer that would manage all of this automatically. Gordon's installer can create single file executables (which unpack dlls if you run them, and remove the dlls afterwards), also it can create a very simple minded installation program. Myself, I'm happy to either distribute zip-files or directories full of files (for internal use), or windows installers (WISE, or Innodist) for external use. Thomas From ponderor at lycos.com Sat Mar 16 02:04:11 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 15 Mar 2002 23:04:11 -0800 Subject: This may seem a slightly strange problem ... References: Message-ID: > But, aside from that, any advice on thinking up programs to write? Try Useless Python: http://www.lowerstandard.com/python for a community of similar folks.. ..and the Python Challange: http://www.lowerstandard.com/python/pythonchallenge.html for inspiration. From cpbotha at i_triple_e.org Sat Mar 30 07:16:16 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Sat, 30 Mar 2002 12:16:16 GMT Subject: GUI programming References: Message-ID: In article , Emmanuelgagniere wrote: > wxpython is the best one > > Umesh Persad a ?crit dans le message : > mailman.1017437568.25402.python-list at python.org... >> available. I am wondering which one should I use >> (tkinter, wxpython?) that will be simple enough >> to get me up and running qiuckly. Also are there >> any examples that I can look at? I'm not denying that wxPython is a very powerful UI library, but the fact that Tkinter is included with Python and that Tk is installed on most *ix systems by default (and very easy to install on windows systems) should not be underestimated. With wxPython, one has to get, configure and build wxWindows first (and this does take quite a while). If on *ix, one has to make sure that one has a current/functional installation of GTK, which could potentially mean configuring and building once again. After all of this, wxPython itself has to be made. All in all, this can be very frustrating to new users. My 2c, -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From hinsen at cnrs-orleans.fr Sat Mar 2 04:30:47 2002 From: hinsen at cnrs-orleans.fr (Konrad Hinsen) Date: 02 Mar 2002 10:30:47 +0100 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: References: Message-ID: Tim Peters writes: > > # Python 2.2 > > > > >>> 1e-200**2 > > Traceback (most recent call last): > > File "", line 1, in ? > > OverflowError: (34, 'Numerical result out of range') > > That one is surprising and definitely not intended: it suggests your > platform libm is setting errno to ERANGE for pow(1e-200, 2.0), or that your > platform C headers define INFINITY but incorrectly, or that your platform C > headers define HUGE_VAL but incorrectly, or that your platform C compiler > generates bad code, or optimizes incorrectly, for negating and/or comparing I just tested and found the same behaviour, on RedHat Linux 7.1 running on a Pentium machine. Python 2.1, compiled and running on the same machine, returns 0. So does the Python 1.5.2 that comes with the RedHat installation. Although there might certainly be something wrong with the C compiler and/or header files, something has likely changed in Python as well in going to 2.2, the only other explanation I see would be a compiler optimization bug that didn't have an effect with earlier Python releases. > OverflowError before. Please file a bug report with full details about > which operating system, Python version, compiler and C libraries you're > using (then it's going to take a wizard with access to all that stuff to > trace into it and determine the true cause). I am willing to look into this if no one else does. But it won't be immediately. Konrad. -- ------------------------------------------------------------------------------- Konrad Hinsen | E-Mail: hinsen at cnrs-orleans.fr Centre de Biophysique Moleculaire (CNRS) | Tel.: +33-2.38.25.56.24 Rue Charles Sadron | Fax: +33-2.38.63.15.17 45071 Orleans Cedex 2 | Deutsch/Esperanto/English/ France | Nederlands/Francais ------------------------------------------------------------------------------- From kragen at pobox.com Wed Mar 20 19:03:25 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 20 Mar 2002 19:03:25 -0500 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: <83sn6udbxu.fsf@panacea.canonical.org> martin at v.loewis.de (Martin v. Loewis) writes: > That is certainly possible; freeze would be the obvious choice for > such a mechanism (IMO). Alas, distutils is unmaintained, so don't wait > for anybody else to implement it for you. That's rather shocking. How did distutils get to be unmaintained? From jeff at ccvcorp.com Fri Mar 22 13:49:29 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 10:49:29 -0800 Subject: __file__ for relative imports References: Message-ID: <3C9B7CB9.9EC64693@ccvcorp.com> Fran?ois Pinard wrote: > [Ken Seehof] > > > > Robin Becker writes: > > > > > > > Is there an obvious reason why modules imported from the current > > > > directory don't have an absolute pathname for __file__? > > > I keep bumping into that one too. [...] > > There is another tiny bit in that area which might be debated as well. > > `__file__' is not defined for the `__main__' module. But `sys.argv[0]' in > that case contains the information one might have hoped out of `__file__'. > I would like if `__file__' was just dependably defined in all circumstances, > the best the Python interpreter can. .... I like this idea a lot. Even if, for __main__, we ended up with __file__ being (potentially) '', or '', or even None, it'd be nice to be able to depend on the name being defined. Jeff Shannon Technician/Programmer Credit International From kirill_simonov at mail.ru Sun Mar 31 18:43:09 2002 From: kirill_simonov at mail.ru (Kirill Simonov) Date: Mon, 1 Apr 2002 02:43:09 +0300 Subject: PEP 285: Adding a bool type In-Reply-To: References: <3CA5E2EA.1CADAF70@engcorp.com> <3CA5F90F.BF37B528@engcorp.com> Message-ID: <20020331234309.GA704@abulafia.local> * Martin v. Loewis : > Can you show examples of (real!) code that will break? Preferably code > you've written yourself. The changes will break the code like this: if type(arg) == type(''): ... elif type(arg) == type(0): ... You can find such code even in the standard library. -- xi From phd at phd.pp.ru Mon Mar 4 13:27:30 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 4 Mar 2002 21:27:30 +0300 Subject: open() error ---- what am I missing? In-Reply-To: <7vOg8.10828$hK4.4034599@e420r-atl1.usenetserver.com>; from torstenson@no-spam.oti-hsv.com on Mon, Mar 04, 2002 at 11:56:36AM -0600 References: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com> <7vOg8.10828$hK4.4034599@e420r-atl1.usenetserver.com> Message-ID: <20020304212730.D11643@phd.pp.ru> On Mon, Mar 04, 2002 at 11:56:36AM -0600, Eric Torstenson wrote: > OK, imported __builtin__ and used __builtin__.open(blah, blah) and got the > same result, so I am guessing that is not a matter of function hiding, but > some other error that I am just being blind to. Try to call it "open(filename, 'w')" - that is, without "mode="... Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From peter at engcorp.com Mon Mar 4 21:07:19 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Mar 2002 21:07:19 -0500 Subject: chopping a string References: Message-ID: <3C842857.275363E7@engcorp.com> David Bear wrote: > > there's gotta be an easier way. I have a string > " something somethingelse " > > note the leading a trailing whitespace. I'd like to grab the first > word and strip whitespace. I came up with > > string.join(string.split(string.strip(str))[:1]) > > but I'm thinking, there must be a better way? better means (faster) (smaller).. Did you try this? >>> a = ' test this ' >>> a.split() ['test', 'this'] >>> a.split()[0] 'test' From phd at phd.pp.ru Mon Mar 18 03:56:18 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 18 Mar 2002 11:56:18 +0300 Subject: Where to download bugfix for email Module? In-Reply-To: ; from usenet@thinkspot.net on Sun, Mar 17, 2002 at 02:52:30PM -0800 References: Message-ID: <20020318115618.B2199@phd.pp.ru> On Sun, Mar 17, 2002 at 02:52:30PM -0800, Sheila King wrote: > > The simplest (though not the best) solution would be to distribute a > > copy of the email package with your code. You know, Python inserts the path > > to your application in the beginning of sys.path, so upon "import email" > > your copy of the package will be imported, and not standard package. > > Thanks for the suggestion. > > Out of curiousity...what is the *best* (or better) method??? There is no "one size fits all" solution. You can distribute email package with your own setup.py, and instruct your user to install it separately, or just install it automatically in your package's setup.py. Or you may instruct a user to download mimelib from mimelib.sf.net and install it. Or wait for Python 2.3. It depends on who your users are and what do you want to achieve - do you want to distribute updates to the email packages every time it gets updates, do you want to instruct users to remove your version of the email package when Python 2.3 will appear, and so on. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From Luap777 at hotmail.com Sun Mar 31 10:24:41 2002 From: Luap777 at hotmail.com (Paul) Date: 31 Mar 2002 07:24:41 -0800 Subject: Possible to save router logs? Message-ID: I have a D-Link 704 cable/DSL router. Unfortunately, it has very limited logging capabilities(in that it doesn't save logs, it just rights over them when the space fills.) What I would like to do is right a program to save the logs to my hard drive every 12 hours or so. I normally have to access the web page with the url being the local IP of the router, then type in a password to get access to the logs. Has anyone attempted something like this? I know this is kinda general, but any feedback would be appreciated. It might give me an idea of where to begin. Thank you. From nhodgson at bigpond.net.au Tue Mar 19 04:50:21 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 19 Mar 2002 09:50:21 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: Martin v. Loewis: > "Neil Hodgson" writes: > > > Unfortunately, I haven't had time recently to push the PEP any further. > > I'm also less certain of its cost / benefit ratio than I was initially as it > > does complexify the Python library code a bit. > > I still think this is the way to go. For character data, use Unicode > where you can - in particular if the operating system interface > supports that, as well. It is the right approach but in terms of packaging its a mess and this will have a maintenance cost. Perhaps moving all the NT specific Unicode handling into a separate file would help although I haven't seen a clean way to do that either as it will then require a bunch of forwarding functions. If there was a good way to subclass posixmodule for this code... Neil From phd at phd.pp.ru Wed Mar 13 06:05:57 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 13 Mar 2002 14:05:57 +0300 Subject: load_site.py error In-Reply-To: <20020313103119.20866.qmail@web13603.mail.yahoo.com>; from manish_ssharma@yahoo.com on Wed, Mar 13, 2002 at 02:31:19AM -0800 References: <20020313103119.20866.qmail@web13603.mail.yahoo.com> Message-ID: <20020313140556.C27310@phd.pp.ru> On Wed, Mar 13, 2002 at 02:31:19AM -0800, Manish Sharma wrote: > I want to upload some files in zope using load_site.py > While running the command in python i m getting the error Syntex error : invalid token > > the command statement is > > >>> python .\load_site.py -u manish:manishkumar -D http:localhost:8080/test/ /tests/ > > here test is a folder created in zope manager and tests is come with Load_site kit having three .htm files. The last /test/ is a folder on a disk, from where you are going to upload files. Are you sure it exists? Give correct path. > i tried wxLoadSite.py through python > >>> python .\wxLoadSite.py > it also giving the same error of invalid token > > if i will use >>> python ./wxLoadSite.py it will give error Syntex Error : invalid syntax Do not give the command inside python - give it in your command line. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From peter at engcorp.com Tue Mar 12 21:32:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Mar 2002 21:32:18 -0500 Subject: trouble testing for existance of variable References: <4bbaa6d6.0203121352.4358f14@posting.google.com> Message-ID: <3C8EBA31.610BD39D@engcorp.com> googlePoster wrote: > > in the interest of full disclosure, I should have said > since I am using python as a gvim scripting tool I > must import the gvim variable, colors_name, before > I can work with it Ah, posting real code is always the best approach. :) > E121: Undefined variable: colors_name > E15: Invalid expression: colors_name > Traceback (most recent call last): > File "", line 1, in ? > File "testMe.py", line 36, in ? > curr_color = vim.eval("colors_name") > vim.error: invalid expression "vim.error" is the key. It is highly likely that that is a vim-specific exception which you should be catching instead of NameError. Try this: try: curr_color = vim.eval("colors_name") except vim.error: curr_color = None if curr_color: print "colorscheme: %s" % curr_color else: print "no color scheme" You might also try typing :py import vim; vim.error.__class__.__bases__ and see what it reports. If it mentions something like (,) you will have a better idea what it represents. RTFM might help too, if you can find a mention of it. -Peter From tim.one at comcast.net Mon Mar 25 15:15:23 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 25 Mar 2002 15:15:23 -0500 Subject: list comprehension question In-Reply-To: <20020325113323.A26319@glacier.arctrix.com> Message-ID: [Tim] > No. len([f(x) for x in y]) == len(y) whenever no exception occurs, > regardless of the form of f() or type of y. [Neil Schemenauer] > Looks like the bot needs a bugfix: Nope, an exception occurs in your example when evaluating len([f(x) for x in f()]) == len(f()) and the bot refused to say anything about what happens then (I confirmed that this was intentional, and he was quite irked (for a bot) that I questioned him on this point). As you show below, one also occurs when a non-bot human substitutes len(f), which is a different expression entirely. Also not covered are cases where len(y) returns an object that raises an exception when "==" tries to compare it. > >>> def f(): > ... for x in range(10): > ... yield x > ... > >>> len(f) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: len() of unsized object > >>> len([int(x) for x in f()]) > 10 > > Hmm, should len() should work on pure iterators? I don't think so (the bot has no opinion on this, btw), and deliberately left len() alone when generalizing "sequence contexts" for 2.2. __len__ is best thought of as a functional (no side-effect) method of sequences nd mappings, and there's generally no reason to suppose that len(iterable) wouldn't be destructive -- the iterator protocol doesn't have any notion of resetting, and some iterators can't be restarted. So the potential for suprise is high, and the few sane use cases are easily programmed explicitly; e.g., len(list(f)), or a loop to drive the iterator and count how many times it goes around. From tim.hochberg at ieee.org Thu Mar 14 22:03:12 2002 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Fri, 15 Mar 2002 03:03:12 GMT Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: James_Althoff wrote: > Here's a q&d sample implementation in case anyone wants to test out the > idea before deciding on its merits. [Implementation of keys, iterkeys, values, itervalues, etc. for a list object] FWIW, here's the corresponding implementation in terms of generic functions instead of methods, an approach I like better than the method approach. # itertools.py """ Tools for working with iterables. Note: several of these functions assumes that if an object has a 'keys' method, it will also have an 'iterkeys' method and they will be consistent. Contents: * keys(I) / iterkeys(I) -> list / iterator for I's keys >>> list(iterkeys('abcd')) [0, 1, 2, 3] >>> _sorted(iterkeys({'fee' : 'one', 'fie' : 'two', 'foe' : 'three', 'fum' : 'four'})) ['fee', 'fie', 'foe', 'fum'] * values(I) / itervalues(I) -> return a list / iterator for I's values >>> list(itervalues('abcd')) ['a', 'b', 'c', 'd'] >>> _sorted(itervalues({'fee' : 'one', 'fie' : 'two', 'foe' : 'three', 'fum' : 'four'})) ['four', 'one', 'three', 'two'] * items(I) / iteritems(I) -> list / iterator for I's items [(key, value) pairs] >>> list(iteritems('abcd')) [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] >>> _sorted(iteritems({'fee' : 'one', 'fie' : 'two', 'foe' : 'three', 'fum' : 'four'})) [('fee', 'one'), ('fie', 'two'), ('foe', 'three'), ('fum', 'four')] * iterzip(I1, [I2, [...]]) -> lazy version of zip. >>> list(iterzip('abcdef', [1,2,3,4], ('cold', 'warm', 'hot'))) [('a', 1, 'cold'), ('b', 2, 'warm'), ('c', 3, 'hot')] """ from __future__ import generators def _sorted(iterable): l = list(iterable) l.sort() return l def iterkeys(iterable): """iterkeys(I) -> iterator for I's keys""" if hasattr(iterable, 'iterkeys'): for k in iterable.iterkeys(): yield k else: k = 0 for v in iterable: yield k k += 1 def keys(iterable): """keys(I) -> list of I's keys""" return list(iterkeys(iterable)) def itervalues(iterable): """itervalues(I) -> iterator for I's values""" if hasattr(iterable, 'itervalues'): for v in iterable.itervalues(): yield v else: for v in iterable: yield v def values(iterable): """values(I) -> list of I's values""" return list(itervalues(iterable)) def iteritems(iterable): """iteritems(I) -> iterator for I's items [(key, value) pairs]""" if hasattr(iterable, 'iteritems'): for i in iterable.iteritems(): yield i else: k = 0 for v in iterable: yield k, v k += 1 def items(iterable): """items(I) -> list of I's items [(key, value) pairs]""" return list(iteritems(iterable)) def iterzip(*args): """iterzip(I1 [, I2 [...]]) -> (I1[0], I2[0] ...), ... Return an iterator yielding tuples, where each tuple contains the i-th element from each of the argument iterables. The iterator returns as many tuples as are in the shortest argument sequence. """ if not args: raise TypeError("iterzip requires at least one sequence") iters = [iter(a) for a in args] while 1: value = [] for i in iters: value.append(i.next()) yield tuple(value) From skip at pobox.com Tue Mar 12 18:08:14 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 12 Mar 2002 17:08:14 -0600 Subject: NormalDate 1.2 released In-Reply-To: References: Message-ID: <15502.35422.24087.262906@beluga.mojam.com> [... 13 X 28 + 1 or 2 ...] Timothy> Why was this simple system never adopted? As someone else said earlier in this thread, "latitude, longitude, attitude (aka religion)". S From mlh at vier.idi.ntnu.no Thu Mar 14 10:50:39 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 14 Mar 2002 15:50:39 +0000 (UTC) Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy Message-ID: Should I use Server or ServerProxy as the name for the ServerProxy class in xmlrpclib? The standard docs use Server, while the effbot seems to use ServerProxy, and >>> xmlrpclib.Server is xmlrpclib.ServerProxy 1 so... I find ServerProxy to be a more logical name, but the fact that I can't find it mentioned in the docs makes me a bit wary of using it... (On the other hand, ServerProxy is what's documented in the docstring. What is the history behind this duality -- and what is the motivation for the conflicting current usage? - Magnus (who thinks that SimpleXMLRPCServer should be called xmlrpclib.Server, with xmlrpclib.ServerProxy being used as the server proxy... :) -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From a.clarke11 at pop.ntlworld.com Sun Mar 17 20:36:53 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Mon, 18 Mar 2002 01:36:53 +0000 Subject: how to print class names, not references Message-ID: <3C9544B5.47CD0918@pop.ntlworld.com> Hi, I wrote a function of x, where later in the program x is substituted by class names. In the function, print x is used, but this returns <__main__.Player instance at 0x38b1ce90> rather than the plain old class name that I wanted. How can I print the name instead? Thanks for your help, Pythoneers... From jeff at ccvcorp.com Fri Mar 22 14:01:33 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 11:01:33 -0800 Subject: eval() References: Message-ID: <3C9B7F8D.CE9FCB24@ccvcorp.com> maximilianscherr wrote: > what does eval exactly do? Cause trouble for people who use it when they don't need to. ;) (And if you're not *completely* sure what it does, then it's a safe bet that you don't need to use it.) Jeff Shannon Technician/Programmer Credit International From jimd at vega.starshine.org Thu Mar 21 18:03:31 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 21 Mar 2002 23:03:31 GMT Subject: Begginers Guide - Exrcise. Help me, plz! References: Message-ID: In article , Sean 'Shaleh' Perry wrote: >On 16-Mar-2002 Jeffrey-man wrote: >> Hello, everybody! >> I'm a newbie and I'm just learning. I know, it's a stupid question, but I >> want to resolve it. >> Learning the Begginers Guide, I found an exercise. It tells me: >> "Write a program that continually reads in numbers from the user and adds >> them together until the sum reaches 100." >> Can anybody help me? ... >> Maybe I'm doing something wrong? > you misread the specification. > You are to ask the user "give me a number", add that number to the > previous one (hint: use zero the first time), then check if the new > sum is less than the stopping point (100 in this case). If the stopping > point is reached, cease asking for a number. >Does that help? Shouldn't all these (helpful) examples be using raw_input() rather than input(). Do we really want the new user to be implicitly and blindly using eval(raw_input())? From bokr at oz.net Mon Mar 25 14:10:33 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Mar 2002 19:10:33 GMT Subject: list comprehension question References: Message-ID: On Mon, 25 Mar 2002 00:25:15 -0500, Tim Peters wrote: >[Tripp Scott] >> thanks for the tip. actually, the essence of what i wanted to >> ask was: "can that SOMETHING be a list of more than one elements >> which will be _flatly_ added to the result list." > >No. len([f(x) for x in y]) == len(y) whenever no exception occurs, >regardless of the form of f() or type of y. > >> as another example, can i generate this list >> >> [1,1 2,2,2, 3,3,3,3, 4,4] >> >> with a list comprehension that contains one 'for' clause? > >Sure, via the obvious spelling: > > [i for i in 1,1, 2,2,2, 3,3,3,3, 4,4] > >Cleverness can't improve one that. Nope. Simple is best, but you _can_ also mess with 'for x in ...' >>> [x<2 and 1 or x<5 and 2 or x<9 and 3 or x<=11 and 4 for x in xrange(11)] [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4] which also has one 'for' clause ;-) Regards, Bengt Richter From ingoogni at home.nl Thu Mar 21 08:42:03 2002 From: ingoogni at home.nl (ingo) Date: Thu, 21 Mar 2002 13:42:03 GMT Subject: How Can I Determine the Operating System with Python? References: Message-ID: in news:mailman.1016713720.31917.python-list at python.org Mark Gash wrote: > The only way of defining the os name that I have found is then to > examine the os.environ .By examining the COMSPEC you will be able to > determine a win 9X machine opposed to an NT or 2000 machine (comspec > for 9X will show command.com whereas win32 machines will show > cmd.exe). > >>> os.environ['OS'] 'Windows_NT' No idea what it does on other platforms. Ingo From jason at jorendorff.com Mon Mar 11 02:46:15 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 11 Mar 2002 01:46:15 -0600 Subject: PyQT: QString to String Problem if ASCII>128 In-Reply-To: <3C8916B7.E5396663@gmx.de> Message-ID: Ingo Linkweiler wrote: > no ideas? > > I found a possible solution, but is this the best way? > > uc=self.edit.text() > try: > t=str(uc) > except: > try: > t=unicode(self.edit.text()).encode("cp437") > except: > t="invalid char in string" I guess you want something like uc = self.edit.text() t = unicode(uc).encode("cp437", errors="replace") I can't test it here, though. ## Jason Orendorff http://www.jorendorff.com/ From janez.jere at void.si Mon Mar 11 09:17:44 2002 From: janez.jere at void.si (Janez Jere) Date: Mon, 11 Mar 2002 15:17:44 +0100 Subject: Zope stdin References: <3C8BECF0.30207@void.si> Message-ID: Are you sure? My echo is not working properly in ZCGI. BTW, I dont want to run a separate process, i just want to read() posted data AS in CGI. Janez # CGI script and test import sys, os if len(sys.argv) == 1: print 'Content-Type: text/plain' print #length = os.environ['CONTENT_LENGTH'] #print 'length', length print repr(sys.stdin.read())#int(length))) else: # test echo url = sys.argv[1] import urllib2 as w x= w.urlopen(url, 'abc '*300) print 'read(%s):\n' % url, x.read() On Sun, 10 Mar 2002 23:51:44 GMT, Darrell wrote: >http://www.zope.org/Members/haqa/ZCGI > >Janez Jere wrote: > >> HHi, >> could anyone help me port my simple cgi to zope script. Problem which I >> am unable to solve is reading posted raw data (legacy client posts a xml >> document to my cgi and expects a result). >> >> Among all my attempts the closest solutions are: >> request.get(BODY) # BODYFILE a >> and >> request.stdin.read() # but it is not allowed to access read method. >> >> #echo cgi >> import sys, os >> length = os.environ['CONTENT_LENGTH'] >> print 'Content-Type: text/plain' >> print >> print sys.stdin.read(int(length)) >> >> Thank for help. >> Janez From dsavitsk at e-coli.net Mon Mar 11 15:31:50 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 11 Mar 2002 20:31:50 GMT Subject: COM traceback translation Message-ID: can anybody help with this one? there is a module called test_write. when it is imported from a python prompt and generate_doc() is called it works fine. When it is invoked by a COM object it throws this error. thanks, doug Traceback (most recent call last): File "X:\epsp2\server\bin\test_write.py", line 5, in generate_doc wordApp = win32com.client.Dispatch('Word.Application') File "C:\Python\win32com\client\__init__.py", line 94, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python\win32com\client\dynamic.py", line 81, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) From jeff at ccvcorp.com Fri Mar 22 13:57:19 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 10:57:19 -0800 Subject: How to delete/mainpulate global variables ?? References: Message-ID: <3C9B7E8E.A9F639DC@ccvcorp.com> Berenike Loos wrote: > I am using two function in my program. The first one reads > out some text of an TK entry field and puts it into a > global variable. The other function has to read out the > global variable and has to print out the text. Now the > global variable should be deleted, so if I call the second > function again without calling the first, NO text will be > displayed. thx a lot Well, first off, I'd point out that global variables are usually not the best way to do things. There's a fair chance in any nontrivial program that they will be changed in ways (or at times) that you don't expect them to. But the short answer to your question, is to have the second function set the variable equal to None. Var1 = None def Func1(): global Var1 Var1 = GetValueFromWidget() def Func2(): global Var1 if Var1 is not None: print Var1 Var1 = None Jeff Shannon Technician/Programmer Credit International From posselt at brics.dk Fri Mar 8 08:32:38 2002 From: posselt at brics.dk (Peter Posselt Vestergaard) Date: Fri, 8 Mar 2002 14:32:38 +0100 Subject: returning a picture Message-ID: Hi I would like to be able to enter an URL to a python script in the src field of an img tag in html. The script is then supposed to return a picture which will be shown in the html-page. I am loading and editing the picture the Python Image Library (PIL) but how should I return/print it to do what I want? Thanks Regards Peter Vestergaard From robin at jessikat.fsnet.co.uk Wed Mar 27 09:18:54 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 27 Mar 2002 14:18:54 +0000 Subject: ReportLab Toolkit 1.13 Released Message-ID: ReportLab Toolkit version 1.13 released. Besides fixing some bugs and improving existing features this release is compatible with Python 2.2. The pdfgen Canvas now has XObject images which means smaller PDF's. A fast interface to the RXP xml parser is in the rl_addons project. NB the old rl_config._verbose flag was renamed to verbose. http://www.reportlab.com/ftp/ReportLab_1_13.zip http://www.reportlab.com/ftp/ReportLab_1_13.tgz -- Robin Becker From msx at crs4.it Fri Mar 15 03:33:55 2002 From: msx at crs4.it (Federico Caboni) Date: Fri, 15 Mar 2002 09:33:55 +0100 Subject: Good book on Python? References: Message-ID: On 14-03-2002 17:08, in article slrna91io0.ha5.philh at comuno.freeserve.co.uk, "phil hunt" wrote: > On Thu, 14 Mar 2002 13:35:53 +0100, Federico Caboni wrote: >> >> I recently bought "Programming Python" by O'Really, > > Oh. Really? LOL... Little typo ;) ____ ____ ____ _ _ ____ _ _ ____ / ___)| __ \/ ___)/ /| | / ___)| \| |/ ___) Federico Caboni (msx at crs4.it) | (___ | /\___ \\__ | * \___ \| |\___ \ Software & Network Solutions \____)|_|\_\(____/ |_| (____/|_|\_|(____/ Phone: +39 070 2796 368 CRS4, Center for Adv. Studies, Research and Development in Sardinia From akuchlin at ute.mems-exchange.org Thu Mar 7 12:21:20 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 07 Mar 2002 17:21:20 GMT Subject: Python daemon instead of CGI programs References: <88bc63c6.0203061444.30ad9c44@posting.google.com> <7x7kope1n9.fsf@ruckus.brouhaha.com> Message-ID: In article <7x7kope1n9.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > writeson at earthlink.net (Doug Farrell) writes: >> What do you think of this idea? Am I completely off base and missing >> some other obvious solution? > > It's a sound idea, but there's already a FastCGI protocol that amounts > to the same thing and is used for the same reasons. Someone has > almost certainly already implemented FastCGI servers in Python. We used the Apache mod_fastcgi for our site, and found it to be buggy and unreliable, occasionally going catatonic, possibly due to a deadlock of some sort in its process management code. Neil wrote a much simpler Apache module, mod_scgi, that just forwards the request data to a server listening on a given port, and starting the server is left up to you, so you can add an /etc/init.d script or whatever you like. Unfortunately we haven't wrapped up mod_scgi for release yet. --amk (www.amk.ca) One of *my* funny turns? The whole world took a funny turn... -- The Doctor, in "City of Death" From printers at sendme.cz Mon Mar 25 17:16:28 2002 From: printers at sendme.cz (A) Date: Mon, 25 Mar 2002 23:16:28 +0100 Subject: How to get a key from dictionary? Message-ID: <3C9FAFCC.20062.91741D@localhost> Hi, Is there a possibility to get, from a dictionary, a key according to a value ? For example I have a dictionary dict={'aa':1,'bb':2} and dict['aa'] is 1 But how can I for value 1 find out key? (That is here 'aa') Thank you for help Ladislav From helmut.zeisel at aon.at Fri Mar 8 02:59:51 2002 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: 7 Mar 2002 23:59:51 -0800 Subject: SWIG and abstract base class References: Message-ID: Luigi Ballabio wrote in message news:... > At 08:01 AM 3/7/02 -0800, Helmut Zeisel wrote: > >I want to use SWIG to create a Python module for > >a C++ class hierarchy using abstract base classes: > > Helmut, > I'm assuming that you're using a reasonably recent version of SWIG > (let's say >= 1.3.9). 1.3.11 > > class Base { > private: > Base(); > public: > // whatever > }; > > hope this helps, > Luigi I also had to add a private/protected ~Base(), but now it works. Thank you, Helmut From loewis at informatik.hu-berlin.de Wed Mar 20 06:26:27 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 20 Mar 2002 12:26:27 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: "Thomas Heller" writes: > Do you think that PyImport_FrozenModule() should be extended to handle > compressed byte codes? Yes, this is what I had in mind. > Or should freeze simply append the compressed byte codes to the > executable (as py2exe and installer do it) instead of compiling them > with the C-compiler? That can't work portably across compilers and operating systems. > An interesting idea would be to additionally distribute Python and > extension modules (on windows) not only as dlls, but also as static > libraries. In this case only a linker would be needed, and you avoid > the problems compiling all the sources... If you use freeze, you will still need a compiler. But I agree that a static library would be nice to have. > Another possibility would be to use a program creating a standalone > exe-file from exe and dlls. I have once tried such a program, it worked > in simple cases, but not for Python. Then I wrote some code (in python) > myself to do this, it is very tricky, but certainly possible. This sounds platform-specific, so it is not very interesting to me. Regards, Martin From see at below Mon Mar 11 06:16:45 2002 From: see at below (Paul Foley) Date: 12 Mar 2002 00:16:45 +1300 Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: On Sat, 09 Mar 2002 20:51:02 GMT, logistix wrote: > I ain't no lisp expert (so please don't yell at me Paul F. ; ) ), but the > interpreter is a read-eval-apply loop. > 1. A statement is READ in > 2. The arguments are EVALuated (unless short circuited by a quote) > 3. The evaluated arguements are APPLYed to the function, result is returned 1. A form is READ in 2. The form is evaluated 3. The results are printed [CL supports multiple values] The evaluation consists of first evaluating the arguments to functions, but QUOTE forms are evaluated, too; its value is just its argument, unevaluated. QUOTE is one of a small number of hard-wired things called "special operators" that have special meaning and don't follow the normal evaluation rules. E.g., ignoring a few details, def EVAL (form): # macroexpand form here if type(form) is not type([]): # if it's a symbol, return its symbol-value return form elif form[0] is QUOTE: if len(form) != 2: raise SomeException return form[1] # other special forms here else: return apply(form[0], map(EVAL, form[1:])) [Many implementations don't actually have an interpreter at all, and implement EVAL as something more like (defun eval (form) (funcall (compile nil `(lambda () , at form)))) i.e., just compile a function whose body is the form in question, and immediately execute the newly-compiled function. `(lambda () , at form) means essentially "[LAMBDA, []] + form" in Python] > "N Becker" wrote in message > news:1f5252d4.0203080721.3bfc5c14 at posting.google.com... >> Back in 1999, I asked "where is quote?". I was looking for >> a way to quote a function (delay evaluation). >> >> I wonder if there is anything new. It looks to me that the >> best answer is to use lambda. Quoting code for later evaluation with EVAL is almost guaranteed not to be what you want, anyway. LAMBDA is the right thing. -- Oh dear god. In case you weren't aware, "ad hominem" is not latin for "the user of this technique is a fine debater." -- Thomas F. Burdick (setq reply-to (concatenate 'string "Paul Foley " "")) From nhodgson at bigpond.net.au Tue Mar 19 03:39:17 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 19 Mar 2002 08:39:17 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: Andrew Markebo: > I am messing a bit with my bookmarks (gonna sync them between a bunch > of computers and browsers) and now comes the question.. How does > os.listdir in the windows-compiled python handle international > characters? If the characters can not be represented in the current code page you get '?' instead. > But do we know that it is latin-1? How would we handle chineese > characters? Someone said the filenames were unicoded, how do I > encode/decode the filename som I can get it into UTF-8?? PEP 277 looks at providing more Unicode file name support including extending os.listdir to return Unicode strings. http://python.sourceforge.net/peps/pep-0277.html Unfortunately, I haven't had time recently to push the PEP any further. I'm also less certain of its cost / benefit ratio than I was initially as it does complexify the Python library code a bit. > p.s.2 what is the status on win9x? Give it up or ;-) More difficult as 9x doesn't have API support for retrieving the Unicode names, so it could require reading the directory bytes directly. Neil From python at rcn.com Fri Mar 15 07:52:11 2002 From: python at rcn.com (Raymond Hettinger) Date: Fri, 15 Mar 2002 07:52:11 -0500 Subject: converting reference name to string ? References: <14b2057b.0203150254.2480f7ae@posting.google.com> Message-ID: Since objects can be bound to more than one variable, the question, what is my name, doesn't translate to what variables am I bound to. The .__name__ attribute can tell you where something was created but not what it is bound to. In your example, >>> def a(): hello >>> d = a >>> d.__name__ # surprise! 'a' # this is where it was defined, not where its bound There is a way to find out which variables an object is bound to; however, it is both arcane and evil in its intent. Generally, if an object needs to know what things refer to it, then there is a design flaw. Raymond "tleduc" wrote in message news:14b2057b.0203150254.2480f7ae at posting.google.com... > example: > > def a(): > print 'hello' > > ==> string is a.__name__ > > but for instances: > > class myclass: > ....etc.... > > b = myclass() > c = myclass() > > in execution of this script, how do i get reference string 'a' 'b' or 'c' ? > > Thanks in advance. > > Thibaut From martin at v.loewis.de Tue Mar 19 04:05:37 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Mar 2002 10:05:37 +0100 Subject: Chewing international (unicode) filenames on windows? References: Message-ID: "Neil Hodgson" writes: > Unfortunately, I haven't had time recently to push the PEP any further. > I'm also less certain of its cost / benefit ratio than I was initially as it > does complexify the Python library code a bit. I still think this is the way to go. For character data, use Unicode where you can - in particular if the operating system interface supports that, as well. Regards, Martin From mlh at vier.idi.ntnu.no Mon Mar 18 17:08:34 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 18 Mar 2002 22:08:34 +0000 (UTC) Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy References: Message-ID: In article , Fredrik Lundh wrote: >Magnus Lie Hetland wrote: >> I find ServerProxy to be a more logical name, but the fact that I >> can't find it mentioned in the docs makes me a bit wary of using >> it... (On the other hand, ServerProxy is what's documented in the >> docstring. What is the history behind this duality -- and what is the >> motivation for the conflicting current usage? > >the original code used Server -- after all, the object is >representing a remote server. Well, that's one way of seeing it; but it *is* an xmlrpc *client*, no? Of course, any "proxyish" client could be said to represent a server, but calling them servers seems to muddle things, IMO. I haven't had any problems with the Server naming, really; it just seems a bit odd when I have a server object on each end of the network... And things become even weirder when I write peer-to-peer stuff, where one object is both client and server... Or, in this case "server and server". Then it *is* one and *represents* the other (through the proxy class). >the (rather lame) ServerProxy alias was added later, after >enough people had flamed me over the original naming... OK. I just saw you using it in some code somewhere, and assumed that perhaps it was the (i.e. your) preferred usage. I guess it wasn't, then :) >> who thinks that SimpleXMLRPCServer should be called >> xmlrpclib.Server, with xmlrpclib.ServerProxy being used as the >> server proxy... > >most XML-RPC users don't use/need server functionality, >and shouldn't have to pay for something they don't use... Pay for? How so? By having to load the code? Oh, well. I didn't really see this as a realistic wish anyway. > -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From krissepu at vip.fi Tue Mar 5 04:15:00 2002 From: krissepu at vip.fi (pekka niiranen) Date: Tue, 05 Mar 2002 09:15:00 GMT Subject: Compiling Python 2.2 for HPUX 10.20 does not work References: Message-ID: <3C848CBF.9000201@vip.fi> Hi, I tried the build script below in HP-UX 10.20 ( HP-UX B.10.20 A 9000/777 2002144332 two-user license) and got the following errors during make: cc -Ae -c -DNDEBUG -O -I. -I./Include -DHAVE_CONFIG_H -o Modules/python.o Modules/python.c (Bundled) cc: warning 480: The -A option is available only with the C/ANSI C product; ignored. (Bundled) cc: warning 480: The -O option is available only with the C/ANSI C product; ignored. cpp: "Python.h", line 44: warning 2013: Unknown preprocessing directive. cpp: "pyport.h", line 86: warning 2013: Unknown preprocessing directive. cpp: "pyport.h", line 419: warning 2013: Unknown preprocessing directive. cpp: "pyport.h", line 437: warning 2013: Unknown preprocessing directive. cpp: "pyport.h", line 86: warning 2013: Unknown preprocessing directive. cpp: "pyport.h", line 419: warning 2013: Unknown preprocessing directive. cpp: "pyport.h", line 437: warning 2013: Unknown preprocessing directive. cpp: "objimpl.h", line 187: warning 2013: Unknown preprocessing directive. cpp: "unicodeobject.h", line 73: warning 2013: Unknown preprocessing directive. (Bundled) cc: "Include/pymem.h", line 88: error 1000: Unexpected symbol: "size_t". (Bundled) cc: "Include/object.h", line 103: error 1000: Unexpected symbol: "*". (Bundled) cc: "Include/object.h", line 104: error 1000: Unexpected symbol: "*". (Bundled) cc: error 2017: Cannot recover from earlier errors, terminating. *** Error exit code 1 Anybody had luck with compiling ? -pekka- czrpb wrote: >Michael: > >That seemed to work, thanks! > >Could I bother you to explain why and more importantly why Python >itself can not figure this out? > >thanks!! -- Quentin > >--- In python-list at y..., Michael Piotrowski wrote: > >>"czrpb" writes: >> >>>I am having the following issues compiling: >>> >>>HPUX 11.0 >>>========= >>> >>[...] >> >>I just tried building Python 2.2 on HP-UX and had no problems; here's >>my build script: >> >>--------------------------------------------------------------------- >>#! /usr/bin/sh >> >>unset LANG >>export CCOPTS='+z' >> >>make distclean >> >>CC=cc ./configure --without-gcc --without-cxx \ >> --prefix=/opt/python && make >>--------------------------------------------------------------------- >> >>HTH >> >>-- >>Michael Piotrowski, M.A. >>-- >>http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fperez528 at yahoo.com Wed Mar 27 01:33:10 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 26 Mar 2002 23:33:10 -0700 Subject: reduce vs. for loop References: <8Rco8.1017$0b.176940@news1.west.cox.net> Message-ID: Tim Hochberg wrote: > Try this out! For n=100, it's only twice as fast, but try it for n=1000, or > n=2000 and it really shines.... (I think it even gives the right answer, > which is a plus.) Well, In [22]: def fact4(n): ....: from sys import maxint ....: mult = 1 ....: result = 1L ....: subresult = 1 ....: max_sub_result = maxint / n ....: for mult in range(n+1): ....: subresult *= mult ....: if subresult > max_sub_result: ....: result *= subresult ....: subresult = 1 ....: return result * subresult ....: In [23]: fact4 10 -------> fact4 (10) Out[23]: 0L That doesn't look right to me. It's hard to say what the op was after, but in general when you need large n factorials it's rare to truly need exact results. If you can live with an approximate answer (good to 10 sig figs or so), then a constant-time solution is vastly preferrable. Note that this is far from optimal, it's a 3 minute port of the standard routine from NumRecipes. But it will do in a pinch: from Numeric import * #----------------------------------------------------------------------------- def gammln(x): """Return the natural log of gamma(x)""" cof = array([76.18009172947146,-86.50532032941677, 24.01409824083091,-1.231739572450155, 0.1208650973866179e-2,-0.5395239384953e-5],Float) y = arange(x+1,x+7,typecode = Float) tmp = x+5.5 tmp -= (x+0.5)*log(tmp) ser = 1.000000000190015 + sum(cof/y) return -tmp+log(2.5066282746310005*ser/x) def fact5(n): return long(round(exp(gammln(n+1)))) #----------------------------------------------------------------------------- This solution obviously has two limitations: - not exact, but quite good. Look at a numerical comparison with an exact (but super-slow) solution: def fact6(n): return reduce(operator.mul, range(1,n+1), 1L ) In [27]: fact5 50 -------> fact5 (50) Out[27]: 30414093203509286326338827883471693198716826006464232959556714496L In [28]: fact6 50 -------> fact6 (50) Out[28]: 30414093201713378043612608166064768844377641568960512000000000000L In [29]: 1.0*(_28-_27)/_27 # force float div Out[29]: -5.9048555901676581e-11 So that's pretty good numerically. - can't go outside the float range. In most 'typical' cases, neither of these is a problem (since you can write most large n problems in terms of logs anyway, which is numerically much saner). Cheers, f. From gimbo at ftech.net Mon Mar 11 10:40:40 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 11 Mar 2002 15:40:40 +0000 Subject: Is Python an object based programming langauge? In-Reply-To: References: Message-ID: <20020311154040.GC12733@andy.tynant.ftech.net> On Mon, Mar 11, 2002 at 07:31:55AM -0800, Graz Bukanoff wrote: > Is Python an object based programming langauge? Short answer: Yes Medium answer: What do you mean? But the answer's yes. Long answer: http://www.python.org/doc/Intros.html -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From tim_one at email.msn.com Fri Mar 1 13:18:33 2002 From: tim_one at email.msn.com (Tim Peters) Date: Fri, 1 Mar 2002 13:18:33 -0500 Subject: Does python have a function like similar_text in PHP In-Reply-To: <61ff32e3.0203010850.3aedc22f@posting.google.com> Message-ID: [ron nixon] > Does anyone know if Python has a function like similar_text in PHP. It > compares two strings and returns a percentage for the match. The .ratio() method of SequenceMatcher objects looks like a similar gimmick, returning a "similarity score" as a float in [0, 1]: http://www.python.org/doc/current/lib/sequence-matcher.html From david at dataovation.com Sat Mar 9 17:59:08 2002 From: david at dataovation.com (David McInnis) Date: Sat, 9 Mar 2002 14:59:08 -0800 Subject: httplib question In-Reply-To: Message-ID: <00c101c1c7be$058e73a0$9865fea9@bigdaddy> I am on a Win2k machine (I have access to a linux box too). Where can I learn how to activate the SSL Support at compile time? I did not see this option when I installed (I used the windows installer). Thanks, David McInnis -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Martin v. Loewis Sent: Saturday, March 09, 2002 2:18 PM To: python-list at python.org Subject: Re: httplib question "David McInnis" writes: > I need to write a small client that can access https (SSL) page? Is > this possible with httplib under 2.1? It is possible, but you need SSL support in your socket module. Whether your socket module provides SSL support depends on the platform you are using, and whether SSL support was activated at compile time. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list From bokr at oz.net Mon Mar 18 17:21:18 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Mar 2002 22:21:18 GMT Subject: Help Required References: Message-ID: On 18 Mar 2002 09:55:18 -0800, surajsub at netscape.net (Surajsub) wrote: >Chris Liechti wrote in message news:... >> surajsub at netscape.net (Surajsub) wrote in >> news:cf4a8ef1.0203151724.440b67ac at posting.google.com: >> > Hi, >> > I am a newbie to Python and am pretty fascinated by it power and >> > speed. >> >> Welcome >> >> >I am however puzzled in trying to write this script. >> > The script builds a list of userids to be fed to ldap and it is >> > supposed to be >> > >> > uid1,uid2,uid3....and so on.( Notice there is no space) >> > >> > However when i am trying to create the uid list it gives >> > >> > uid1, uid2, uid3,...and so on. >> > how do i get rid of this leading space if u would call it.. >> > string.lstrip does not work either. >> >> i don't see what you're doing. please post some example code alomg >> with such questions. however some guesses: >> >> if you have a list of numbers: n = [1,2,3,4] >> you can make string of it using: ','.join(map(str,n)) >> >> or are you parsing the numbers from a string? then you could try: >> >>> import string >> >>> n = map(string.strip, '1, 2, 3, 4'.split(',')) >> >> and if want numbers instead of strings in the list: >> >>> n = map(int, '1, 2, 3, 4'.split(',')) >> >> (*) "map" is simply calling the 1st argument (a function) with each >> element of the list 2nd arg and saves the result in a list which it >> returns. >> you can achieve the same with a "for" loop over the list and saving >> the result in an other list, but i find the "map" is very elegant. >> >> chris > >Ok here is the code..I just need a set of uid's and other similar >parameters which i need to feed to ldap.these are just a dummy set of >values. >============================================================= >#!/usr/local/bin/python >import string > >MIN=0 >MAX=25 >UID="UID" >val="" There is no need to bind val to "" here. You are not reserving space for a value when you do this in Python. Python takes care of space for you. val="" just tells Python to make a linkage between the name val and the constant "" so you can use val later to look up the value you bound it to. >for x in range(MIN,MAX,1): In this case, your range expression could be written range(MAX) because of the defaults of zero start and one for step. However, since you have defined a symbol for the start value, it should probably be carried through as range(MIN, MAX). > if( x == 0 ): > x=str(x) > val=UID,x+',' > st=string.join(val,"") > st=string.strip(st) That sure is working hard to accomplish (BTW, why the strip?) st = "%s%d," % (UID,x) > print st, > elif(x > 0 ): > x=str(x) > val='UID'+x+',', Why the comma here -----^ ? Just to make the next line necessary? > st=string.replace(string.join(val,""),' ','') I urge you to play more at the command line. Notice: >>> x='0' >>> val='UID'+x+',', >>> val ('UID0,',) now leaving off the comma: >>> val='UID'+x+',' >>> val 'UID0,' which is what you wanted, right? ;-) > print st, >========================================================== > >The output that this script produces is > >UID0, UID1, UID2, UID3, UID4, UID5, UID6, UID7, UID8, UID9, UID10, >UID11, UID12, UID13, UID14, UID15, UID16, UID17, UID18, UID19, UID20, >UID21, UID22, UID23, UID24, > > >Notice the spaces between the , and the UID >============================================ >I need to get rid of these spaces.How do i do it.. > >Thanks The spaces come from the print statements, not the data. The solution is a lot easier than your code ;-) For an explanation of print, please read http://www.python.org/doc/ref/print.html Print prefixes a space in front of its output unless it is at the beginning of a line, or some special condition applies (like something else having written to stdout). Most of the time, this works out fine, but when it doesn't there are several ways to do what you want. 1) Join your output into a line before printing, e.g., using your parameters: >>> MIN=0 >>> MAX=25 >>> UID="UID" >>> print ','.join([UID+str(i) for i in xrange(MIN,MAX)]) UID0,UID1,UID2,UID3,UID4,UID5,UID6,UID7,UID8,UID9,UID10,UID11,UID12,UID13,UID14,UID15,UID1 6,UID17,UID18,UID19,UID20,UID21,UID22,UID23,UID24 (The output is a single line that wrapped). 2) You could make yourself a printf function that works very much like C, with no automatic spaces or newlines (leaving out return value for less interactive confusion): def printf(fmt, *args): import sys sys.stdout.write(fmt % args) Then you can use it like: >>> for i in xrange(MIN,MAX): ... if i == 0: ... printf('%s%d',UID,i) ... else: ... printf(',%s%d',UID,i) ... UID0,UID1,UID2,UID3,UID4,UID5,UID6,UID7,UID8,UID9,UID10,UID11,UID12,UID13,UID14,UID15,UID1 6,UID17,UID18,UID19,UID20,UID21,UID22,UID23,UID24>>> (Note that the >>> prompt came without a newline before it, so we might want to add a plain print after the for loop is done). 3) We could directly manipulate sys.stdout.softspace to kill the space prefixing that results from the comma at the end of the print lines: >>> for i in xrange(MIN,MAX): ... if i == 0: ... print '%s%d' % (UID,i), ... else: ... print ',%s%d' % (UID,i), ... sys.stdout.softspace = 0 ... UID0,UID1,UID2,UID3,UID4,UID5,UID6,UID7,UID8,UID9,UID10,UID11,UID12,UID13,UID14,UID15,UID1 6,UID17,UID18,UID19,UID20,UID21,UID22,UID23,UID24>>> I'm not sure softspace was intended to be used that way. You could make the leading comma conditional in the format various ways too, e.g. using printf(): >>> for i in xrange(MIN,MAX): ... printf('%s%s%d', i and ',' or '', UID, i) ... UID0,UID1,UID2,UID3,UID4,UID5,UID6,UID7,UID8,UID9,UID10,UID11,UID12,UID13,UID14,UID15,UID1 6,UID17,UID18,UID19,UID20,UID21,UID22,UID23,UID24>>> (The expression i and ',' or '' results in '' if i==0 and ',' otherwise). HTH, Regards, Bengt Richter Why is a de-dented-to-zero line not accepted interactively? Couldn't it postpone execution until a later blank line, and not demand an immediate one, once in the mode of accepting multiple lines? It would be handy for showing an example like the above with a single print at the end. From mwh at python.net Thu Mar 14 12:14:24 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Mar 2002 17:14:24 GMT Subject: Conditional Import References: Message-ID: Danil writes: > Is there a standard python idiom for coping with importing one of several > libraries? > > Right now, I've this hack in the middle of my code > > try: > from codeop import CommandCompiler > except: make that except ImportError: > from MockCommandCompiler import CommandCompiler > > But if I have to put up with a work around like this, I'd prefer that it > be fairly elegant. Or at least standard... try:...except ImportError:... is standard. > p.s. because codeop.CommandCompiler fails in 2.1, I know, I wrote it for 2.2... do the workarounds mentioned in the docs: http://www.python.org/doc/current/lib/module-codeop.html help? > and I've yet to find a recipe that will get me to Win32 + Python 2.2 > + pygtk. That help would be appreciated too; I've been unable to > find or build a _gtk.pyd that python22 will import. Can't help you here. Cheers, M. -- (ps: don't feed the lawyers: they just lose their fear of humans) -- Peter Wood, comp.lang.lisp From martin at v.loewis.de Tue Mar 26 18:49:19 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Mar 2002 00:49:19 +0100 Subject: is'nt Tkinter a standard module? References: Message-ID: Rajarshi Guha writes: > Is'nt the Tkinter module supposed to be a standard part of Python? Yes, but it may be that your Linux distributor has chosen to put Tkinter in a separate package, so that Python, in itself, does not need to depend on Tk. Regards, Martin From sag at hydrosphere.com Thu Mar 7 17:45:17 2002 From: sag at hydrosphere.com (Sue Giller) Date: Thu, 7 Mar 2002 15:45:17 -0700 Subject: Problem with VB-COM-Python arg passing/value returning Message-ID: <20020307224100390.AAA134@mail.climatedata.com@SUEW2000> I am hoping that someone here can help me with the following problem. I have an application that uses a VB 6 front end and python backend. The VB app creates some python COM objects and calls those objects to get python to do the work. The VB just displays results, etc. This is on W2000, SP2, python is '2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)]' In one case, I am passing a VB class object to the python COM object. This contains a set of complicated configuration settings for a python object to use when it does its thing. In that VB class object, there are some functions that allow python to obtain data stored in that class object. If the function in the VB class does not have any input args, then the return from that function to python is correct. However, if the VB class does have input args, then the values of those args are appended to the end of the return values. If I change the value of the input args, that changed value is reflected in the returned data. If I use 'Byval' for the arg, I get a python error "List() args must be a sequence" Can anyone explain what is going on here? Is this a bug? Can I assume that I can discard the trailing items in ALL cases where I pass an arg(s) to such a function? VB pseudo code, python pseudo code, very simplified VBclass 'class with function being used public property get NeedsArg(arg1) as variant NeedsArg = 1 ' should return a single item end property ' all type returns have the problem public property get NoArgs() as variant NoArgs = 1 end property public property get ByValArg(byval arg1) as variant ByValArg = 1 end property 'create the python com object that uses the vb class pythonObject = CreateObject("python.comthing") 'create the class instance to be passed vbObject = new VBClass 'pass object to python pythonObject.UseMe(vbObject) python class # python class set up as COM _public_methods_ = [ 'UseMe' ] _reg_progid_ = "python.comthing" _reg_clsid_ = blah blah blah def UseMe(vbObject): idobj = win32com.client.Dispatch(vbObject) info = idobj.NeedsArg("abc") print `info` # prints out (1,'abc') info = idobj.NoArgs() print `info` # prints out (1) as it should info = idobj.ByValArg("abc") # raises python error: #Type Error: list () argument must be a sequence print `info` From watercoolerwar at netscape.net Tue Mar 19 01:45:13 2002 From: watercoolerwar at netscape.net (Alex K. Angelopoulos) Date: Tue, 19 Mar 2002 01:45:13 -0500 Subject: modifications of PythonWin? Message-ID: Per Murphy's law, I will stumble across this 30 seconds after I post. I'm looking for information on the PythonWin IDE - specifically, any modifications or customizations that may have been done to it in the past. I have found the sources to it, of course, as well as the basic documentation on it - which seems to be very well done, but is a bit dense for someone who is "MSVC-impaired" such as myself. I'm grinding through it right now, but I think I would do a bit better if I could see some "hacks" that have been done to it... Is anyone aware of open modifications made to the PythonWin environment for special purposes - hopefully with links or a couple of search terms I can use to find such mods? I've come up with nothing but the "real" PythonWin using PythonWin as a search term. From tchur at optushome.com.au Sun Mar 17 03:48:23 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 17 Mar 2002 19:48:23 +1100 Subject: Relieved but disappointed: The Pariah thread Message-ID: <3C945857.64A9F2D8@optushome.com.au> While I was much relieved that Mark Hammond took my mischievous "Has Mark Hammond attained pariah status yet?" post with the good humour for which that noble, heterogenous breed of people known as Aussies are justly renowned, I was a bit disappointed that no-one at all commented on the pictorial reference which I gave to sum up my view of the .NETification of Python: http://www.sciam.com/2002/0102issue/010250100.html OK, I know that the etymology of the name Python is non-herpetic, but that historic photograph may nevertheless be a valuable shorthand for expressing one's views on, for instance, a PEP which proposes yet another syntactic addition... Tim C PS The newspaper article which prompted the post featured a picture of Mark, and not only is his name remarkably similar to that of a famous Australian National Park ranger, he even looks like a younger version of Ed Devereaux...and his email address is mhammond at skippinet.com.au ...hmmm. TC From syver-en+usenet at online.no Wed Mar 13 08:43:01 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Wed, 13 Mar 2002 13:43:01 GMT Subject: module import in cgi scripts References: Message-ID: Have you checked the sys.path from within the running cgi script? It's just a hunch but the cgi process might run under an account that doesn't have the sys.path that you require, No? -- Vennlig hilsen Syver Enstad From claird at starbase.neosoft.com Fri Mar 22 09:41:14 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 22 Mar 2002 08:41:14 -0600 Subject: multithreading and Tkinter References: Message-ID: In article , Laura Creighton wrote: >> Greetings: >> How do I signal the GUI thread that new information for a particular >> object has arrived? Currently I'm using after() method of the Tkinter >> object to update info for *all* objects every second, but that is >> hardly a good design, since there may be 500 of them, and the new info >> can be arriving once every 15 minutes. >> >> Any ideas and/or pointers to the documentation (preferably online) >> highly appreciated. > >You want to use Queue.Queue() to make yourself a nice incoming >queue, and fill it with the data that arrived and the object(s) that >care(s) about it. You'll still use after, but you will only update >the objects that care, and only when something has arrived. See >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 > >Laura Creighton > Excellent advice from both Laura and Aahz. There's been very casual chatter among Tk insiders about (in Tkinter-speak) making update a method of individual widgets. It definitely doesn't exist now, it appears to require guru-level concentration, and we're still not sure it's even feasible in some appropriate sense; however, I think it's worth alerting readers of this thread that there's a possibility of an interesting enhancement in the indefinite future. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jason at jorendorff.com Mon Mar 4 01:06:26 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 4 Mar 2002 00:06:26 -0600 Subject: mx odbc result strings with special characters? In-Reply-To: <24c39b2c.0203032114.3df9e523@posting.google.com> Message-ID: > Hmm, ok, can you tell me how I can convert such a string back to the > ISO8859-1 character set so that I can write it to a text file? It appears that it already *is* in the right character set. Unfortunately, you seem to be converting it to a different representation sometimes, quite unintentionally, when you output it. Try this and see how it works. import mx.ODBC.Windows as odbc outfile = open("myfile.txt", 'w') con = odbc.connect(...) c = con.cursor() c.execute(...) record = c.fetchone() # record is a tuple my_string = c[1] print my_string # print the string, not the tuple outfile.write(my_string + '\n') # write the string, not the tuple c.close() con.close() outfile.close() > The strange thing is, that when I read umlauts from a textfile and > print them to standard out, they remain intact. Only when they come > from the database driver are they converted to this hex > representation. It's not the database or mxODBC that's doing it. The "hex representation" is just Python source code. Nothing too weird about it; that's how Python programmers put strings into programs. Suppose you type this. >>> x = '123\n\txyz\n' Now in memory there's a string that has 9 characters in it, not 12. Your '\n' has been converted to a single byte, with the value 10 (a newline character). The '\t' has been converted to a single byte with the value 9 (a tab character). >>> print len(x) 9 >>> print ord(x[3]) # the value of the '\n' character 10 >>> print ord(x[4]) # the value of the '\t' character 9 Now, suppose we print this string two different ways. >>> print x 123 xyz >>> print repr(x) '123\n\txyz\n' See the difference? When you do "print x", Python dumps those characters to your console. The newline characters, which you entered as '\n', are now displayed as line breaks, and the tab character, which you entered as '\t', is displayed as an indentation. Likewise, depending on your console, the character you could enter as '\xd6' might be displayed as a Latin capital letter O with diaeresis (aka umlaut). When you do "print repr(x)", Python converts x *back* into Python-source-code form and displays the result. Which of these is the true internal representation of x? Neither. The internal representation is 9 bytes of data-- a bunch of numbers, really, not characters or pixels or source code. When you print a tuple, it tries to display itself in Python-source-code format. This means, basically, calling repr() on its contents. Not what you want. In order to display a string usefully, you must print the string itself, not the tuple that contains it. Sorry to write at such length... :( ## Jason Orendorff http://www.jorendorff.com/ From sjones16 at rochester.rr.com Sat Mar 2 20:09:53 2002 From: sjones16 at rochester.rr.com (Seth Jones) Date: Sun, 03 Mar 2002 01:09:53 GMT Subject: (Hopefully) simple IDLE question References: <11aed8f9.0203020225.4d8b7922@posting.google.com> Message-ID: > IDLEfork should handle the working directory correctly. > > See http://idlefork.sourceforge.net/ Thanks; that's exactly what I needed. Now if Idle just had vim integration, I'd be in coding heaven. (c: Keith. From peter at engcorp.com Mon Mar 4 19:08:46 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Mar 2002 19:08:46 -0500 Subject: Deitel and Deitel Book... References: Message-ID: <3C840C8E.3FD1DF3D@engcorp.com> Dennis Roark wrote: > > First books in C++ are mostly a dissappointing lot, surprisingly so. > The Lippman and Lajoie and books by Bruce Eckel are good for students > who have some familiarity with programming. I've used the Savitch and > Main and Savitch books, and a host of others searching for the "perfect > book". I've considered D&D, but I could never stomach its approach (not > truly object oriented from the ground up) and conceptual errors or > weaknesses (some mentioned in this thread). There will probably be many > grumbles with this suggestion, but the best I have found for the first > introduction is Lafore, Object Oriented Programming in C++. But I am > really interested in weaving Python into the CS courses including the > first year courses. I am taking tentative steps in that direction this > year and next. It was mentioned here in the past that Prof. Stefan Kremer at University of Guelph (uoguelph.ca) was actively teaching Python to first-year students in CS. Perhaps if you contact him you could gain the benefit of his experience. (I don't think he reads this group.) -Peter From wall at adinet.com.uy Fri Mar 22 23:45:22 2002 From: wall at adinet.com.uy (Walter Moreira) Date: Sat, 23 Mar 2002 01:45:22 -0300 Subject: ht2html project at SourceForge In-Reply-To: <15515.36115.281626.923961@anthem.wooz.org>; from barry@zope.com on Fri, Mar 22, 2002 at 02:59:15PM -0500 References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: <20020323014522.C7591@casa.parque> On Fri, Mar 22, 2002 at 02:59:15PM -0500, Barry A. Warsaw wrote: > > To maintain www.python.org, we use a web page templating system called > `ht2html', which transforms .ht template files into .html files. Why not Zope, and Page Templates? Walter From robin at jessikat.fsnet.co.uk Sat Mar 23 08:28:20 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 23 Mar 2002 13:28:20 +0000 Subject: New SIG on logic/CLP programming in Python References: <59667b81.0203221433.261c8210@posting.google.com> Message-ID: In article , Peter Norvig writes >I have some simple, inefficient CSP code in Python at >http://www.norvig.com/python/csp.html > >Includes fintie domain backtracking search (with optional forward >checking, domain ordering, and variable ordering); hill-climbing >min-conflicts search; examples from map coloring, n-queens, and the >zebra puzzle. > >-Peter > OK I searched and found the search.py and utils.py files at http://www.norvig.com/python does the use of generators imply that I need Python 2.2? -- Robin Becker From morton at dennisinter.com Mon Mar 11 00:28:55 2002 From: morton at dennisinter.com (damien morton) Date: 10 Mar 2002 21:28:55 -0800 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> <4abd9ce7.0203101059.444f1ec1@posting.google.com> <3C8BBFD4.A29A69F1@engcorp.com> Message-ID: <4abd9ce7.0203102128.67c7fa0d@posting.google.com> Peter Hansen wrote in message news:<3C8BBFD4.A29A69F1 at engcorp.com>... > damien morton wrote: > > > > Check this out: > > > > ('fox' in 'the quick brown fox') > > ('the quick brown fox'.find('fox') != -1) > > > > Which of these expressions is clearer, more intuitive and convenient? > (Put another way, this question is a matter of opinion, and I'm > afraid yours is outweighed by the mass of existing Python code > and programmers. Nothing personal, but don't waste your time.) The existing mass of python code would be unchanged. The only issue that might occur is that something that is now an error, would not be. It remains to be seen whether or not the mass of python programmers are opposed. No-one has taken me up on my question about what circumstances one would want "'fox' in 'the quick brown fox'" to throw an exception, rather than return a result. [On a tangent... we now have proposals for a boolean type to be added to Python, does this presage the addition of a char type also?] From jgardn at alumni.washington.edu Sat Mar 16 01:29:19 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Sat, 16 Mar 2002 15:29:19 +0900 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> Message-ID: I'm going to restate the problem because I don't think I was very clear in the first place. (I'm not being rude, I just don't think that it was very well put now that I read it again.) My problem is: I don't have a windows box. I can't afford a windows box. I can't even afford a Big Mac right now. I don't have access to a windows box. This is because I am a jobless programmer who is looking for work, writing free software in the meantime. (And it looks like more and more I am going to have to find a job in the local grocery store). I run a free software project that is trying to keep things compatible with Windows and Linux. So that means I am in *deep trouble* because I can't test windows directly. BUT! I do have a few guys who run windows and do try stuff out very actively. Unfortunately, they can't code well enough to do this themselves. My question is twofold: 1) Where do I go to find a neat free software (READ: No problems with GPL) windows installer (that works on all windows platforms)? I could work through this on the Linux box and then have the guys on windows try stuff out realtime for me. 2) Can someone on this list help me (by writing the installer for me?) [Note: this is a plea for help out of desperation]. Gerhard H?ring wrote: > Peter Hansen wrote in comp.lang.python: >> Jonathan Gardner wrote: >>> >>> I have a free software program (http://sf.net/projects/bttotalcontrol/) >>> and I am having great difficulty writing an installation script for >>> windows. >>> ... >>> I am at a major disadvantage because I don't have access to a windows >>> machine, and so I can't test anything directly. However, I do have a few >>> people who actively test for the project at home. >>> ... >> >> Why not find and use one of the several free installer programs, rather >> than trying to write something from scratch yourself? >> Great idea. I'll do that. >> For example, try looking at google with "free windows installers" and >> follow the first link you find. To... http://www.wxwindows.org/technote/install.htm ? =) I did try looking on google, and it looks like I have a choice between: a) Windows Installer b) WISE None of which seem to be free. I remember a long time ago that there was a popular installer offering a free version for free software. Was I just seeing things or was that so? > > NSIS rocks. But AFAIR his problem is that he doesn't have a Windows > box to build the installer on. > What is NSIS? > The best solution to this problem is to give in and get a damn Windows > box. Even a virtual one with VMWare or Bochs will do. AFAIK Bochs can > run at least Windows 95 and it even runs on non-x86 hardware. > Bochs sounds cool, but I don't own a copy of Windows, nor do I plan on pirating a copy. However, in the meantime, I will dig around for an old Win 95/98 disks that I can take from somebody who doesn't use it anymore (as this is perfectly legal). Thanks for the suggestion. Jonathan From akuchlin at crystal.mems-exchange.org Mon Mar 25 09:01:19 2002 From: akuchlin at crystal.mems-exchange.org (A.M. Kuchling) Date: 25 Mar 2002 14:01:19 GMT Subject: PEP262 - database of installed packages References: Message-ID: In article , Thomas Heller wrote: > + THE (= Thomas Heller) thinks the first option. IMO a home > + page for the user is much more useful until we get something > + like to CPAN. Source distributions are platform and version OK. It should be really easy to have two URLs, anyway, one for the home page and another for the latest package or a package description file of some sort. > + THE: IMO typically a few dozen packages are installed, so we > + probably have less than, say, one hundred files in the 'database', > + which should reside in a single directory. Also it is not very Agreed, though I think a few hundred packages is certainly possible. Another thing has made it clear to me that invidual files are the right way to go: installers such as RPM or DPKG. They can just drop the new database file into the database directory. If one large text file or a binary file were used, the Python database would then have to be updated by running a postinstall script. > + THE comments: The uninstall 'database' (which is a simple text > + file) which bdist_wininst installers create, contain entries > + for *every* file to be removed, this includes .pyc and .pyo > + files. On the other hand, MD5 digests or CRC checksums are > + probably not so useful for .pyc/.pyo files. Hmm... I suppose it could simply ignore checksums on .pyc/.pyo files, so we don't need a type field to tell us when to ignore them. I can't think of any other generated files that don't need to be checksummed. > * XXX do we need to store permissions? The owner/group? > + THE: no, not on windows. Really? Even on Windows, couldn't files be potentially owned by Administrator or some other user. We should definitely have permissions and owner/group on Unix; can you tell me what Windows needs here? (I assume MacOS X would be the same as Unix, and earlier MacOS versions aren't multi-user, so they don't need anything.) > * The file's full path, as installed on the system. (XXX > should it be relative to sys.prefix, or sys.prefix + > '/lib/python?' If so, full paths are still needed; > consider a package that installs a startup script such as > /etc/init.d/zope) > + THE: Only full paths should be in the database file. I had the vague idea that relative paths might make it easier to relocate packages. On the other hand, maybe that's not something we want to encourage... > * XXX some sort of type indicator, to indicate whether this is > a Python module, binary module, documentation file, config > file? Do we need this? > + THE: No, we don't need this. There is no mechanism (now) how > + this could be specified, also I cannot think of a use case > + where it would be needed. Neither could I. :) I'll remove this, unless someone can suggest a use for it. > + THE: Maybe I don't understand what you are talking about here. I > + have absolutely no idea how RPM or DPKG is working, so I'm only > + talking about bdist_wininst or maybe other windows installers > + here. win32all and wxPython are examples of very popular packages I was wondering whether an RPM package should bother to update the Python database, as RPM provides much the same functionality; if you already have one database, why maintain two? But you're right; updating the database shouldn't be optional, and therefore RPM will have to update it. Luckily that will be easy to packagers to support, because of the one-file-per-package database. --amk (www.amk.ca) This supports reflection, which is the 90s way of writing self- modifying code. -- John Aycock at IPC7, during his parsing talk From phr-n2002a at nightsong.com Mon Mar 4 16:18:30 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 13:18:30 -0800 Subject: Can Python do this? References: <7xvgccm5f5.fsf@ruckus.brouhaha.com> Message-ID: <7xelj0m3q1.fsf@ruckus.brouhaha.com> quinn at barf.ugcs.caltech.edu (Quinn Dunkan) writes: > Really? > ... > >>> a.m > > >>> getattr(a, 'm') > > >>> > > Or did you mean something else? Oops, thanks. Yes, that's what I meant, but my test case had an error. I'm glad getattr works the way I'd hoped/expected it did. From peter at engcorp.com Sun Mar 10 01:44:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 01:44:50 -0500 Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> Message-ID: <3C8B00E2.75783719@engcorp.com> Grant Edwards wrote: > > Hmm, I don't really see the difference in practice between > statically linking and installing a bunch of "private" DLLs > that are only used by my app. Upgrades? If you don't plan to distribute any new versions of your program, or you don't mind redistributing multi-megabyte packages just to fix a small bug, no problem. I couldn't probably think of other reasons (or maybe not). Modularity is generally good. Less good for simple utilities. > >> I don't know diddly about DLLs, so pardon the ignorant > >> question: Can my DLLs be put in a private directory where my > >> EXE can find them? I'd rather not put anything in any public > >> system directories. > > > > Yes, definitely. Not entirely advisable if you're delivering > > more than one program in the same manner, > > Right now I don't exect to. If I did, couldn't I make all of > "my" apps look in the same place for "my" DLLs? I really hate > the idea of my app putting things in "system" directories. Not sure how you would make your app look elsewhere than in the executable's directory for DLLs, if you need to avoid the system directories. Might be possible. Anyone? > AFAICT, there doesn't appear to be a practical way to have > multiple versions of DLLs installed, so if you've got two apps > that require different versions of DLLs, then one of the apps > is screwed. A good reason to use the everything-in-one-folder method and not worry about it. > > And I suppose there's the fact you'd be avoiding much of the > > grief caused by dynamically linked apps and "DLL version hell" > > by doing that, if you can spare the hard drive space (and most > > users probably can these days). > > Windows users... worried about drive space... ROTFL! Who's worried? Not me. I thought you might be, and I didn't want to insult you by saying I thought that would be silly. If you don't care, then you have little reason not to go with the options suggested. Distributing to Windows users via a single executable is actually worse than via an installer (which would hide the multiple files if it's not statically linked) since (a) they get cute icons in the Start menu, (b) they can uninstall without having to run Explorer and manually delete files, (c) you can split out parts that should be modular (resources such as help files, etc.), and (d) they're used to it and don't know what to do with an executable (depending on the ignorance level of the user). -Peter From skip at pobox.com Thu Mar 14 12:21:20 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 14 Mar 2002 11:21:20 -0600 Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy In-Reply-To: References: Message-ID: <15504.56336.145185.432869@beluga.mojam.com> Magnus> Should I use Server or ServerProxy as the name for the Magnus> ServerProxy class in xmlrpclib? The standard docs use Server, Magnus> while the effbot seems to use ServerProxy, ... When xmlrpclib was originally released, the class that represents a remote XML-RPC server was named "Server". At some point it was decided that calling it "ServerProxy" was more descriptive. I would use ServerProxy for new code. I'll check the docs and make sure they are correct. Note also that the code is class ServerProxy: ... # compatibility Server = ServerProxy and that is the only place "Server" is used in the code or comments. Everywhere else it is referred to as "ServerProxy". -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From BgPorter at NOartlogicSPAM.com Fri Mar 15 10:01:05 2002 From: BgPorter at NOartlogicSPAM.com (Brett g Porter) Date: Fri, 15 Mar 2002 15:01:05 GMT Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> Message-ID: "James T. Dennis" wrote in message news:a6rk1v$oac$1 at news.idiom.com... > Dean Goodmanson wrote: > > One of his examples implements a priority queue by treating a list as a "heap" > (his term); his example takes over 50 lines of code and he doesn't clearly show > sample usage of this class. After awhile I abandonned my pondering of his code > and wrote my own from scratch (as a dictionary of queues with a list of the > keys to sort into priority order). Actually, 'heap' is the correct word (assuming that he's using it in the correct way -- don't have the book in question) and most algorithms texts will implement priority queues in terms of heaps. When inserting single elements into a priority queue, it's (IIRC) the most efficient representation, requiring O(log n) comparisons and exchanges. From les_ander at yahoo.com Sat Mar 30 23:16:21 2002 From: les_ander at yahoo.com (les ander) Date: 30 Mar 2002 20:16:21 -0800 Subject: list subscripting (nested lists) Message-ID: Hi, is it possible to have nested lists indexing in python? i.e. index=[3,1,1] and List1=['a','b','c','d'] then List1[ index ] should print out ['d','b','b'] I think this would be a cool feature to add if not already present. thanks les From peter at engcorp.com Sat Mar 23 11:17:03 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 23 Mar 2002 11:17:03 -0500 Subject: "Zope-certified Python Engineers" [was: Java and Python] References: Message-ID: <3C9CAA7F.9B2B0D2F@engcorp.com> Martijn Faassen wrote: > > Rest assured the Python Secret Underground is working on all of this. [...] > and Fnord therefore Fnord the PSU is in an excellent Fnord position not just > to diminish Erisian propaganda, but to completely eliminate it shortly. Damn! They've managed to build the autocoder! We're doomed! :-( From greg at cosc.canterbury.ac.nz Mon Mar 4 23:13:48 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 05 Mar 2002 17:13:48 +1300 Subject: Status of PEP's? References: Message-ID: <3C8445FC.A1816810@cosc.canterbury.ac.nz> James_Althoff at i2.com wrote: > > [David Eppstein] > > > > "for" expression ":" > > You might want to think this through a bit more since neither arbitrary > "expression" nor arbitrary "conditional" is supported in the suggestions > posted so far. The official Python grammar currently defines a for-loop thusly: for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] where 'exprlist' is, confusingly, *not* a list of general expressions, but of expressions not including comparisons. So it seems that the following would work: for_stmt: 'for' (exprlist 'in' testlist | exprlist lt_op exprlist lt_op exprlist | exprlist gt_op exprlist gt_op exprlist) ':' suite ['else' ':' suite] lt_op: '<' | '<=' gt_op: '>' | '>=' Later phases of the compiler would be responsible for checking that the exprlists in the new parts actually contain only one item each, and that the middle one is a variable. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From James_Althoff at i2.com Mon Mar 11 18:48:32 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 11 Mar 2002 15:48:32 -0800 Subject: PEP 284, Integer for-loops Message-ID: (Please excuse the top-posting). I did notice the wink. I should have acknowledged it. Sorry. I just thought it might be useful to show an application domain in which using indices seems pretty natural. I like all the points you make below. Sorry for the confusion. Jim ================================ > [Tim Legant] > > So either Jason and I are significantly better than you and your > > team at expressing ourselves naturally in Python or it's > > the need to interface with Java that's forcing you to use integer > > indices all the time. I'm betting big money on the latter. > > I'm happy to believe you all are excellent programmers versed in Pythonic > ways. And I'm always happy to learn something new. So feel free to help > me on this one. Hmmm. Did you by any chance miss my ? My intent was to provide a supporting data point to your hypothesis that the real issue is interfacing with Java. With Python as it exists today, I am unaware of any good solutions. [snip description of nasty problem...] > Perhaps you could give some ideas on approaches that would be more > "Pythonic"? Well, like I was trying to convey in my original message, I think you're stuck. Tim Peters actually came up with something a little better, but I still think it's sad you have to write all kinds of wrappers just to get a reasonable looping syntax. FWIW, I completely agree that [x]range is awkward and inelegant (and necessary) in these sorts of cases. I'm also in full agreement with better language support for more complex loops. I haven't been really happy with either of the PEPs, but I sure understand the problem they're trying to address. From djc at object-craft.com.au Sat Mar 23 23:33:56 2002 From: djc at object-craft.com.au (Dave Cole) Date: 24 Mar 2002 15:33:56 +1100 Subject: MS Sql Server References: <788n8.60257$bj1.19179906@news02.optonline.net> Message-ID: >>>>> "Tim" == Tim Churches writes: Tim> Chase wrote: >> Wondering what the most accepted practice is, for communicating to >> Sql Server Databases. Is it the ODBC module ? mxODBC ? Is there an >> ADO module ? Tim> You can use the mxODBC module but Object Craft have a Python Tim> interface which is specific to MS SQL Server and Sybase - see Tim> http://www.object-craft.com.au - but you may want to check with Tim> its developer, Dave Cole, as to its suitability for production Tim> systems. Some people have reported success in using it. Getting feedback of any kind for free software is as difficult as pushing butter into a fishes arse with a hot needle. Sorry, couldn't help myself. - Dave -- http://www.object-craft.com.au From alans at killergame.com Fri Mar 22 12:32:49 2002 From: alans at killergame.com (alan scales) Date: 22 Mar 2002 09:32:49 -0800 Subject: python/wxPython opengl question Message-ID: i have a python app (using wxPython). from it i create a top level window (frame) using python opengl. this works: i have my app running, and alongside it the gl graphics window. however, when i close the opengl window, it closes my wxPython app (and the python console) - i.e. everything. i don't want this behavior. is there any way to prevent it? for the gl window i am just making a standard glutCreateWindow(title)call. alan scales From laytonjb at bellsouth.net Wed Mar 6 19:34:29 2002 From: laytonjb at bellsouth.net (Jeff Layton) Date: Wed, 06 Mar 2002 19:34:29 -0500 Subject: Newbie Python+XML Question References: Message-ID: <3C86B595.3F2A0EF5@bellsouth.net> Brian Quinlan wrote: > Jeff wrote: > > % python2.1 testg.py > > Traceback (most recent call last): > > File "testg.py", line 26, in ? > > class XmlHandler(saxutils.DefultHandler): > > AttributeError: 'xml.sax.saxutils' module has no attribute > 'DefultHandler' > > > > It looks like the SAX stuff is not getting imported correctly. > > Does anyone feel like helping a lowly Newbie with this one? > > Easy one: you spelled "Default" incorrectly. Change 'DefultHandler' to > 'DefaultHandler' everywhere in that script. OK, got that one fixes :) I still get an error message: [laytonj at home2 GANGLIA]$ python2.1 testg.py Traceback (most recent call last): File "testg.py", line 26, in ? class XmlHandler(saxutils.DefaultHandler): AttributeError: 'xml.sax.saxutils' module has no attribute 'DefaultHandler' Just for completness, here's the top part of the code: # import socket import getopt import string import xml.sax #import xml.sax.saxutils from xml.sax import saxutils import sys class XmlHandler(saxutils.DefaultHandler): def __init__(self, argv, machines=[]): saxutils.DefultHandler.__init__(self) self.info = {} self.hostname = '' self.max_hostname_len = 0 self.metrics = {} self.machines = machines Any thoughts? Ideas? Thanks! Jeff > > > Cheers, > Brian From fperez528 at yahoo.com Wed Mar 27 01:08:52 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 26 Mar 2002 23:08:52 -0700 Subject: Looking for a python shell under linux like PythonWin References: Message-ID: newgene wrote: > Hi, group, > The only python shell under linux I can find is IDLE, but it is > not as good as PythonWin. A important feature "Attribute expansion"(a > list of attributes for selection when pressing period after a module > name) is not available. Is there a good python shell existing on linux > now? > > Thanks. > > Newgene You may want to check out: http://www-hep.colorado.edu/~fperez/ipython/ It's classical command line stuff (no syntax highlighting) but has many features for convenient use, including TAB based expansion for keywords, attributes and filenames in the current dir. cheers, f From gerhard at bigfoot.de Fri Mar 15 08:27:55 2002 From: gerhard at bigfoot.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 15 Mar 2002 14:27:55 +0100 Subject: line-by-line file read References: Message-ID: <3C91F6DB.9040001@bigfoot.de> Michael Stenner wrote: > OK, so the wonderful flow of the "warty range" thread inspired me to > ask the following style question: > > I often find myself reading and processing a file line-by-line. The > way I usually end up doing it goes something like this > [...] > Anyway... just wondering if there's a preferred way to do this. Python 2.2 and later: for line in open("bla"): # do something with line Pre-2.2 Python: for line in open("bla").xreadlines(): # do something with line Gerhard From dsavitsk at e-coli.net Fri Mar 22 16:32:49 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 22 Mar 2002 21:32:49 GMT Subject: CGI, etc. References: Message-ID: <5qNm8.779$d7.243355@newssrv26.news.prodigy.com> "Bertrand Geston" wrote in message news:a7fiko$l2o7i$1 at ID-135695.news.dfncis.de... > "Gerhard H?ring" wrote in message > news:slrna9m09g.1ic.gerhard at koesesoy.opus-gmbh.net... > > In article , dsavitsk > wrote: > > > "Sheila King" wrote in message > > >> http://www.python.org/topics/web/ > > > > > > btw, the instructions linked to here for doing CGI on windows under iis > are > > > out of date (only covering 9*/NT). For win2k (server and professional) > see > > > http://www.e-coli.net/mag.shtml (or http://www.e-coli.net/pyiis.html and > > > http://www.e-coli.net/pyiis_server.html specifically) > > > > I'd suggest to inform webmaster at python.org. > > > > Gerhard > > I second this suggestion because, as a newbie not involved in the Python > community (btw really really cool), my first thought after the mail of > "dsavitsk" was "Ah, Ah this Python site is not really up to date" > > Have a nice WE. > This has been added to the FAQ. -d From BPettersen at NAREX.com Thu Mar 21 19:37:55 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 21 Mar 2002 17:37:55 -0700 Subject: Popular style document? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158DB2@admin56.narex.com> > From: Bj?rn Lindberg [mailto:d95-bli.no at spam.nada.kth.se] > > phil hunt wrote: > > > IMO the requirement to say self everywhere in methods is the worst > > feature of python. > > How come Python doesn't have an "automatic" this-variable, > like C++ or Java? Because Python can have nested classes. -- bjorn From gbreed at cix.compulink.co.uk Tue Mar 12 08:48:03 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Tue, 12 Mar 2002 13:48:03 +0000 (UTC) Subject: Has Mark Hammond attained pariah status yet? References: Message-ID: Robin Becker wrote: > Another > example of embrace and strangle. Good pythonic behaviour, then. From jgitomer at erols.com Sun Mar 10 01:20:51 2002 From: jgitomer at erols.com (Jerry Gitomer) Date: Sun, 10 Mar 2002 01:20:51 -0500 Subject: import gadfly causes 500 Server Error -- anyone know how to fix? Message-ID: <3C8AFB43.275714BB@erols.com> Hi, I have an application I am porting from Python with Tkinter to Python on the Web. I built my first set of scripts by copying something that worked and then modifying one idea at a time. Everything was fine until I tried to add a query into a gadfly database. I discovered that adding the "import gadfly" statement results in: 500 Server Error The server encountered an internal error and could not complete your request. Anyone have any ideas on why and how to fix? Jerry From eric.brunel at pragmadev.com Mon Mar 4 04:51:37 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 4 Mar 2002 09:51:37 +0000 Subject: The Text Widget References: <5Hzg8.72869$vP.290047@rwcrnsc51.ops.asp.att.net> <3C82E8C4.24531DE7@tds.net> Message-ID: Edward K. Ream wrote: > First, note that if you bind to a key-press () event, when the > event handler is called the Text widget hasn't been changed yet(!) > Other frameworks provide a "text will change" event and a "text did > change" event, but AFAIK Tk does not. Tk does: it's simply that the event "" is a short-cut for "", called when the key is depressed, so before the insertion happened. To do a binding after the text has been inserted, the event is "". For Ali's problem, I don't exactly understand what you want to do. When reading your mail, it seems to me that a sub-class of Tkinter.Text with a redefined "insert" method may do the trick. Or is it more complicated? HTH - eric - From logstx at bellatlantic.net Thu Mar 7 19:41:33 2002 From: logstx at bellatlantic.net (logistix) Date: Fri, 08 Mar 2002 00:41:33 GMT Subject: marcos and .pyc References: Message-ID: <1NTh8.7464$J3.6384@nwrddc01.gnilink.net> > Is there a feature in the basic python for doing inline marcos (similar to > the ones found in C and C++)? Also is there a way to specify where .pyc > files are to be deposited? > Python uses the exec statement and eval() functions to generate code instead of macros. It's more powerful. >>> def powerFactory(power): powerString = "def power" + str(power) + "(pw):\n" for i in range(power - 1): powerString += "\tpw *= pw\n" powerString += "\treturn pw\n" print powerString exec powerString in globals() ... >>> powerFactory(1) def power1(pw): return pw >>> powerFactory(2) def power2(pw): pw *= pw return pw >>> powerFactory(3) def power3(pw): pw *= pw pw *= pw return pw >>> power1(2) 2 >>> power2(2) 4 >>> power3(2) 16 From jimd at vega.starshine.org Sun Mar 17 19:28:58 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 18 Mar 2002 00:28:58 GMT Subject: signal handling toy Message-ID: The following dumb script is for playing with Python signal handling under Linux. It does show some minor descrepancies between the names returned by kill -l and the signal.SIG* names. To actually kill this you have to send it an uncatchable signal such as kill -9 (kill -SIGKILL). So make sure to background it or to have another terminal (window, virtual console, whatever) into which you can enter your kill command. #!/usr/bin/env python import signal linuxsigs = { 1: "SIGHUP", 2: "SIGINT", 3: "SIGQUIT", 4: "SIGILL", 5: "SIGTRAP", 6: "SIGABRT", 7: "SIGBUS", 8: "SIGFPE", 9: "SIGKILL", 10: "SIGUSR1", 11: "SIGSEGV", 12: "SIGUSR2", 13: "SIGPIPE", 14: "SIGALRM", 15: "SIGTERM", 17: "SIGCHLD", 18: "SIGCONT", 19: "SIGSTOP", 20: "SIGTSTP", 21: "SIGTTIN", 22: "SIGTTOU", 23: "SIGURG", 24: "SIGXCPU", 25: "SIGXFSZ", 26: "SIGVTALRM", 27: "SIGPROF", 28: "SIGWINCH", 29: "SIGIO", 30: "SIGPWR", 31: "SIGSYS", 32: "SIGRTMIN", 33: "SIGRTMIN+1", 34: "SIGRTMIN+2", 35: "SIGRTMIN+3", 36: "SIGRTMIN+4", 37: "SIGRTMIN+5", 38: "SIGRTMIN+6", 39: "SIGRTMIN+7", 40: "SIGRTMIN+8", 41: "SIGRTMIN+9", 42: "SIGRTMIN+10", 43: "SIGRTMIN+11", 44: "SIGRTMIN+12", 45: "SIGRTMIN+13", 46: "SIGRTMIN+14", 47: "SIGRTMIN+15", 48: "SIGRTMAX-15", 49: "SIGRTMAX-14", 50: "SIGRTMAX-13", 51: "SIGRTMAX-12", 52: "SIGRTMAX-11", 53: "SIGRTMAX-10", 54: "SIGRTMAX-9", 55: "SIGRTMAX-8", 56: "SIGRTMAX-7", 57: "SIGRTMAX-6", 58: "SIGRTMAX-5", 59: "SIGRTMAX-4", 60: "SIGRTMAX-3", 61: "SIGRTMAX-2", 62: "SIGRTMAX-1", 63: "SIGRTMAX" } # Ugly bit of introspection follows: pysignames = filter(lambda x: x[0:3]=="SIG" and x[3]!='_', dir(signal)) pysigs = {} for i in pysignames: pysigs[signal.__dict__[i]] = i del(pysignames) def prsig(sig,sframe): print "%d (%s?: %s) received" % \ (sig,linuxsigs[sig],pysigs.get(sig, "Uknown")) if __name__ == '__main__': for i in linuxsigs.keys(): signal.signal(i, prsig) print "Signal set for: %s (%d %s?)" % (linuxsigs[i], i, pysigs.get(i)) while i: ## Must send "uncatchable" signal to end program? ## Could add sigalarm + time support? signal.pause() From bernie at 3captus.com Wed Mar 13 19:08:34 2002 From: bernie at 3captus.com (Bernard Yue) Date: Thu, 14 Mar 2002 00:08:34 GMT Subject: dictonary References: <3C8F27DC.F69B1F54@stud.cs.uit.no> <3C8F3800.3070002@mxm.dk> Message-ID: <3C8FEA78.C6250F62@3captus.com> Max M wrote: > > Gerhard H?ring wrote: > > >>db = _mysql.connect() > >>string = { > >> hello:'wow', > >> something:'nothing', > >> nothing : 'something', > >> number : 5, > >> name : 'daniel'} > >> > > This is one way to do it, I bet there's a better one: > > > > dict = {'name': 'Andy', 'age': 39} > > > > columns = ",".join(dict.keys()) > > # I hope using only %s works for MySQLdb. It does work like this for pyPgSQL. > > placeholders = ",".join(['%(' + k + ')s' for k in dict.keys()]) > > sql = "insert into table(" + columns + ") values (" + placeholders + ")" > > A bit more readable perhaps? > > keys = dict.keys() > vals = dict.vals() > sql = "insert into table(%s) values (%s)" % ( > ','.join(keys), > ','.join(list(len(keys)*'?')) > ) > cursor.execute(sql, vals) > Will this method cause problem when inserting numbers (strings are quoted, but not for numbers)? I remember it will (not 100% sure, it's been a while). Thats what I've done (with MySQLdb): import MySQLdb as DB _host, _port, _user, _passwd = 'host', 3306, 'me', 'passwd' _insertTemplate = 'INSERT INTO %s (%s) VALUES (%s)' _tableName = 'MyTable' _myData = { hello:'wow', something:'nothing', nothing : 'something', number : 5, name : 'daniel'} _valueTemplate = ('%s, ' * len( _myData))[:-2] _sqlTemplate = _insertTemplate % (_tableName, reduce( lambda x, y: '%s, %s' % (x,y) , _myData.keys()), _valueTemplate) try: _dbconn = DB.connect( host=_host, port=_port, user=_user, passwd=_passwd) _cursor = _dbconn.cursor() _cursor.execute( _sqlTemplate, _myData.values()) _dbconn.commit() except DB.OperationalError, _msg: # connection failed print 'Warning: %s' % _msg except (DB.ProgrammingError, DB.IntegrityError), _msg: # insert failed print 'Warning: insert failed.\n' % _msg print 'sql = %s' % _sqlTemplate print 'data = %s' % _myData.values() else: _cursor.close() Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From cunsan at lycos.com Tue Mar 26 05:46:52 2002 From: cunsan at lycos.com (stclaus_imi) Date: Tue, 26 Mar 2002 10:46:52 -0000 Subject: running python on win2k Message-ID: hi, all of you. i downloaded python for win2k. i wonder how to run it via the command line and over the apache/iis web server. thank you From eppstein at ics.uci.edu Sat Mar 2 11:08:07 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Sat, 02 Mar 2002 08:08:07 -0800 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: In article , "Emile van Sebille" wrote: > "Carel Fellinger" > > You specify that the > > integer to iterate over should be possitive, why not allow for > > negative values and do the sensible thing, like: > > > > >>> [i for i in -3] > > [-1, -2, -3] > > If you change the sensible thing to mean: > > [-3, -2, -1] > > I'd like it better. ;-) But that wouldn't be as useful for iterating backwards through lists. Which is what most of this seems to be directed at, rather than anything to do with integers per se, so I wonder why we are trying to convert integers into lists of indices rather than converting the lists directly. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From mrussell8081 at pacbell.net Mon Mar 18 15:15:54 2002 From: mrussell8081 at pacbell.net (Mark) Date: 18 Mar 2002 12:15:54 -0800 Subject: Problems embedding with win2k Message-ID: <3a7925ca.0203181215.626e8ea3@posting.google.com> I need to embed a python interpreter in C++ applications in both Win2K and Linux environments. I have started to work the embedding examples and have run into problems on the windows side, here is my setup and problem: Environment: Win2K Pro, VC6 SP4 Problem 1?Very High Level Embedding Example: Access violation in msvcrtd in debug mode I work the first example from the Python docs?extending and embedding sec 5.1. When I build this in release mode the application runs fine. When I compile and run in Debug mode I get an access violation in msvcrtd.dll. When the program is run the following two asserts fail: Dbgheap.c line: 1044 _CrtIsValidHeadPointer(pUserData) Dbgheap.c line: 1050 _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) When I look back through the trace, this error occurs when in Py_Initialize() when the site module is being imported. I am using the debug multithreaded dll runtime for debug and the multithreaded dll runtime for release. I am sure I must have a project setting wrong but I can't figure out exactly what. Problem 2?Pure Embedding Example?Access violation in python22.dll When the pure embedding example is built in release mode using the multithreaded dll runtime, I get and access violation. When I try to build and run in debug mode I get the same problem in Py_Initialize() as described in Problem 1. If anyone has seen this problem and can suggest a way forward I would be very grateful. From store_li at sina.com Sun Mar 3 22:09:41 2002 From: store_li at sina.com (Ricky) Date: Mon, 4 Mar 2002 11:09:41 +0800 Subject: How can I use a foreign language char in Swing Message-ID: I installed J2SDK 1.4.0 several days ago. I need to get some strings from database which stored in GB2312 encode method, and display it using Swing. I got correct result in Windows2000(Use China as default region and GB2312 as encode method.) While I??run it on Windows(English Edition), all I can see is ?????. What should I do? I think ResourceBoundle can't help me. Is there any other method can help me? From ffjhenon at club-internet.fr Tue Mar 12 17:43:54 2002 From: ffjhenon at club-internet.fr (Fabien Henon) Date: Tue, 12 Mar 2002 23:43:54 +0100 Subject: Scrolling line number Tkinter Message-ID: <3C8E84AA.4070306@club-internet.fr> I am currently writing a text editor for POV-RAY under Windows using Tkinter. It should be working as well with linux and Mac. To display the line numbers, I use a scrolling column at the left of the editor with a text box. I also linked the main text editor with a scroll. My problem is that the text editor is well linked to the scroll, but the line numbers do not move when I use the arrow cursors. Thanks for any help Fabien -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: 54.py URL: From skip at pobox.com Tue Mar 19 12:01:47 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 19 Mar 2002 11:01:47 -0600 Subject: Extending Python/Tkinter In-Reply-To: References: <5acdbd0c.0203190838.20c3733e@posting.google.com> Message-ID: <15511.28411.274557.350873@12-248-41-177.client.attbi.com> >> I have a C++ class that draws maps that I've been assigned to extend >> into python. The class uses X primitive calls (XDrawPoint, etc.) to >> do much of the work and I'm at a loss on how to integrate this as an >> extension to Python. Perhaps http://python-xlib.sourceforge.net/ would help? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From dave at pythonapocrypha.com Fri Mar 29 12:59:16 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: 29 Mar 2002 09:59:16 -0800 Subject: optional pass? (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26)) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA35C49.31397789@ndh.net> Message-ID: <477762c2.0203290959.3b163108@posting.google.com> philh at comuno.freeserve.co.uk (phil hunt) wrote in message news:... > On Thu, 28 Mar 2002 19:09:13 +0100, Stefan Schwarzer wrote: > >What about > > > >class BaseClass: pass > > > >class MyClass(BaseClass): > > def __init__(self): pass > > def method1(self, a, b, c): pass > > def method2(self, d, e): pass > > def method3(self, f): pass > > > >IMHO, that looks almost as well as your version, and makes the absence > >of additional code seem rather intentional, not accidental. > > True, but i still have to remove the passes when i want to implement > the class. No you don't. They're no-ops. If you are prioritizing on reducing keystrokes, then you should leave them in there. If you are prioritizing on clean, readable code, then you'll happily put them in there (or perhaps better, raise an exception) and happily take them out later. Perhaps a change in perspective would help you: the with-pass versions of functions are not "unimplemented" but "minimally implemented". Your proposal is to make unimplemented code parsable and runnable, which makes no sense. It's like saying that, until you're ready to flesh out the code, you also want to omit the colon and parentheses on the 'def' line but you want Python to not complain about this. If this is really driving you crazy, add a couple of macros to your editor - no point in changing the language over something so trivial. -Dave From krists at ifi.uio.no Wed Mar 20 12:00:21 2002 From: krists at ifi.uio.no (Kristin Skoglund) Date: Wed, 20 Mar 2002 18:00:21 +0100 Subject: Remove empty lines Message-ID: <3C98C025.7741BA58@ifi.uio.no> Hi I am trying to make a script that reads javafiles and remove comments and empty lines. The script looks like this...... def removestuff(file): infilename=file infile=open(infilename, 'r') copyfile=infilename +".bak" newfile=open(copyfile,'w') str = infile.read() str=re.sub(r"/\*\*\n.*\n*\*/|/\*\n.*|\*.*|\s*/\s*"," ",str) #This strips away comments lines=re.split("\n",str) for line in lines: # Here I try to remove the emty lines if line== '': continue elif empty: continue else: tmp.append(line) newfile.write(line) infile.close() newfile.close() ...and everything works except the removal of empty lines. Does anyone knoe whats wrong? Kristin From peter at engcorp.com Sun Mar 31 10:58:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 10:58:18 -0500 Subject: List problem References: Message-ID: <3CA7321A.DF13361A@engcorp.com> Jon Cosby wrote: > > This is strange. I've added some lines to see where this is failing. > You can see below the interpreter is not detecting matches, but they > are there, and it is showing them. There is something in > word[0] == firstword[i] that's not right or the interpreter isn't > understanding. What could possibly be wrong with this? Well, there's certainly nothing wrong with that, so it must be something else's understanding that is wrong... > for word in words: > for i in range(lword): > l.append(word[0] + ":" + firstword[i]) > if word[0] == firstword[i]: > cols[i].append(word) > [...] > C:\Python21>python projects\wordsquare.py > Enter first word (enclosed in quotes): "add" > 502 > [[], [], []] > ['A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', > 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', Are you sure you aren't forgetting case-sensitivity? I still don't really understand your code, but I get a sense from the above that you are expecting "AWORD" to equal "aword", which is not the case (no pun intended). If this is true, try using word[0].upper() == firstword[i].upper(). -Peter From philh at comuno.freeserve.co.uk Thu Mar 28 14:41:32 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 28 Mar 2002 19:41:32 +0000 Subject: optional pass? (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26)) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA35C49.31397789@ndh.net> Message-ID: On Thu, 28 Mar 2002 19:09:13 +0100, Stefan Schwarzer wrote: >What about > >class BaseClass: pass > >class MyClass(BaseClass): > def __init__(self): pass > def method1(self, a, b, c): pass > def method2(self, d, e): pass > def method3(self, f): pass > >IMHO, that looks almost as well as your version, and makes the absence >of additional code seem rather intentional, not accidental. True, but i still have to remove the passes when i want to implement the class. >> And then, when you begin to flesh out your code, you would have to >> get rid of the extraneous passes you didn't want to add (assuming >> you are like me) in the first place. So the with-pass version >> requires more effort, and is more verbose, for no good reason. > >I value the explicitness of pass over having to write or delete a bit >less. With my proposal, you can still use pass if you want to. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From herrn at gmx.net Tue Mar 19 18:55:16 2002 From: herrn at gmx.net (Marco Herrn) Date: Wed, 20 Mar 2002 00:55:16 +0100 Subject: inheriting from curses window-objects In-Reply-To: References: Message-ID: <20020319235516.GA11899@lurkabove.darkstar> On Tue, Mar 19, 2002 at 07:58:23PM +0000, Gerhard H?ring wrote: > Marco Herrn wrote in comp.lang.python: > > Hi, > > > > i would like to create window-objects that are derived from the standard > > curses windows (like window or pad). But I don't see any way to achieve > > this. > > Is this possible? > > No. But there's help: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 That seems not a bad idea. > > Or would I have to write a "new curses library" to get real objects > > for window, one can inherit from? > > Fortunately, that's not needed. If you want to write a patch to make > curses objects subclassable and submit it at Sourceforge, I'm sure it > will be appreciated. By me, at least :-). I am thinking about using tinter. There are some elements like dialog boxes etc. already done as classes. I could inherit from them and create some additional classes like for ordinary windows and so on. I think that would do it quite well. Possibly that is easier than to write everything by myself. Bye Marco -- The more we disagree, the more chance there is that at least one of us is right. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From andymac at bullseye.apana.org.au Fri Mar 15 03:53:10 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 15 Mar 2002 19:53:10 +1100 (EDT) Subject: Tkinter BUG: memory loss for tag bindings in Canvas In-Reply-To: Message-ID: On Thu, 14 Mar 2002, Eric Brunel wrote: > Considering my memory loss problem with tag bindings, I went a little > deeper into the Tkinter module and found out what happened: whenever a > binding is created, a new tcl command is created by the Tkinter/_tkinter > modules. This command in fact just calls the Python function, but is > required to do the binding at the tk level, which of course knowns nothing > about Python. This is this command that cause the memory leak: when the > graphical item is deleted or even when the binding is cancelled, the > command is not destoyed in the tcl interpreter... Can you report this on Sourceforge? (ISTR that an SF account may be required) -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bergeston at yahoo.fr Thu Mar 21 10:53:47 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Thu, 21 Mar 2002 16:53:47 +0100 Subject: eval of a private attribute References: <3C998F89.66DB1290@infomaniak.ch> Message-ID: "Skip Montanaro" wrote in message news:mailman.1016720675.17480.python-list at python.org... > > Cedric> I'd like to create a method which will be able to get any > Cedric> attribute of the class. > > Why use eval? Why not simply > > p = getattr(self.__class__, var) > > ? The first arg restricts you to fetching class variables. You could also > use 'self' there I suppose. > > -- > Skip Montanaro (skip at pobox.com - http://www.mojam.com/) > Yes, this is right with var = '_%s__%s' % (self.__class__.__name__, var) From deathtospam43423 at altavista.com Sat Mar 9 05:06:08 2002 From: deathtospam43423 at altavista.com (A.Newby) Date: 9 Mar 2002 10:06:08 GMT Subject: Q: How can I lock a file in Windows? Message-ID: I am writing a cgi based, html chat script in Python. Basically, it takes input from people's browsers, writes it to a text file, then displays the contents of that file back to everyone. Simple. Problem is I need to be able to lock the text file during the write procedure, so that only one person can write to it at a time. Unfortunately, not having access to a Unix server atm, I'm using Windows. That means I don't have the fcntl module, which means I can't use flock to lock the file. Is there another way I can lock the file in Windows? -- cdewin at dingoblue.net.au From adeptus at onebox.com Wed Mar 13 04:33:46 2002 From: adeptus at onebox.com (adeptus) Date: 13 Mar 2002 01:33:46 -0800 Subject: Python / Active Scripting - Value Assignment - HELP Message-ID: OK... Within a script block of a HTML file, I can do the following: something = ax.document.bgColor ax.document.write("Background color is %s:" %something) However, unlike all the Javascript and VB examples I see, I can't do the following: ax.document.bgColor = "#000000" I always get an error about unicode strings being read only. The easiest workaround I can concieve of involves simply using the genhtml module, but something about this bothers me. I should be able to set the values as I could with VB or Javascript. I also have a feeling this is something that would be remedied by a better understanding of COM, but there are only so many hours in a day... ;) Thanks in advance... From syver-en+usenet at online.no Thu Mar 28 12:53:42 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 28 Mar 2002 17:53:42 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: Dale Strickland-Clark writes: > Absolutely. All of Mark's Win32 stuff are pretty much essential to > many Windows users now, I would guess. That's very true. > > Updating the distro package would be nice too: Add a few handy > registry tweaks, such as setting PATHEXT properly, and a nice HTML > Windows help file (chm) and we'd have a nice slick package. Adding the registry settings so that one can drop data files on .py and .pyw files and the files dropped will be received as commandline arguments would also be nice. Does anybody know who is responsible for dynwin/calldll these days, It is very nice for experimenting with the win32 api's. -- Vennlig hilsen Syver Enstad From oleksik at awa.mat.agh.edu.pl Tue Mar 19 05:53:35 2002 From: oleksik at awa.mat.agh.edu.pl (Pawel Oleksik) Date: Tue, 19 Mar 2002 10:53:35 +0000 (UTC) Subject: python 2.1.2, Linux and 'os' library: bug or (bad) feature? References: Message-ID: Martin v. Loewis wrote: > > I think the is the doing of X itself: start the same program from the > shell prompt, and you should observe the same behaviour. > > Regards, > Martin > No way! And as I've written above: python 2.1.1, 2.1.0, and 2.0.1 work OK. BTW. just for proof: oleksik at awa:~> ps -A PID TTY TIME CMD 1 ? 00:00:03 init [...] 5592 ? 00:00:02 X [...] oleksik at awa:~> python Python 2.1.1 (#1, Aug 23 2001, 13:52:32) [GCC 2.95.4 20010619 (prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> open("/proc/5592/cmdline").read() 'X\x00:1\x00' So, IMHO, 'os' library from python 2.1.2 has a BUG. But I'm still iteresting in your opininion. best regards p.o. From aahz at pythoncraft.com Wed Mar 13 13:17:15 2002 From: aahz at pythoncraft.com (Aahz) Date: 13 Mar 2002 13:17:15 -0500 Subject: trackers (was: zlib vulnerabilities and python) References: Message-ID: In article , Trent Mick wrote: >[Michael Hudson wrote] >> >> Time to look at roundup again? The tracker on sf is starting to piss >> me off (even more). > >If you *are* going to get motivated to look at a different tracker *please* >consider bugzilla. You will find it a much more appropriate than roundup. Sure! Knowing nothing about SF trackers (yesterday was my first submitted bug, I think), roundup, or bugzilla, I think I'm in a perfect position to evaluate all of them. Can you explain what makes bugzilla superior to roundup? What, if anything, does roundup have that bugzilla does not? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From martin at v.loewis.de Sat Mar 30 06:46:03 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 12:46:03 +0100 Subject: PEP 285: Adding a bool type References: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > I don't see much need for it. There's no need to turn Python into Java. > Python, C, and Lisp have all done fine without bools. C99 has stdbool.h, though. > What kinds of programming tasks in Python are bools supposed to make > easier? RPC implementations (see the rationale in the PEP), XPath processors. > > Some external libraries (like databases and RPC packages) need to > > be able to distinguish between Boolean and integral values, and > > while it's usually possible to craft a solution, it would be > > easier if the language offered a standard Boolean type. > > Again, most of those libraries have C interfaces Actually, no. Most of those libraries are pure-Python. Those that do use C interfaces need to expose the bool types of the C interface. > and (pre-C99) C didn't have bools. Many C programs (in particular pre-C99) have bools. Not just one, but hundreds of them. C99 introduces an additional one, which it calls the "standard" boolean type. Regards, Martin From logiplexsoftware at earthlink.net Wed Mar 13 13:43:16 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 13 Mar 2002 10:43:16 -0800 Subject: Another socket/thread question In-Reply-To: References: Message-ID: <20020313104316.781fca2c.logiplexsoftware@earthlink.net> On Wed, 13 Mar 2002 10:37:29 -0800 Ken wrote: > Hey everyone.. > > I've got a thread that continously listens to a socket, and reports what it > receives. Blocking is turned on, and I would like it to stay that way since > the only thing the thread has to do, is listen to the socket. > > My question is when the socket needs to be closed (program shuts down, or > that user is being disconnected by the server) is it possible to interupt a > socket.recv ()? > > If not, whats the easiest way to cut processor time from looping endlessly > with blocking turned off? You might try using select() with a reasonable timeout period. Then you won't busy loop, but you'll be able to check every few seconds to see if some condition is set that would indicate a program exit. Alternatively, you could have your shutdown function send something to the socket itself which would indicate to the thread that it should exit. Or even some irrelevant data followed by a test on whether the thread should exit (the data would never be processed so what it is would be unimportant - it's used simply to cause socket.recv to return). -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From wolfson at uchicago.edu Mon Mar 11 19:42:12 2002 From: wolfson at uchicago.edu (Ben Wolfson) Date: Mon, 11 Mar 2002 18:42:12 -0600 Subject: python and haskell for fun References: Message-ID: On Mon, 11 Mar 2002 17:02:34 -0600, Aahz Maruch wrote: > The main problem with Vyper was that it wasn't finished, and Skaller > mysteriously vanished. The most recent hits for "John Max Skaller" on google is from September 2001. He's now got a new language of his own: http://felix.sf.net . It seems pretty similar to what he had planned for Vyper, but looks more C-ish. I don't know if he still follows Python; interscript uses 1.5.1. -- BTR BEN WOLFSON HAS RUINED ROCK MUSIC FOR A GENERATION -- Crgre Jvyyneq From r.salz at verizon.net Sun Mar 17 22:42:34 2002 From: r.salz at verizon.net (Rich Salz) Date: Mon, 18 Mar 2002 03:42:34 GMT Subject: how to print class names, not references References: <3C9544B5.47CD0918@pop.ntlworld.com> Message-ID: <3C95622B.4040803@verizon.net> If "x" is an instance, then x.__class__.__name__ is the name of the class. /r$ From usenet at minus1.de Sat Mar 16 15:09:20 2002 From: usenet at minus1.de (Konrad Anton) Date: Sat, 16 Mar 2002 21:09:20 +0100 Subject: Gadfly mirrors? References: Message-ID: matt at swordfish.havenrock.com schrieb: >Hi, folks-- > >Does anyone know of an alternate download site for Gadfly? I have been >unable to reach www.chordate.com all evening. It is also in a Debian package called "gadfly" in section "interpreters", available from ftp.Debian.org mirrors. HTH Konrad. -- Konrad Anton ; Web: www.minus1.de ; gpg: 0x22954D8A Tel. +49-761-881-2122, Fax +49-721-151318943. Alice: It's generally why? From curtin at ubsw.com Tue Mar 5 10:06:13 2002 From: curtin at ubsw.com (craig curtin) Date: 5 Mar 2002 07:06:13 -0800 Subject: stdout/stderr disabled when debugging in pythonwin (somehow i disabled it...) Message-ID: <4c7395cb.0203050706.668a8eaa@posting.google.com> i'm having a problem with "print" and sys.stdout.write() in pythonwin (2.1.212). when i'm executing/debugging in pythonwin, i have no sdtout/stderr. any of my print statements, exceptions, etc don't display in the immediate window.... when i execute python from the cmd line, i see the exceptions/ print statements. this was working before, somehow i disabled it.... ;-( anyone seen this before ? craig From fredrik at pythonware.com Mon Mar 11 14:22:41 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Mar 2002 19:22:41 GMT Subject: lambda question References: Message-ID: <5u7j8.24390$n4.4764583@newsc.telia.net> RES: lambda questionAlves, Carlos Alberto wrote: > Sorry, but your code doesn't work also. See below: > >>> def exe1(f,list): > return map(lambda x,list=list:eval(f),list) > SyntaxError: local name 'f' in 'exe1' shadows use of 'f' as > global in nested scope > 'lambda' (, line 1) try this one instead: def exe1(f,list): return map(lambda x,f=f:eval(f),list) > By the way, where can I find the Python's LGB scoping rules. > I would like to read that. the language reference, perhaps? http://www.python.org/doc/2.1/ref/execframes.html "The _local namespace_ of an execution frame determines the default place where names are defined and searched. The _global namespace_ determines the place where names listed in global statements are defined and searched, and where names that are not bound anywhere in the current code block are searched." "When a global name is not found in the global namespace, it is searched in the built-in namespace (which is actually the global namespace of the module __builtin__ )." (local, global, built-in -> LGB) note that the scoping rules has been modified in Python 2.2: http://www.python.org/doc/2.2/ref/nested-scopes.html under the revised scoping rules, your example should work as originally written. From khirmint at hotmail.com Fri Mar 8 16:11:00 2002 From: khirmint at hotmail.com (Ken) Date: Fri, 08 Mar 2002 13:11:00 -0800 Subject: newbie socket/thread question Message-ID: <3C8928E3.4B55769D@hotmail.com> Hey everyone.. I'm messing around with Python, trying to learn the language, by building a simple network chat program that uses threads and sockets. I'm trying to set it up so that if the server receives a keyboard interupt from console, it'll shut everything down. Which seems to work fine for the most part. The problem is that after a user connects and the server is stopped, the server cannot start up again right away. It gets the error: socket.error: (48, 'Address already in use') This only happens after a user has connected, though. Can anyone give me an idea of what I'm doing wrong? Here's the code that I'm using: (keep in mind that I'm just learning the language and that program itself is incomplete) #! /usr/bin/env python # # Globals # CHATPORT = 43278 userlist = [] # # Imports # from socket import socket, gethostbyname, AF_INET, SOCK_STREAM from threading import Lock, Thread, Event from time import sleep from signal import signal, SIGINT # # User # class User ( Thread ): "Handles incoming and outgoing communications to a user" def __init__ ( self, conn, addr, goevent ): print "Initializing user.." Thread.__init__ ( self ) self.conn = conn self.addr = addr self.goevent = goevent; def run ( self ): while self.goevent.isSet (): try: data = conn.recv ( 1024 ) print "Got data..: " + data except: sleep ( 3 ) pass def terminate ( self ): print "Terminating " + self.addr[0] self.conn.close () # # MasterListener # class SocketListener ( Thread ): "Waits for connections to be recieved and hands new connections off \ to the child handler" def __init__ ( self, goevent, port ): Thread.__init__ ( self ) self.goevent = goevent self.hostip = gethostbyname ( 'localhost' ) self.port = port # setup the socket self.mainsocket = socket ( AF_INET, SOCK_STREAM ) self.mainsocket.bind ( (self.hostip, self.port) ) self.mainsocket.listen ( 1 ) self.mainsocket.setblocking ( 0 ) def run ( self ): print "Daemon started and awaiting connections.." while self.goevent.isSet (): try: conn, addr = self.mainsocket.accept () print "Connected by", addr print "Connection received.." # start up a user thread to handle the new comer newuser = User ( conn, addr, self.goevent ) newuser.start () userlist.append ( newuser ) except: sleep ( 1 ) # clean up print "Closing user connections.." for user in userlist: user.terminate () print " user connections closed." print "Closing main socket.." self.mainsocket.close () print "Socket Listener Terminated" class MasterLoop: "Handles the startup of the daemon, starts network functionality, etc" def __init__ ( self ): self.mastergoevent = Event () self.socketlistener = SocketListener ( self.mastergoevent, CHATPORT ) signal ( SIGINT, self.sigint_handler ) def beginExecute ( self ): self.mastergoevent.set () self.socketlistener.start () # loop endlessly until told to terminate while self.mastergoevent.isSet (): sleep ( 1 ) def endExecute ( self ): self.mastergoevent.clear () def sigint_handler ( self, frame, frameobj ): print "\nAttempting to shutdown daemon.. please wait.." self.endExecute () if __name__ == '__main__': "Simple chat server" maincontrol = MasterLoop () maincontrol.beginExecute () From news at charneyday.com Fri Mar 8 04:42:52 2002 From: news at charneyday.com (Reginald B. Charney) Date: Fri, 08 Mar 2002 09:42:52 GMT Subject: Order of constructor/destructor invocation References: Message-ID: Thanks Justine, I don't feel that your tone is confrontational. You have expressed a view, reflected by many others here, that my approach is not appropriate for Python. While this is a small sample of respondents, it may be representative, so the style may not be acceptable in the sense that it is not idiomatic for this language. That said, let me comment on your example. The use of block structures can define scope so that your example: > h = HTML() > b = BODY() > l = LIST() > le = LISTELEMENT() > p = PARAGRAPH() could be written, using my approach, as: h = HTML() b = BODY() l = LIST() le = LISTELEMENT() p = PARAGRAPH() Believe it or not, I was not trying to start a religious war. I was trying to use a well-defined approach in one language to another language that I thought was similar enough in structure to work in the same way. However, as Brett g Porter (an earlier poster) said, "Down that path lies madness." Thanks to you all who were good enough to respond to my question and my apologies if I started out to strongly or offended anyone. Reg. "Justin Sheehy" wrote in message news:mailman.1015517608.2847.python-list at python.org... > "Reginald B. Charney" writes: > > > Brett is exactly right. I am using an approach that is valid and elegant in > > C++. > > Since elegance is largely a matter of opinion, I'll simply disagree on > that point. Destructors and related methods generally ought to be > used for object cleanup related to their reclamation, not for doing > additional new processing. Abusing them in this fashion feels deeply > inelegant to me, especially since there are so many straightforwward > ways to solve the problem without resorting to such means. > > Elegance aside, your approach is invalid regardless of the > programming language. > > You cannot create a correct HTML-writing program in the style you > demonstrated, given the structure of HTML. Your linear style simply > will not work for anything beyond trivial examples, since HTML is > fundamentally hierarchical. > > As another poster mentioned, your method breaks down very quickly. > Your style would not work for this fairly simple document because the > structure is unclear: > > ----------------------------- > h = HTML() > b = BODY() > l = LIST() > le = LISTELEMENT() > p = PARAGRAPH() > ----------------------------- > > This will not work because you must specify both the start and end of > a tag in this sort of language. It cannot be usefully inferred from > any linear structure. This has little to do with Python, and will > break just as badly in any language. > > A few examples of alternate strawman methods that might work: > > ----------------------------- > h = HTML() > b = BODY() > l = LIST() > le = LISTELEMENT() > p = PARAGRAPH() > h.start() > b.start() > l.start() > le.start() > le.end() > l.end() > p.start() > p.end() > b.end() > h.end() > ----------------------------- > HTMLstart() > BODYstart() > LISTstart() > LISTELEMENTstart() > LISTELEMENTend() > LISTend() > PARAGRAPHstart() > PARAGRAPHend() > BODYend() > HTMLend() > ----------------------------- > HTML(BODY(LIST(LISTELEMENT()), PARAGRAPH())) > ----------------------------- > > The first two of these are not quite as concise as yours, but unlike > yours all three are able to express the needed structure to correctly > generate HTML. > > > While Justin is correct - there are a number of packages out there to > > generate HTML, I was writing an article and trying to use Python for the > > simple examples in the article. (The article was not about Python, per se). > > I had to remove all references to Python when I found that the order of > > destruction was non-deterministic. > > This doesn't follow. There are plenty of simple ways to do what you > describe that work without trying to misuse the methods designed to > aid with garbage collection. > > > It is interesting that destruction/garbage collection (something > > usually done after everything has been completed) has so profound > > effect on the design of programs and thus, implementation of > > algorithms. > > It wouldn't have nearly as much effect if you took heed of your own > parenthetical note and realized that all of an object's interesting > work should be done before the destructor, as opposed to inside the > destructor. > > I apologize if my tone here is a bit confrontational, but that is > largely due to the fact that you immediately began blaming Python for > not doing what you want in spite of an incorrect design. > > -Justin > > > > > > From maxm at mxm.dk Wed Mar 20 09:30:40 2002 From: maxm at mxm.dk (Max M) Date: Wed, 20 Mar 2002 14:30:40 +0000 Subject: classes for fun and newbies References: Message-ID: <3C989D10.5070409@mxm.dk> Bruce Dykes wrote: > Now what I expect to be able to do is say: > > log = readlines(today.log) > > and then summon discrete bits of info like so: > > print call_record.record_id(log[1]) It would probably be simpler to it with just a function in this case: id = (0,5) date = (6,11) def getPart(slice, line): return line(slice[0]:slice[1]) print getPart(id, log[1]) or something like that. But just writing it in one big mess is probably not out of the question either. for line in,lines: id, date = line[0:5], line[6:11] Generally there is no need ti write objects before it is needed. Ie. when your code violates the DRY (Dont Repeat Yourself) principle. But then you could do something like (untested). class Rec: def __init__(self, line): self.line = line def __getattr__(self, attr): if attr == 'id': return self.line[0:5] if attr == 'date': return self.line[6:11] class Log: def __init__(self, fileName): f = open(fileName,'r') self.lines = f.readlines() f.close() def __getitem__(self, index): return Rec(self.lines[index]) def __len__(self): return len(self.lines) Then you can use it like: log = Log('logfile.log') print log[1].id or like: for item in log: print item.id regards Max M From jjb5 at cornell.edu Wed Mar 27 13:42:28 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Wed, 27 Mar 2002 13:42:28 -0500 Subject: The Python Way References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: > lock.acquire() > try: > code > code > code > code > code > code > code > code > code > code > code > code > finally: > lock.release() > > In any large application, it gets *tiresome* to see this, particularly > if you add another layer of nested try/except. In C++ it's common to have a wrapper class that acquires the lock in the ctor and releases it in the dtor, then allocating an object of that class on the stack local to the function. Is there a Pythonesque version of the same design pattern? Is there any way to add the locking functionality as a facade to a non-locking version of the same function? I'm on the leading edge of the Python learning curve, but would this work? class A: def fn(self,x): pass class B(A): def fn(self,x): lock.acquire() try: A.fn(self,x) finally: lock.release() Or is this considered poor form? Joel From stephen at xemacs.org Mon Mar 11 03:28:09 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 11 Mar 2002 17:28:09 +0900 Subject: should i learn it first ? References: Message-ID: <87elirbjae.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Jason" == Jason Orendorff writes: Jason> Bengt Richter wrote: >> If you start with C, you will get used to a procedural way of >> looking at problems, and when you get to C++ you will be >> tempted to see it as just C with extra features. Jason> Everybody (Stroustrup included) seems to think this is a Jason> common pitfall, but I haven't seen anyone fall into it. Evidently you haven't been exposed to very many C++ textbooks. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From johnroth at ameritech.net Sat Mar 30 07:31:42 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 30 Mar 2002 07:31:42 -0500 Subject: PEP 285: Adding a bool type References: <2zRcLUAVjXp8EwVv@jessikat.fsnet.co.uk> Message-ID: "Robin Becker" wrote in message news:2zRcLUAVjXp8EwVv at jessikat.fsnet.co.uk... > In article , Guido van > Rossum writes > ...... > This pretty much seems unwanted to me. Done purely for political > correctness. Whenever new keywords are discussed the Gods are against > them. Now we have to accept new constants true, false + a new type. > Silly like all those programmers who have constants like one and zero or > ten in code. Disagree strongly. One of the things that makes a programming language pleasant is that you can **depend** on certain constructions. Having a bool type, properly implemented, is IMHO definitely in line with that - I've always thought that 0 and 1 were a kludge put into languages by designers that were too lazy to do it right. > If we get bools can sets be far behind, and what about quaternions and > abelian groups? I could see sets as part of the core language, if a couple of issues with respect to notation could be cleared up. I don't see the other two, but then, I don't really think that complex numbers should have been part of the core language either. It depends on what can be used by most applications. Sets and enums are generally useful. Complex, quaternians and so forth are application specific things. John Roth From tejarex at yahoo.com Thu Mar 7 23:51:39 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 08 Mar 2002 04:51:39 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> Message-ID: "Bengt Richter" wrote in message news:a6912n$jnt$0 at 216.39.172.122... > Sorry, I wasn't making clear an unspoken condition I really had in mind ;-) > I think (3) does follow (2) using the added explicit condition that the > text quotation is to be part of the source text of a program or module, > and the quoted text must not need to be changed or restricted to do it. With the added conditions, the logic works much better. ... > The simplest practical example is wanting to use a paste operation > to insert arbitrary text into a program source without having to inspect > the text or modify it, yet be able to use it to define a string > with the exact raw text value. As Greg Ewing noted, you still have to scan the text with your method, so why not scan for triple quotes - which are *extremely* rare in any text except Python code and *quite* easy to spot (speaking for myself). One can always use the interpreter to check also. Write s='''\ ''' and run or paste into interpreter. If there is a ''' that one missed, there will almost certainly be a SyntaxError reported, with the line number. One could also follow the definition of s with 'print s[:-100]' to see if entire quotation got included in assignment. For myself, I can hardly imagine wanting to incorparate gobs of someone else's text into my code. If I did, I would want to look at it and/or isolate it in a separate module where it could be tested as above. I would also feel free to modify it with escape codes if necessary. Terry J. Reedy From kennedy.bill.nospam at freeuk.com Fri Mar 8 02:21:15 2002 From: kennedy.bill.nospam at freeuk.com (William Kennedy) Date: Fri, 08 Mar 2002 07:21:15 GMT Subject: NoteTab Lite? References: Message-ID: Sorry if I was not clearer, the editor is called NoteTab and is supplied in three formats of which the Lite version is Freeware. It uses what they call libraries that allow the user to store code snippets or macros and several have been set up for perl etc. I was wondering if anone has such a library for Python or wxPython, I am starting to build one but why reinvent the wheel if you dont have to. In article , "Delaney, Timothy" wrote: >> From: kennedy.bill.nospam at freeuk.com >> >> Does anyone use the NotePad series for writing Python code, >> if so have they >> built a python library that I can have. > >Do you mean NoteTab? > >Tim Delaney > --- William Kennedy remove the .nospam from my email address From carifio.nospam at nospam.usys.com Mon Mar 11 15:32:57 2002 From: carifio.nospam at nospam.usys.com (Mike Carifio) Date: Mon, 11 Mar 2002 20:32:57 GMT Subject: augmented arithmetic operations Message-ID: According to the language ref section "Emulating numeric types" (http://www.python.org/doc/current/ref/numeric-types.html), I can use special name methods to overload operations. When creating "augmented operations" like __iadd__ (for "+=") is it considered "bad form" to create a intermediate value and then assign parts of self to the intermediate value? Or is this just an implementation detail? For example, suppose I introduced Point as a kind of number: class Point: def Point(self, x, y): self.x = x; self.y = y def __add__(self, rhs): return Point(self.x + rhs.x, self.y + rhs.y) def __iadd__(self, rhs): intermediate = self + rhs # bad form? self.x = intermediate.x; self.y = intermediate.y p11 = Point(1,1) p22 = Point(2,2) p33 = p11 + p22 # p11.__add__(p22) p33 += p11 # p33.__iadd__(p1) makes p33 (4,4) I'd like to reuse __add__ without having to introduce an intermediate object... From jkraska at san.rr.com Wed Mar 27 12:05:58 2002 From: jkraska at san.rr.com (Courageous) Date: Wed, 27 Mar 2002 17:05:58 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: <8gv3au47846mgol398j4oc5t0ufoi274b4@4ax.com> >And then, when you begin to flesh out your code, you would have to >get rid of the extraneous passes you didn't want to add (assuming >you are like me) in the first place. So the with-pass version >requires more effort, and is more verbose, for no good reason. The reasons are related to the implementation and not the design of Python, I believe. C// From mcherm at destiny.com Wed Mar 20 13:41:51 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 20 Mar 2002 13:41:51 -0500 Subject: Java and Python Message-ID: <3C98D7EF.5000408@destiny.com> Jan Dries writes: >> May I ask you what the scale for your webapp was? (Because MySQL is >> related to small to mid-size web applications). Is it the same case with >> Python? > > FWIW, a recent benchmark test in Eweek showed MySQL to be comparable to > Oracle 9i with respect to both performance and scalability. > See http://www.eweek.com/article/0,3658,s=708&a=23115,00.asp And please not that this benchmark used MySQL in *transaction* mode, same as Oracle. When used without transactions it's even faster. I must say, I was quite surprised... I thought Oracle was further ahead. -- Michael Chermside From James_Althoff at i2.com Mon Mar 11 14:31:16 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 11 Mar 2002 11:31:16 -0800 Subject: PEP 284, Integer for-loops Message-ID: [Tim Legant] > So either Jason and I are significantly better than you and your > team at expressing ourselves naturally in Python or it's > the need to interface with Java that's forcing you to use integer > indices all the time. I'm betting big money on the latter. I'm happy to believe you all are excellent programmers versed in Pythonic ways. And I'm always happy to learn something new. So feel free to help me on this one. Here's your mission. You are writing applications that deal with advanced spreadsheets populated from database tables. Your spreadsheets need to have all the features of Excel including advanced things like pivot tables for multi-dimensional OLAP analysis, reports, charts, graphs, etc. The data in your spreadsheets can be fairly complex and can include images. Your market demands that you use Java. C-Python is not an option. You will be using 3rd party components written in Java. These component were not created by the folks at PythonLabs. These components do not follow any of Python's standard protocols. You do not have the source code to these components. Furthermore, due to the advanced nature of the application and its data you understand that you are on the hairy edge of acceptability of performance. You have noted that creating Python subclasses of Java superclasses can slow performance -- in your case, it drops below acceptable levels. Same with wrapper classes. Also note that the version of Jython used, 2.1, does not support iter/__iter__ and does not support generators. One of your 3rd party components is a table. It has a basic access protocol via methods like this: def getRowCount(): pass def getColumnCount(): pass def getValueAt(rowIndex,columnIndex): pass def setValueAt(rowIndex,columnIndex): pass You have lots of example code written in Java that manipulates this component via row and column indices using for-loops. Your team will be writing hundreds of code fragments that do things like: - take a specified formula and apply it to a specified column for each row - take a specified formula and apply it to a specified row for each column - pivot the table on a specified column, spread the cells in that column across a specified row - from a specified formula, calculate and set the value for every other row in a given column - etc., etc., etc. (think many hundreds of variations here) We tend to use for-loops based on indices for this type of code. We could drop back to writing while-loops; but that seems more error-prone, like more work, and less favorable to the programmers around here. Perhaps you could give some ideas on approaches that would be more "Pythonic"? Thanks, Jim Althoff Senior Vice President i2 Technologies, Inc. From grante at visi.com Sat Mar 16 00:44:41 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 16 Mar 2002 05:44:41 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: In article , Donn Cave wrote: > Quoth grante at visi.com (Grant Edwards): >| In article , Rich Cook wrote: > ... >|> So do I have to read the data byte by byte using read(1) and >|> examine each character to avoid blocking? Is there any way to >|> find out how much data is actually waiting for me in the file >|> object so I can read it in bigger increments, or must I call >|> select then read(1) for every byte? >| >| You don't have to read it 1 byte at a time. Just call >| f.read(1024) and it will give you however many bytes are >| available, up to the max of 1024. You can use a max different >| than 1024 if you want. > > I think you're making the problem worse here. > > import popen2 > t = popen2.Popen3('echo L1; sleep 2; echo L2; sleep 2; echo L3') > print 'First read: ', repr(t.fromchild.read(1024)) > > $ python /tmp/x > First read: 'L1\nL2\nL3\n' > > C I/O basically sucks for this application. When you ask for 1024, > fread is bound to get that amount, just as it is if you ask for a > line via fgets ("readline".) If you omit the amount, you're asking > for all the data, won't return until the socket's other end closes. Sorry, with all the talk of sockets, I was thinking of the recv() call. -- Grant Edwards grante Yow! -- In 1962, you could at buy a pair of SHARKSKIN visi.com SLACKS, with a "Continental Belt," for $10.99!! From rkashyap at sympatico.ca Thu Mar 7 14:32:39 2002 From: rkashyap at sympatico.ca (Ramkumar Kashyap) Date: Thu, 07 Mar 2002 14:32:39 -0500 Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> <20020307035851.GA23955@isis.gerrietts.net> Message-ID: <3C87C057.4040902@sympatico.ca> My original intent for starting the thread was because I truly believe in CP4E. In my freshman year, we were a total of 38 students in the EE major. When I graduated four years later, there were 12 of us, no women. I don't believe that programming concepts are more difficult/harder to understand and grasp than any engineering curriculum or for that matter physics/mathematics. Somebody in this thread raised the point that the logic involved in programming in not intuitive. I agree with that. The point I want to make is that there are programs like Hooked-on-Phonics, and other remedial language programs that are quite effective in raising the literacy levels among adults. Another point (this is purely from observation and others with children may want to corroborrate) is that children tend to learn faster and retain longer with repetition. I don't know if there are any people on CLP who are also conversant with the human brain and can shed light on the formation of new neural pathways etc. I should also confess that I have an ulterior motive in this discussion, which is to teach my kid to program, (which is still a few years away). regards, Ramkumar Geoff Gerrietts wrote: >Quoting Geoff Gerrietts (geoff at gerrietts.net): > >>What is it about internet discussion forums that makes everyone >>struggle to find grounds to argue rather than make an effort to >>understand? >> > >I was probably being unfair here. Read here frustration at feeling >like the point's been missed for the lint-picking. > >>Again, this is begging the question, and after two pointless arguments >>niggling over the semantics of "smarter", I'm starting to get a little >>annoyed. I can define smarter as "having a higher IQ", as "best >>educated", or as "most able to solve a given problem" and all of them >>work pretty well. Right now I'm talking about ability to ingest raw >>information and retain it. It's clear I should have been a little more >>explicit; I guess terms like "smarter" are just begging for people to >>fight. >> > >And here at least I admit it's my fault, if a little late in the >issue. > >I've tried to recast this discussion away from the specifics of my >first article and toward the issues, lest they get lost. I just want >to apologize in advance for letting my frustrations show, lest I give >insult where none was intended or deserved. > >I'd rather the thread be intellectually provacative than >provocational, if we can manage it; pedagogy is of interest to me. > >Thanks, >--G. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fperez528 at yahoo.com Wed Mar 6 05:05:03 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 06 Mar 2002 10:05:03 +0000 Subject: [ANN] istring 1.0.1 released; announce list created References: Message-ID: Steven D. Arnold wrote: > Neosynapse has released istring 1.0.1, a module for interpolating > strings in Python. String interpolation means you can put variables > directly in strings, like this: > >>>> from neo.istring import istring as i >>>> n = 100 >>>> s = i("Value is $n") >>>> s > "Value is 100" > > The new release fixes several small bugs. In addition, we have > created an istring-announce list, which will receive information > regarding minor version updates and bug fixes. To subscribe, go to: > > http://www.casti.com/mailman/listinfo/istring-announce. > > The istring download page is at: > > http://www.neosynapse.net/interpolated_string.htm Very nice, and thanks for the contribution. I've long been a fan of this idea. But could you please clarify if your module is in anyway different to the 'old' interpolation module that's been the reference implementation to PEP 215? You can find it at http://web.lfw.org/python/ towards the middle of the page. Also see pep215 at http://python.sourceforge.net/peps/pep-0215.html BTW, this isn't meant to deride your work in any way. It's just that when I see new code doing similar things to existing modules I like a quick comparison to decide whether I want to move to the new code or not. Thanks, f. From philh at comuno.freeserve.co.uk Fri Mar 8 13:54:28 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 8 Mar 2002 18:54:28 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Fri, 08 Mar 2002 08:54:15 -0800, David Eppstein wrote: >In article , > philh at comuno.freeserve.co.uk (phil hunt) wrote: > >> Thev reasdon i don't like it is that the syntax already has a >> meaning: to compare the magnitude of values. Now you are proposing >> another, totally different, meaning. > >How is that unlike the difference in meaning between "in" in expressions >and "in" in for-loops? I never said I particularly liked that, either. But it is a well-established part of the python language. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From phr-n2002a at nightsong.com Wed Mar 20 07:46:12 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 20 Mar 2002 04:46:12 -0800 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> Message-ID: <7xelifcsq3.fsf@ruckus.brouhaha.com> Andy Gimblett writes: > > > >
      > > >
    • > > > surname > > >
    • > > >
    > > > Geez, I find all this pseudo-HTML horrendous. Why not just embed > > It's not pseudo-HTML, it's W3C compliant HTML (is " IMHO it's also better looking than tags. The issue isn't the which can be replaced by something else if you want. It's making code look like HTML properties instead of making it look like code. From slick at asia.com Tue Mar 26 00:38:03 2002 From: slick at asia.com (Slick) Date: 25 Mar 2002 21:38:03 -0800 Subject: Memory Error while simulating matrix Message-ID: Hello, When i execute the code(part of an algorithm code) given below, i get a MemoryError. The best part was that this ran a couple of time before it began crashing. ------------------------ code starts here ---------------------- row = [] # list row = [0] * 1000000 # each row contains million columns matrix =[] # contains a collection of rows for i in range(1000): # creating a matix of 1000 rows each matrix.append(row[:]) # having a million columns ------------------------ code ends here ---------------------- ------------------------- error message starts here ------------ Traceback (innermost last): File "a.py", line 7, in ? matrix.append(row[:]) MemoryError ------------------------- error message ends here -------------- Is there any way to prevent this error ? other than installing the pyNum package ? Any help to prevent this from happening is appriciated. Thanks in advance Max From gh_pythonlist at gmx.de Sun Mar 31 23:27:32 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 06:27:32 +0200 Subject: Python/Linux In-Reply-To: References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: <20020401042732.GA8783@lilith.hqd-internal> * Robert Oschler [2002-04-01 00:07 -0500]: > So what then do you think? BlueFish, Quanta Last time I checked these didn't do WYSIWYMG. > WebSphere Homepage builder? Haven't tried it (it wouldn't run on the version of SuSE I had at the time). As I said, I personally like very much and use Mozilla Composer for WYSIWYMG and vim for editing HTML code directly. You should really have a look at Mozilla, it's *far* better than the editor from Netscape, though it could need some UI improvements (hiding the less used options in advanced tabs or such). But I haven't seen anything that comes close to Macromedia's Dreamweaver and runs on Linux. But then, I don't fuzz with page layout very often - my HTML design mostly consists of editing .css files :-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 5.6 ?C Wind: 1.3 m/s From theller at python.net Wed Mar 20 09:16:33 2002 From: theller at python.net (Thomas Heller) Date: Wed, 20 Mar 2002 15:16:33 +0100 Subject: Develop-test-debug cycle References: Message-ID: "Dale Strickland-Clark" wrote in message news:un2h9ukh13kddcd3ooc9osejapiaf5v6t3 at 4ax.com... > I can't believe I'm doing this this best way. > > I am debugging a large system written in Python with modules spread > over 4 directories. I'm using PythonWin under Win2K to set-up the > environment and run the code. > > Setting up the environment typically involves the following commands: > > import sys > sys.path.append("x:\\whereever") > from wibbleModule import wibble > wibs = wibble(args) > > wibs.methods(args) > > > > At this point, I fix the error. > > Now, I haven't figured out a way of continueing past this point > without quiting and starting from scratch because there appears to be > no way to get Python to reload a module. The reload() function doesn't > do it. > > I've tried stuff like this: > > del wibs > reload(sys.modules['wibbleModule'] > > but I still seem to have the old version loaded. > > I've also tried using PyCrust for this but it suffers from the same > problems. I assume IDLE does too. > > How do others go about interactively debugging large Python OO-based > systems? Dave, maybe this can help you? Comments appreciated, I didn't get much feedback! This script spawns a thread watching changed modules, automatically reloads them, and tries its best to update the currently running program. http://aspn.activestate.com/ASPN/Mail/Message/907876 and note this bugfix: http://aspn.activestate.com/ASPN/Mail/Message/907945 Thomas From david.abrahams at rcn.com Sat Mar 30 05:57:39 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sat, 30 Mar 2002 05:57:39 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> Message-ID: <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> "Guido van Rossum" writ: > Dear reviewers: > > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. Depends on the resolution of #2 and #3 ;-) > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) str(True) must return 'True' or there isn't much point in bothering with this, IMO. > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). As a language interoperability guy, I prefer to keep as much precise correspondence as possible with C++ (and Java), so I vote for 'true'/'false'. > Most other details of the proposal are pretty much forced by the > backwards compatibility requirement; e.g. True == 1 and > True+1 == 2 must hold, else reams of existing code would break. Guess what other language made that same choice for the same reasons? > Minor additional issues: > > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. Changing my position somewhat from earlier, I'll vote in my project's self-interest: I agree with your inclination to allow bool to be "promoted" to an int in these conditions. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. I agree again! 6) Should we eventually remove the inheritance relationship between Int and Bool? I hope so. Bool is-a Int doesn't seem like the right relationship to me, unless perhaps we make Int is-a Long... naah, not even then. -Dave From michael at amtec.com Thu Mar 28 11:17:21 2002 From: michael at amtec.com (Michael Saunders) Date: Thu, 28 Mar 2002 08:17:21 -0800 Subject: Extension Modules in C Message-ID: <3CA34211.5D367EAB@amtec.com> I am trying to wrap an existing C API as an extension module for Python. Some of the functions have parameters that are both input and output. Yea, I know it stinks. Does Python support this notion of a passed parameter being modified? For instance if I had a c function: int GetSomeInfo(char **Title, int *count, int *size); where it would be called as follows: int isOk, count, size; isOk = GetSomeInfo(NULL, &count, &size); where addresses of the storage locations are passed or NULL if you are not interested in the information. Can this function be wrapped to have a similar API from python. For instance in Pytyon: isOk = SomeModule.GetSomeInfo(None, count, size) if isOk: print count, size Thanks, Michael From philh at comuno.freeserve.co.uk Sun Mar 17 20:13:30 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 18 Mar 2002 01:13:30 +0000 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: On Sun, 17 Mar 2002 15:08:08 -0500, David Mertz, Ph.D. wrote: >| danb_83 at yahoo.com (Dan Bishop) wrote: >|> Even for complex numbers, for which "less than or greater than" is >|> meaningless? > >Just van Rossum wrote previously: >|It doesn't have that meaning for me anymore, it simple means "not equal" >|to me. It is an abstract symbol. I really don't believe we can discuss >|this on any other level than "I prefer x because I'm used to it"... > >In the end, Just is right. People get used to different things. > >Nonetheless, I think of the natural language semantics of the >symbols--or maybe better "insinuations"--prefers '<>' to '!='. The >(good) one suggests "is greater than or less than (but not equal to)". >I know that not everything is technically in an order relation, but it >still "makes sense" at a first approximation. No it doesn't. It's implying that you can only test for equality two tings that are both magnetudes, by implying that if a != b then either a < b or a > b. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From kirschh at lionbioscience.com Tue Mar 5 03:15:51 2002 From: kirschh at lionbioscience.com (Harald Kirsch) Date: 05 Mar 2002 09:15:51 +0100 Subject: Memory leak when importing? References: Message-ID: Martin von Loewis writes: > Harald Kirsch writes: > > > Any ideas? Rough guesses? > > I'd invoke gc.getobjects() from time to time, to see whether the list Sounds good, but in which version does it appear? I cannot find it in the docs of 2.1 or 2.2, nor a function of a similar name. Harald Kirsch -- ----------------+------------------------------------------------------ Harald Kirsch | kirschh at lionbioscience.com | "How old is the epsilon?" LION bioscience | +49 6221 4038 172 | -- Paul Erd?s *** Please do not send me copies of your posts. *** From wealthychef at mac.com Fri Mar 15 12:07:46 2002 From: wealthychef at mac.com (Rich Cook) Date: Fri, 15 Mar 2002 09:07:46 -0800 Subject: readline() blocks after select() says there's data?? In-Reply-To: <15506.10262.578727.665781@12-248-41-177.client.attbi.com> References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: At 10:57 AM -0600 3/15/02, Skip Montanaro wrote: > Rich> I don't really need select to block. I just want it to be > Rich> accurate. If it returns a file object in the list of things which > Rich> are available, why should then readline() block on it? > >Remember that select() is lower level than readline(). As someone else >pointed out, select() may return because there is data available, but it >makes no promises about what that data is. Calling readline() may then hang >waiting for other conditions (presence of a newline in the input, for >example). So do I have to read the data byte by byte using read(1) and examine each character to avoid blocking? Is there any way to find out how much data is actually waiting for me in the file object so I can read it in bigger increments, or must I call select then read(1) for every byte? The reason I'm concerned is that I have two file objects (childerr and fromchild, actually) and I want to know right away if one has data. So I can't just call read on either one, because I may get blocked on one waiting for data from the other. But I'd like to avoid the char-by-char read if possible. -- -Sincerely, Rich Cook 925-784-3077 ******************************************************************* Sometimes it is said that man cannot be trusted with the government of himself. Can he, then, be trusted with the government of others? Thomas Jefferson ******************************************************************* From Pierre_Rouleau at ImpathNetworks.com Tue Mar 12 14:49:45 2002 From: Pierre_Rouleau at ImpathNetworks.com (Pierre_Rouleau at ImpathNetworks.com) Date: Tue, 12 Mar 2002 14:49:45 -0500 Subject: Can we use print to print to more than sys.stdout? Message-ID: <85256B7A.006CED33.00@Notes.ImpathNetworks.com> Wow! That's got to be why i like Python so much! Elegant, powerful and great community support with superfast turn-around time to get questions answered!!! Hope it would be like that for some well know Companies... Thanks ! "Jason Orendorff" on 03/12/2002 01:25:09 PM To: Pierre Rouleau/impath at impath, "python-list" cc: Subject: Re: Can we use print to print to more than sys.stdout? Pierre Rouleau wrote: > #1) Is it possible to change print behavior to make it print to several > streams? > > #2) > Is it also possible to define an object that would behave like a file > and that would do the printing itself to wherever required? # Sure. This code does both. class Mux: def __init__(self, *objects): self.__objects = objects def write(self, data): for obj in self.__objects: obj.write(data) def writelines(self, lines): for obj in self.__objects: obj.writelines(lines) myfile = open('somefile.txt', 'a') sys.stdout = Mux(sys.stdout, myfile) ## Jason Orendorff http://www.jorendorff.com/ From ykingma at accessforall.nl Mon Mar 18 15:53:43 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Mon, 18 Mar 2002 21:53:43 +0100 Subject: Python/JXTA References: Message-ID: <3C9653C3.5E048BCB@accessforall.nl> Gerhard H?ring wrote: > > * moxie [2002-03-17 16:54 -0800]: > > It may be a good idea to create Python bindings for > > JXTA (P2P [peer-2-peer] networking solution from Sun)... > > > > http://www.jxta.org/project/www/background.html > > Sure. Go on. > > Or just use Jython (IIRC the reference implementation was in Java). Which just means: from net import jxta Have fun, Ype From emile at fenx.com Fri Mar 22 06:55:07 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 22 Mar 2002 03:55:07 -0800 Subject: does anyone have any idea? References: Message-ID: Trung Hoang > this is so urgent :( > If you asked a question and we missed it, re-post the question. -- Emile van Sebille emile at fenx.com --------- From Gabe.Newcomb at noetix.com Thu Mar 14 20:00:44 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Thu, 14 Mar 2002 17:00:44 -0800 Subject: Good book on Python? Message-ID: <0C7CA8D8DF75494EB09AB6016990107FF08369@NOXMAIL.noetixad.com> For what it's worth, I have the older edition of Programming Python and I was, and am, really disappointed with it. It's random, not good to learn from, wordy, and too big! O'Reilly's books are usually so terse, but this one was ugly. It's like something published by WROX, except you don't have to see an 8x10 picture of the clown that wrote it on the cover. Gabe -----Original Message----- From: Federico Caboni [mailto:msx at crs4.it] Sent: Thursday, March 14, 2002 4:36 AM To: python-list at python.org Subject: Re: Good book on Python? On 14-03-2002 12:26, in article Pine.GSO.4.43.0203141117120.6137-100000 at muir, "Antonis C Koutalos" wrote: > > Hi there, > I would greatly appreciate information about a good book on python. I > have been programming C for a few years, but I know next to nothing about > python. Therefore, I would appreciate a book that describes the basics of > python as well as the more advanced features of the language. > > Thank you in advance! > > -A. > Hi, There are a lot of books about Python nowadays (and, yes,that's GOOD). I found "Python Essential Reference" by New Riders a very useful book (that is, if you want a brief but deep explanation of the language, Provided that you had previous programming experience with other Languages..) but, AFAIK, it's still based on Python 1.5.2. I recently bought "Programming Python" by O'Really, and I have to admit That I don't know if I like it. It's a very "strange" book, very diifferent from the more famous "Programming Perl". In my opinion it's more like a big cookbook. And...it assumes you already know the language. Maybe it can be useful if you already read Python Essential Reference or Learning Python. I hope you find this useful. Bye, ____ ____ ____ _ _ ____ _ _ ____ / ___)| __ \/ ___)/ /| | / ___)| \| |/ ___) Federico Caboni (msx at crs4.it) | (___ | /\___ \\__ | * \___ \| |\___ \ Software & Network Solutions \____)|_|\_\(____/ |_| (____/|_|\_|(____/ Phone: +39 070 2796 368 CRS4, Center for Adv. Studies, Research and Development in Sardinia -- http://mail.python.org/mailman/listinfo/python-list From dgallion1 at yahoo.com Sun Mar 10 18:55:29 2002 From: dgallion1 at yahoo.com (Darrell) Date: Sun, 10 Mar 2002 23:55:29 GMT Subject: Regular expressions newbie: something for templates References: Message-ID: >>> s="This is the test $var1$ and this is $var2$" >>> import re >>> re.sub("\$(.*?)\$","%(\g<1>)s",s) 'This is the test %(var1)s and this is %(var2)s' >>> --Darrell Thomas Weholt wrote: > Hi, > > I'm not getting the hang of regular expressions. All I want to do is this. > > Take string #1 : > > "This is the test $var1$ and this is $var2$" > > and turn it into > > "This is the test %(var1)s and this is %(var2)s" > > Any clues? > > ( And yes, yet another template system in the works ;-) ) > > Thomas From aahz at pythoncraft.com Mon Mar 25 15:19:59 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Mar 2002 15:19:59 -0500 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: In article , Huaiyu Zhu wrote: >On 24 Mar 2002 00:14:00 +0100, Martin v. Loewis wrote: >>>>> To maintain www.python.org, we use a web page templating system called >>>>> `ht2html', which transforms .ht template files into .html files. >>> >>> Is the source for this available? >> >>It's in the CVS. > >Is it very new? I've got a cvs copy a few weeks old, and it's not there. Try http://ht2html.sf.net -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From gh_pythonlist at gmx.de Sun Mar 31 21:14:35 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 04:14:35 +0200 Subject: PyOS -- was: Re: ANN: cage 1.0 -- Cellular automata engine in Python In-Reply-To: <3CA5194E.D5AB00E1@alcyone.com> References: <3CA5194E.D5AB00E1@alcyone.com> Message-ID: <20020401021435.GF333@lilith.hqd-internal> * Erik Max Francis [2002-03-29 17:47 -0800]: > Here's the latest PyOS installment: > [...] For one second I thought: "Hey cool - somebody wrote an operating system in Python." :-) This would be a nice exercise, IMO: use an existing kernel and C library, like Linux and glibc, then implement everything starting, including /sbin/init and the standard network servers (echo, finger, ...) in Python. Add a little Python shell and voila - the PyOS :-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.0 ?C Wind: 0.7 m/s From malletc3 at cti.ecp.fr Sun Mar 3 18:20:39 2002 From: malletc3 at cti.ecp.fr (DarkCed) Date: Mon, 4 Mar 2002 00:20:39 +0100 Subject: [newbie] Problem with os.system References: <1015194944.406831104@news.tpi.pl> Message-ID: I solved the problem by adding a proper python path in the script... I told you it was a newbie question :-) Ced From skip at pobox.com Sun Mar 24 15:24:23 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 24 Mar 2002 14:24:23 -0600 Subject: 2.2.1c1 platform experiences In-Reply-To: <3c9e2442@nntp.server.uni-frankfurt.de> References: <3c9e2442@nntp.server.uni-frankfurt.de> Message-ID: <15518.13815.727178.576008@12-248-41-177.client.attbi.com> >> I've attempted to summarise the reports of people using 2.2.1c1 on >> various platforms here: Mickey> Speaking of foreign or unusual platforms... does anyone have a Mickey> reliable build-script for building python on arm-linux ? No, but if "./configure ; make && make test" doesn't work for you, it would be helpful if you file a bug report at SF identifying what didn't work. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From paul at boddie.net Wed Mar 13 07:44:22 2002 From: paul at boddie.net (Paul Boddie) Date: 13 Mar 2002 04:44:22 -0800 Subject: Python embedded like PHP References: <3Nuj8.31472$l93.6215261@newsb.telia.net> Message-ID: <23891c90.0203130444.3d8a1a3b@posting.google.com> "Fredrik Lundh" wrote in message news:<3Nuj8.31472$l93.6215261 at newsb.telia.net>... > Rob Nikander wrote: > > Are there any projects out there that allow you to embed python in HTML > > like PHP? I like the PHP-style of embedding the bits of program in HTML, > > but I'd like to use python... > > start here: > > http://thor.prohosting.com/~pboddie/Python/web_modules.html The new recommended starting place is now here: http://www.boddie.org.uk/python/web_frameworks.html Take a look at the following page for more information on templates: http://webware.sourceforge.net/Papers/Templates/ Paul From m.faassen at vet.uu.nl Sat Mar 9 06:49:47 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 9 Mar 2002 11:49:47 GMT Subject: PEP 2, Procedure for Adding New Modules Message-ID: Hi there, With all the discussion on the further evolution of Python recently I decided to dig up my long-dormant proposal for PEP 2, 'Procedure for Adding New Modules' (to the standard library). So here it is again, with minor editing. I've also added another open issue involving the keeping of a list of head maintainers. I'll also pass it on to Barry so it can be actually included in the index of proposed PEPs. Note that currently this PEP stays away from technical issues and focuses on the organisational aspects of adding a new module and then maintaining it. It should be supplemented by a PEP detailing the technical procedure, if necessary (that includes tests and documentation requirements). Title: Procedure for Adding New Modules Introduction The Python Standard Library contributes significantly to Python's success. The language comes with "batteries included", so it is easy for people to become productive with just the standard library alone. It is therefore important that this library grows with the language, and that such growth is supported and encouraged. Many contributions to the library are not created by core developers but by people from the Python community who are experts in their particular field. Furthermore, community members are also the users of the standard library, applying it in a great diversity of settings. This makes the community well equipped to detect and report gaps in the library; things that are missing but should be added. New functionality is commonly added to the library in the form of new modules. This PEP will describe the procedure for the _addition_ of new modules. PEP 4 deals with procedures for deprecation of modules; the _removal_ of old and unused modules from the standard library. Finally there is also the issue of _changing_ existing modules to make the picture of library evolution complete. PEP 3 and 5 give some guidelines on this. The continued maintenance of existing modules is an integral part of the decision on whether to add a new module to the standard library. Therefore, this PEP also introduces concepts (integrators, maintainers) relevant to the maintenance issue. Integrators The integrators are a group of people with the following responsibilities: - They determine if a proposed contribution should become part of the standard library. - They integrate accepted contributions into the standard library. - They produce standard library releases. This group of people shall be PythonLabs, led by Guido. Maintainer(s) All contributions to the standard library need one or more maintainers. This can be an individual, but frequently is a group of people such as for instance the XML-SIG. Groups may subdivide maintenance tasks among themselves. One ore more maintainers shall be the _head maintainer_ (usually this is also the main developer). Head maintainers are convenient people the integrators can address if they want to resolve specific issues, such as the ones detailed later in this document. Developers(s) Contributions to the standard library have been developed by one or more developers. The initial maintainers are the original developers unless there are special circumstances (which should be detailed in the PEP proposing the contribution). Acceptance Procedure When developers wish to have a contribution accepted into the standard library, they will first form a group of maintainers (normally initially consisting of themselves). Then, this group shall produce a PEP called a library PEP. A library PEP is a special form of standards track PEP. The library PEP gives an overview of the proposed contribution, along with the proposed contribution as the reference implementation. This PEP should also contain a motivation on why this contribution should be part of the standard library. One or more maintainers shall step forward as PEP champion (the people listed in the Author field are the champions). The PEP champion(s) shall be the initial head maintainer(s). As described in PEP 1, a standards track PEP should consist of a design document and a reference implementation. The library PEP differs from a normal standard track PEP in that the reference implementation should in this case always already have been written before the PEP is to be reviewed for inclusion by the integrators and to be commented upon by the community; the reference implementation _is_ the proposed contribution. This different requirement exists for the following reasons: - The integrators can only properly evaluate a contribution to the standard library when there is source code and documentation to look at; i.e. the reference implementation is always necessary to aid people in studying the PEP. - Even rejected contributions will be useful outside the standard library, so there will a lower risk of waste of effort by the developers. - It will impress the integrators of the seriousness of contribution and will help guard them against having to evaluate too many frivolous proposals. Once the library PEP has been submitted for review, the integrators will then evaluate it. The PEP will follow the normal PEP work flow as described in PEP 1. If the PEP is accepted, they will work through the head maintainers to make the contribution ready for integration. Maintenance Procedure After a contribution has been accepted, the job is not over for both integrators and maintainers. The integrators will forward any bug reports in the standard library to the appropriate head maintainers. Before the feature freeze preparing for a release of the standard library, the integrators will check with the head maintainers for all contributions, to see if there are any updates to be included in the next release. The integrators will evaluate any such updates for issues like backwards compatibility and may require PEPs if the changes are deemed to be large. The head maintainers should take an active role in keeping up to date with the Python development process. If a head maintainer is unable to function in this way, he or she should announce the intention to step down to the integrators and the rest of the maintainers, so that a replacement can step forward. The integrators should at all times be capable of reaching the head maintainers by email. In the case where no head maintainer can be found (possibly because there are no maintainers left), the integrators will issue a call to the community at large asking for new maintainers to step forward. If no one does, the integrators can decide to declare the contribution deprecated as described in PEP 4. Open issues There needs to be some procedure so that the integrators always can reach the maintainers (or at least the head maintainers). This could be accomplished by a mailing list to which all head maintainers should be subscribed (this could be python-dev). Another possibility, which may be useful in any case, is the maintenance of a list similar to that of the list of PEPs which lists all the contributions and their head maintainers with contact info. This could in fact be part of the list of the PEPs, as a new contribution requires a PEP. But since the authors/owners of a PEP introducing a new module may eventually be different from those who maintain it, this wouldn't resolve all issues yet. Should there be a list of what criteria integrators use for evaluating contributions? (source code but also things like documentation and a test suite, as well as such vague things like 'dependability of the maintainers'). This relates to all the technical issues; checkin privileges, coding style requirements, documentation requirements, test suite requirements. These are preferably part of another PEP. Should the current standard library be subdivided among maintainers? Many parts already have (informal) maintainers; it may be good to make this more explicit. Perhaps there is a better word for 'contribution'; the word 'contribution' may not imply enough that the process (of development and maintenance) does not stop after the contribution is accepted and integrated into the library. Relationship to the mythical Catalog? Copyright This document has been placed in the public domain. From niemeyer at conectiva.com Mon Mar 4 19:58:30 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Mon, 4 Mar 2002 21:58:30 -0300 Subject: Python Embedding, stdin/-out redirection In-Reply-To: References: Message-ID: <20020304215830.A22871@ibook.distro.conectiva> > I'm just trying to embedd python in my 3D Engine > which works fine, except the problems with my console: > I'd like to do the > PyRun_InteractiveLoop(stdin, ""); > for my Engines console, because the python interactive > mode is just perfect. To make it as simple as possible > I redirected stdin/-out to 2 pipes which I read out > and print to my 3D window's console. Within my programm > all I/O stream releated stuff just works fine. > Mysteriously that doesn't work with python. > Below you see an example of what I tried: [...] I'm trying to understand the usefulness of python being run as an external process, since it won't be able to change your program's environment. What you probably want is to run python "inside" your game, right? If you have a game console, you probably have your own read/write routines. It's quite easy to implement your own interactive loop, with amazing results. Just have a look at Python/pythonrun.c, inside python source, and check PyRun_StringFlags() routine. To get the output back in your console, implement an object with a write() method, and replace sys.stdout and sys.stderr with it (PySys_SetObject() will do the job for you) Hint: if you want a behavior similar to the python interactive console, use Py_single_input when calling PyRun_StringFlags(), and be sure to implement a read/write attribute named 'softspace' in your output object. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From olc at ninti.com Sat Mar 30 19:56:23 2002 From: olc at ninti.com (Michael Hall) Date: Sun, 31 Mar 2002 10:26:23 +0930 (CST) Subject: CGI/modpython ??? In-Reply-To: Message-ID: Sorry folks, I just found the modpython docs, so I can RTFM. Still, I'd be interested in any comments about modpython versus Python CGI. Mick On Sun, 31 Mar 2002, Michael Hall wrote: > > I'm writing Python CGI scripts using the MySQLdb module and getting a > grasp on things fairly quickly ... Python is a cool language (I'm coming > to it from PHP). Thanks to Drew and Emile for sorting out my looping > function, it works fine now. > > Now I'm wondering how modpython is used. If Apache has the modpython > module installed, how do I use it? What form do scripts take? > > Do they still look like CGI scripts, or do they look more like a PHP > script (some sort of embedded scripting)? > > Does a script still use '#!/usr/bin/python', or are file endings (eg > .py) used to call the Python interpreter? > > Is the script located in public_html or cgi-bin? > > What would I have to do with a CGI script written in Python to use it with > modpython? > > Thanks > > ----------------------------- > Michael Hall mick at ninti.com > ----------------------------- > > > -- ----------------------------- n i n t i . c o m data driven development ----------------------------- Michael Hall mick at ninti.com ----------------------------- From hfoffani at yahoo.com Sat Mar 2 15:54:36 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: 2 Mar 2002 12:54:36 -0800 Subject: Status of PEP's? References: Message-ID: <1cef615e.0203021254.6bf3658@posting.google.com> Carel Fellinger wrote: > Jeff Hinrichs : > > > What you are asking everyone to agree with is: > > 5 = [0,1,2,3,4] > > No he isn't:) He explicitly says he doesn't think of sequences at all. Yes, but... The 'for' sentence in Python differs substantially from other languages. Besides the whitespace show it may be one of the first thing you learn in Python. From the tutorial: "Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence" And, to be fair, in the Ref. we read: "The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object" Newbies don't get that far reading docs, heh heh... The occasional/newbie programmer should not get the idea that Python's for loop behaves along the lines of Basic or Fortran. I would like that the concept of the for construction as we know it is as clear as possible. So, if the PEP progress it should go along with a BIG notice that in Python positive integers are iterable objects (or, more precisely, that they follow the iter protocol.) Thinking in practical terms, I'm more in favour of an indici(seq_or_iter) builtin function and/or an inditems(seq_or_iter) one as someone proposed. for n in indici(set): for n, datum in inditems(set): Also, we should work implementing the iter interface in old code so we can see more things like: for row in resultSet: print row.attribute so there is no need of xrange(seq.getCount()) / seq.get(n) pairs. indici(x) will replace the odd xrange(len(x)) idiom and address the problem of open intervals where the length of the set is not known in advance. But I fail to see how to apply this solution naturally on sets that have several different main 'walking' directions like arrays or like the sample in the PEP. If the 'table' object has symmetry between two (or more) axes, then indici(table) is ambiguous. Regards, -Hernan From claird at starbase.neosoft.com Wed Mar 20 10:17:45 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 20 Mar 2002 09:17:45 -0600 Subject: Java and Python employment prospects (was: Java and Python) References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> Message-ID: <4CFAF0C0B33691F4.3834C641951F9CBE.EF865BE046133EE8@lp.airnews.net> In article <3C981961.9F5E5383 at engcorp.com>, Peter Hansen wrote: >Ahmed Moustafa wrote: . . . >> I'm interested in knowing which skills will(are) being looked for. . . . >3. The best support for either Java or Python is probably in >their respective newsgroups. Python's is widely known as being >one of the most polite and helpful. The language has been . [a great deal of useful and correct information] . . >Here's my best answer to you: I happen to hire programmers >to work on my team in a wireless telecom company. Although >we happen to have chosen to use Python in addition to C and >a few minor languages like Javascript and Assembly, where >necessary, the language we use is hardly the most important >thing. > >Communication skills are, first and foremost, the thing I >look for in hiring. This includes the softer social skills >like how to work in a team and put aside one's programming >ego. Next are adaptability, as in how easily someone can >pick up new skills and apply them effectively. Design >skills are useful. Debugging skills are very valuable, >though rather unfortunately rare. Probably some others >that don't come to mind in today's economy (we're not >hiring now :-). > >Way, way down the list of things I look for in a resume >is the programming languages a candidate has. Not entirely . . . >Not all companies hire in this way, of course, but all >the best ones do. :-) > >-Peter > >P.S.: If you are considering Python as a massive growth >area where ex-Java programmers can go to get lucrative >jobs, you're bound to be disappointed. As in programming, >there is no silver bullet. I feel a need to reinforce some of what Peter has written. Understand clearly that many, many organizations do NOT hire based on anything like the criteria Peter describes. They instead process candidates based narrowly on "certifications", alleged language experience, and so on. Of course these are not the best employers; they are, in my experience, the over- whelming majority. Yes, comp.lang.python has a deserved reputation for its cor- diality and effectiveness. Incidentally, I have personal knowledge of a prestigious educational institution that's working on a training unit whose purpose I feel I can fairly paraphrase as, "Python for Java programmers who seek a 'silver bullet' for their founder- ing careers". This stuff happens. Peter's fighting powerful social forces by writing and managing his company so wisely. I think a decision to seek career counseling in comp.lang.java [sic] and comp.lang.python is ... well, perhaps it's best to express it this way: my reading of c.l.p is that few of the participants claim expertise in the specialty of "drive-by" career counseling. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From test at biggulp.readfreenews.net Fri Mar 1 23:03:47 2002 From: test at biggulp.readfreenews.net (test) Date: Sat, 2 Mar 2002 14:03:47 +1000 Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: <3c804f7b$0$4215$afc38c87@news.optusnet.com.au> Backtalk is another python-based framework. http://sourceforge.net/projects/backtalk/ From cfelling at iae.nl Sat Mar 30 17:40:05 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 30 Mar 2002 23:40:05 +0100 Subject: PEP 285: Adding a bool type References: Message-ID: Terry Reedy wrote: ... > Proposed amendment: call the new type 'truth' instead of 'bool' and > change the title of the PEP to "Formalizing a Python truth type". ...lots of arguments snipped A *very* good idea. -- groetjes, carel From nhodgson at bigpond.net.au Wed Mar 13 22:33:30 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 14 Mar 2002 03:33:30 GMT Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> <3C8F1D74.10802@mxm.dk> <20020313092857.4765dd0d.logiplexsoftware@earthlink.net> <3C8FF468.408183B2@engcorp.com> Message-ID: Gerhard H?ring: > You're of course right. Has anybody tried their .NET SDK, > yet. Does it contain a usable commandline version of VC++7? The .NET SDK contains a usable compiler but as mentioned it does not optimize. You may need to download extra include and library files such as those provided by the Platform SDK which is also free. I already had these from an earlier version of Visual C++. You may also need a version of STL such as the free STLPort. The code produced is not fast or small but works well enough for applications that are not performance sensitive. The mingw version of gcc and Borland's free C++ compiler are packaged better than the free version of Microsoft's compiler and they include optimization. Neil From ctp at ctpdesign.com Sat Mar 23 02:27:04 2002 From: ctp at ctpdesign.com (Christopher Palmer) Date: Fri, 22 Mar 2002 23:27:04 -0800 Subject: simple question In-Reply-To: <2UVm8.30655$J54.1855090@news1.west.cox.net> References: <2UVm8.30655$J54.1855090@news1.west.cox.net> Message-ID: Let's say I have a variable called a and a contains an integer, say 4522 and I want 4, 5, 2, and 2 to be items in a list instead of an integer... I know it must be dirt simple, but nothing I have tried so far has worked. Thanks in advance, CTP From oinkfreddie at oinkmadcowdisease.oinkorg Sun Mar 31 22:40:35 2002 From: oinkfreddie at oinkmadcowdisease.oinkorg (Freddie) Date: Mon, 01 Apr 2002 03:40:35 GMT Subject: Python socket problems Message-ID: Hi, I'm having quite a bit of trouble with some code I've written in Python recently. The program itself is an offer bot (think iroffer), and it uses python-irclib to handle the IRC stuff. There's a thread that handles DCC SEND transfers using select and non-blocking sockets. The problem is, if several sends are active (say, using ports 31000 through 31002), starting a new send will quite often cause earlier sends to time out. I have no idea what this problem is, it doesn't _seem_ to be a call blocking (for 90 seconds?). I've tried starting a single thread per send, but that seemed to create more problems than it solved (file read calls returning nothing, when they weren't EOF?). Anyone have any idea? I can send the relevant code parts via e-mail, if you need them. Thanks, Freddie -------------------------------------------------------------- Remove the oinks from my e-mail address if you really want to From ack at ee.ed.ac.uk Thu Mar 14 06:26:01 2002 From: ack at ee.ed.ac.uk (Antonis C Koutalos) Date: Thu, 14 Mar 2002 11:26:01 +0000 Subject: Good book on Python? Message-ID: Hi there, I would greatly appreciate information about a good book on python. I have been programming C for a few years, but I know next to nothing about python. Therefore, I would appreciate a book that describes the basics of python as well as the more advanced features of the language. Thank you in advance! -A. From rjk at grauel.com Fri Mar 22 13:28:48 2002 From: rjk at grauel.com (Richard J. Kuhns) Date: 22 Mar 2002 18:28:48 GMT Subject: A question about generators References: <3C9A87F5.8EA76936@cosc.canterbury.ac.nz> Message-ID: <85d6xwe9t6.fsf@moriarity.grauel.com> Greg Ewing writes: > Richard J Kuhns wrote: > > > > That's EXACTLY what I did :). The main reason I had problems to start with > > is that almost everything I've done with python feels more-or-less > > "elegant", and this doesn't. > > Well, generators weren't designed for the sort of problems > that require restartability. > > Is there some reason you absolutely can't just create > a new instance of the generator each time you need > to restart? That would be the most elegant way, > if you can manage it. > No, there's no reason I couldn't create a new instance each time. I'd started out trying to find a simple way to implement something that's only rarely going to be used in this particular app, and it turned out to be hairier than I'd expected. After I get this app running I'll probably revisit it, but since it *is* working right now... You know, `good enough' is the enemy of `the best'. -- Richard Kuhns rjk at grauel.com PO Box 6249 Tel: (765)477-6000 \ 100 Sawmill Road x319 Lafayette, IN 47903 (800)489-4891 / ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With NINE Servers In California And Texas - The Worlds Uncensored News Source From fredrik at pythonware.com Wed Mar 20 14:08:09 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 20 Mar 2002 19:08:09 GMT Subject: module for assessing gray levels of gray level bitmap? References: <3C987942.9060309@web.de> Message-ID: Oliver Pust wrote: > is there a module for assessing the gray levels of gray level bitmap? I > am thinking of a module that allows to open a bmp-file and stores the > gray levels of each pixel in form of a matrix e.g. gray_level[x,y]. http://www.pythonware.com/products/pil/index.htm from PIL import Image im = Image.open("myimage.bmp") print im.getpixel((x, y)) From martin at v.loewis.de Sun Mar 31 05:28:59 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 12:28:59 +0200 Subject: PEP 285: Adding a bool type References: Message-ID: philh at comuno.freeserve.co.uk (phil hunt) writes: > That *is* a valid reason. However, it must be decided whether > Python's primary goal is to be easy to learn or easy to use. I think this has been decided; many educators are interested in using Python in school (at all levels of education). > This proposal makes it easier to learn in some respects, but adds > difficulty as well, as the user must learn a new data type, albeit > a rather simple one. This should not be a problem. The notion of boolean values must be understood, anyway, and wordings like "[],{},None, ..., 'count as true'" are more easy to understand (IMO) if there really is the thing they count as. Regards, Martin From fredrik at pythonware.com Fri Mar 15 13:36:55 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 15 Mar 2002 18:36:55 GMT Subject: Threading/TkInter problems with Buttons. References: <4378fa6f.0203141407.9b20050@posting.google.com> Message-ID: Marc wrote: > I was trying to start a thread from a button to find that it would not > work. The problem was that every time I started the application, the > thread would automatically kick off: can you spot the the difference between those two lines: > self.Go["command"] = self.thread1.start() > self.Go["command"] = self.go_thread (in the first case, you're calling the function, and assign the return value to the command option... in the second case, you're doing the right thing) From lac at strakt.com Wed Mar 6 08:32:31 2002 From: lac at strakt.com (Laura Creighton) Date: Wed, 06 Mar 2002 14:32:31 +0100 Subject: Brewster's Factor - was :Trouble running programs In-Reply-To: Your message of "Tue, 05 Mar 2002 00:38:29 MST." <3C8475F4.46E94132@3captus.com> References: <200203041148.g24BmttB007592@ratthing-b246.strakt.com> <3C8475F4.46E94132@3captus.com> Message-ID: <200203061332.g26DWVtB014395@ratthing-b246.strakt.com> Ok, Brewster's Angle it is! Thank you. Laura Creighton From peter at engcorp.com Tue Mar 26 22:31:31 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Mar 2002 22:31:31 -0500 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: <3CA13D13.3C134F88@engcorp.com> Emile van Sebille wrote: > As to finding it at http://ht2html.sf.net, I didn't find it either first > time through as I didn't look closely enough at the ht2html at SourceForge > to distinguish it from an e-mail address. Now that I think of it, this was definitely something that confused me for a moment until my desperation forced me to move the mouse over it. And that was the third time I visited the site. The first two times I believe I simply assumed it was email and ignored it. Suggestion to site author: remove "@" and reword to suggest more strongly that this is the link to the real SourceForge site and you'll have more "customers". -Peter From nospam at mega-nerd.com Sun Mar 10 17:59:03 2002 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sun, 10 Mar 2002 22:59:03 GMT Subject: Modulo operator : differences between C and Python Message-ID: <3C8BE537.74E55963@mega-nerd.com> Hi all, Just recently I prototyped a relatively complex algorithm in Python before converting it to C. During this conversion I noticed that the modulo operator returns different results in C and Python if the numerator is negative. For positive values they produce the same result. ---------------------------------------------------------------- erikd at coltrane > python Python 2.1.2 (#1, Jan 18 2002, 18:05:45) [GCC 2.95.4 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> 123 % 12 3 >>> -123 % 12 9 >>> erikd at coltrane > cat mod_test.c #include int main (void) { int a = 123 ; printf (" % d %% 12 == %d\n", a, a % 12) ; printf (" % d %% 12 == %d\n", -a, -a % 12) ; return 0 ; } erikd at coltrane > gcc -Wall mod_test.c -o mod_test erikd at coltrane > ./mod_test 123 % 12 == 3 -123 % 12 == -3 ---------------------------------------------------------------- Anybody have any idea why this is? Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ The government everybody loves to abuse sues the company everybody loves to hate. Throw in a bunch of faceless lawyers cross-examining techies [with] all the charisma of a video driver and you've got a spectacle of thoroughly miniscule proportions. From gh_pythonlist at gmx.de Wed Mar 13 19:15:18 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 14 Mar 2002 01:15:18 +0100 Subject: data persistent from run In-Reply-To: References: Message-ID: <20020314001517.GC1347@lilith.hqd-internal> Le 13/03/02 ? 15:22, Bob Roberts ?crivit: > What is the best way to keep data like window size and position for > the next time I run the program? I know in win2k, stuff like that is > usually stored in the registry. Are there any python commands to > store such information in a platform-independent manner? I'd just store the settings in the user's home directory. This leads us to the next problem: where's the home directory, which has come up several times on this mailing list, with no 100 % satisfactory solution for the various Windows flavours, IIRC. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 8.6 ?C Wind: 2.3 m/s From les_ander at yahoo.com Fri Mar 1 18:22:21 2002 From: les_ander at yahoo.com (les ander) Date: 1 Mar 2002 15:22:21 -0800 Subject: string to dictionary Message-ID: Hi, i have a list of strings like this: aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3',...] i want to convert this to a dictionary with a_i -> b_i without using loops (it is trivial to do it with loops) i tried this dict={} map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList) but it complains that "keyword can't be an expression" can someone please help me get this right? thanks les From grey at despair.dmiyu.org Thu Mar 7 16:56:00 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 07 Mar 2002 21:56:00 -0000 Subject: PEP 284, Integer for-loops References: <3c87d103.26130283@news.laplaza.org> Message-ID: On Thu, 07 Mar 2002 13:47:49 -0800, David Eppstein wrote: > But there are a few warts in the design, where instead of just using Python > I have to stop and explain some unnatural unintuitive syntax. You keep using that word. I do not think it means what you think it means. You killed my language, prepare to die! -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From daniel at dittmar.net Wed Mar 13 14:39:25 2002 From: daniel at dittmar.net (Daniel Dittmar) Date: Wed, 13 Mar 2002 20:39:25 +0100 Subject: Why Don't Scripts Run ? References: <3C8F9C59.F9408D47@mcn.net> Message-ID: <3C8FAAED.8030905@dittmar.net> > 'python script.py' > > completely fails (syntax error). This is the only way I If you're getting a SyntaxError like below [0] h:\tmp >python script.py File "", line 2 impor something ^ SyntaxError: invalid syntax then your Python is working just fine, there is only a mistake in your script. Daniel From peter at engcorp.com Fri Mar 1 06:31:55 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Mar 2002 06:31:55 -0500 Subject: Want to monitor process.. References: <87550ef1.0202272315.15779bbd@posting.google.com> <97ae44ee.0202280901.3153bdfc@posting.google.com> <3C7EC9C6.D11FB17@engcorp.com> <97ae44ee.0203010102.14ebf2bb@posting.google.com> Message-ID: <3C7F66AB.D51BEA03@engcorp.com> Stephen wrote: > > > Yikes! "Crash"? Do you really mean they crash the Python interpreter, > > or do you mean they exit with an exception? > > Sorry, I guess I mean "exit with an exception" though to be honest, I > still don't know because I haven't been able to run the programs > interactively during a 'crash'. I'm not sure what the interactive thing would add, since the interpreter will already print exception tracebacks to the console whenever your program exits exceptionally. If you aren't seeing a traceback, maybe you aren't really exiting with an exception. > > If the latter, just wrap the highest level code with a try/finally > > or try/except and put code in to ensure the child processes are > > properly terminated. Simple, clean, safe. > > Will do. I didn't want to put try/except/finally at the highest level > of code yet since we're actually in Beta and I want to know when my > server encounters a problem. No problem, just put a "raise" statement as the final statement in the exception handling block (when using try/except only) and you'll still propagate the exception up and right out of the interpreter so it prints a traceback to the console. In the try/finally case, however, you'll still get the traceback if an exception *did* occur, because the interception is only a temporary one. After the finally code executes, exception processing continues on. > Problem has been that not running it in > interactive mode, I've missed the reasons for the failures. That's > why I also asked about logging recently. Logging is good, but shouldn't be absolutely essential to catch a serious exception. The interactive mode should be entirely unnecessary and, as you suggest, gets in the way of normal execution. I think you might focus on the lack of a traceback. You should always see one if you aren't explicitly swallowing the exception. (Note, a few standard modules such as the SocketServer and such will internally swallow exceptions in the server threads by default.) -Peter From theller at python.net Wed Mar 20 04:06:04 2002 From: theller at python.net (Thomas Heller) Date: Wed, 20 Mar 2002 10:06:04 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: "Magnus Lie Hetland" wrote in message news:slrna9fqje.k50.mlh at vier.idi.ntnu.no... > In article , Chris Liechti wrote: > >mlh at vier.idi.ntnu.no (Magnus Lie Hetland) wrote in > >news:slrna9fkli.9ti.mlh at vier.idi.ntnu.no: > > > [snip] > > > >as i understand py2exe it does exactly that. it adds a new target > >"py2exe" so that disutils have a new target name. > > > >i.e "python setup.py py2exe" generates the exe+dlls in the dist dir > > Yes, I realise that, but... > > 1. It only works on Windows; working on all platforms (as when > compiling extensions with distutils) would be desirable; Gordon's installer also works on linux (and solaris?). Myself I'm only working on windows, so there is no need for me to extend py2exe to work on linux systems. If anyone is willing to provide patches for linux (or other systems), and is willing to maintain them, I will happily add him as developer ;-). Thomas From phr-n2002a at nightsong.com Mon Mar 25 06:02:58 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 25 Mar 2002 03:02:58 -0800 Subject: Root access with python References: Message-ID: <7x663krjtp.fsf@ruckus.brouhaha.com> mtaylor at lowebroadway.com (Moray Taylor) writes: > I want to know how to run a 'root' command with python, i.e. mounting > an NFS drive. > > On the terminal, you would do a 'su', type your password, then enter > the command you wanted to run. How is this achieved within Python? > > My purpose is to make a small GUI app with PyQT to make mounting NFS > volumes easier, I can handle the GUI bit, but I don't understand how > to 'su'. > > Thanks for any help Don't try to do that unless you REALLY know what you're doing with security implementation. Instead, run "su" the usual way and type your password to get a root shell, then launch your GUI app from the root shell. From bokr at oz.net Sun Mar 24 21:09:16 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Mar 2002 02:09:16 GMT Subject: 2.2 open References: Message-ID: On Sun, 24 Mar 2002 18:53:41 -0500, Tim Peters wrote: >[Martin v. Loewis] >> Correction: open is file. Just try it >> >> >>> open is file >> 1 >> >> So open is the type of file objects. > >Na, file is the type of file objects: > >>>> type(sys.stdout) > >>>> type(sys.stdout).__name__ >'file' > >"open" was made identical to "file" just so open(filename) would continue to >work as before. Once you get used to it, it's more natural to say >file(filename) in 2.2 (for much the same reason it's long been more natural >to say int("42") than string.atoi("42")). > >>> id(open),id(file),open==file (503978992, 503978992, 1) Really identical, it seems. BTW, I was playing around classifying things in __builtins__ according to type(thing).__name__: >>> sys.version '2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)]' >>> d={} >>> for k,v in __builtins__.__dict__.items(): ... vn = type(v).__name__ ... if d.has_key(vn): d[vn].append(str(k)) ... else: d[vn] = [str(k)] ... >>> for k in d.keys(): print k ... instance builtin_function_or_method str int ellipsis NotImplementedType type class NoneType >>> def pl(alist,cols=None,width=78): ... fmt= '%%%ss' % (cols and width//cols-1 or '',) ... for i in xrange(len(alist)): ... if not cols: ... print alist[i] ... else: ... if not i%cols: print ... print fmt % alist[i], ... >>> >>> pl(d['instance'],3) help credits copyright license >>> pl(d['str'],3) quit __doc__ exit __name__ >>> pl(d['int'],3) __debug__ >>> pl(d['ellipsis'],3) Ellipsis >>> pl(d['NotImplementedType'],3) NotImplemented >>> pl(d['NoneType'],3) None >>> pl(d['class'],4) RuntimeError MemoryError StopIteration UnicodeError LookupError ReferenceError NameError ImportError SystemExit Exception StandardError SystemError IOError IndexError RuntimeWarning SyntaxWarning Warning ArithmeticError KeyError EnvironmentError DeprecationWarning FloatingPointError OverflowWarning ValueError EOFError TabError SyntaxError OSError IndentationError AssertionError TypeError KeyboardInterrupt UserWarning ZeroDivisionError UnboundLocalError NotImplementedError AttributeError OverflowError WindowsError >>> ... all the exceptions appear to be type 'class'. Are they slated to become object-based? >>> pl(d['builtin_function_or_method'],4) vars pow globals divmod apply isinstance zip hex chr __import__ input oct repr hasattr delattr setattr raw_input iter compile reload round dir cmp hash xrange reduce coerce intern issubclass unichr id locals slice min execfile getattr abs map buffer max len callable eval ord filter range >>> pl(d['type'],4) float unicode open super long complex dict type tuple list str property int file object _ classmethod staticmethod >>> ... sort of interesting, FWIW. Has someone done a proper showinfo(x) utility to do this kind of thing for various objects? Hard to believe not. Regards, Bengt Richter From bokr at oz.net Fri Mar 29 14:19:15 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Mar 2002 19:19:15 GMT Subject: Python 2.2 chr representation errors with embedded C References: Message-ID: On Fri, 29 Mar 2002 09:12:08 -0500, "Mark Szigety" wrote: >Hello, > >I have recently made the upgrade to Python 2.2 from 1.5.2. In the >Python application which I develop, we have several embedded C >functions, one of which is a simple function to convert a hex string to >octal--it simply chars each byte and returns the new buffer. However, I What do you mean "hex string" and "to octal" ? is this a string->string conversion, changing a hex string representation of an integer to an octal string representation of the same integer, or what? Please define your terms. Since it's so simple, why not post the actual code you're having trouble with?? >have noticed a 0.01% error rate in Python 2.2 which I did not see in >Python 1.5.2 (it was 100% accurate). That is, 1 out of 10,000 hex >strings will be converted incorrectly in the C function, usually one >byte is returned as \x00 instead of what is should be. I also have >noticed that in Python 2.2, chr(0xff) returns \xff instead of \377 in >Python 1.5.2. Could this be the source of the communication breakdown? > >I should mention that writing a similar conversion function totally in >Python is 100% accurate in Python 2.2 as well as Python 1.5.2, although >it is an order of magnitude slower. > >Any information about the apparent source of this issue would be >appreciated! I dislike playing 20-questions games when being asked to help. I guess I should have eaten a better breakfast ;-/ Regards, Bengt Richter From neal at metaslash.com Sun Mar 31 19:03:30 2002 From: neal at metaslash.com (Neal Norwitz) Date: Sun, 31 Mar 2002 19:03:30 -0500 Subject: Accessing CVS on SourceForge? References: Message-ID: <3CA7A3D2.F37314D6@metaslash.com> Samuel Schulenburg wrote: > > How do you access a particular python realease on SourceForge? I can > obtain the latest realease by following the instruction provided at > SourceForge, but I would like to obtain Python2.2 or 1.52. cvs upd -r r221 # when it's available in about a week cvs upd -r r221c2 # most recent version 2.2.1 RC2 cvs upd -r release22 # 2.2 cvs upd -r r152 # 1.5.2 to find out what the tags are do: cvs log Objects/intobject.c # or any other file Neal From jim.vickroy at noaa.gov Wed Mar 6 16:25:47 2002 From: jim.vickroy at noaa.gov (j vickroy) Date: Wed, 6 Mar 2002 14:25:47 -0700 Subject: Dictionaries in Lists References: Message-ID: Nothing wrong with the idea. Did you specify: > Info = {'IName':"Voodoo2",'IDescription':"blahblah"} or what you posted (which had some syntax errors)? "Avi Homes" wrote in message news:ayvh8.55100$6j2.3265866 at typhoon.austin.rr.com... > I was attempting to make a list of dictionaries, which to me feels like the > C equivlant of an array of structs, kind of. anyway, after making a > dictionary and putting some values into it, and trying to append it to a > list, python is not liking this. Am I approaching the idea the wrong way? i > would like to keep the data organized as dictionaries.. the code looked > something like > > Info{'IName':"Voodoo2",'IDescription':"blahblah} > Listing=[] > Listing.append(Info) > > > > From jar at mminternet.com Wed Mar 13 13:08:08 2002 From: jar at mminternet.com (James A Roush) Date: Wed, 13 Mar 2002 10:08:08 -0800 Subject: Converting relative URLs to absolute References: <23891c90.0203130331.6f030f5b@posting.google.com> Message-ID: In article <23891c90.0203130331.6f030f5b at posting.google.com>, paul at boddie.net says... > Fernando P?rez wrote in message news:... > > James A Roush wrote: > > > > > Does anyone have any code that, given that absolute URL of a web page, can > > > convert all the relative URLs on that page to their absolute equivalent? > > > > Assuming absolute is a string and relative_list a list of strings, the > > followinng comes to mind: > > > > [absolute+'/'+relative for relative in relative_list] > > > > Maybe you wanted something fancier, don't know. > > I suppose it would be nicer or more appropriate to deal with "back > references" as well as being able to detect "base" elements. For > example, given the following "base"... > > http://www.python.org/invented/framework/demo/ > > ...and the following URLs... > > moreinfo.html > docs.html > ../apps.html > ../../stuff.html > /index.html > http://www.zope.org > > ...one would want to remove certain parts of the "base" before > concatenating the relative URLs to it. Thus, we would produce these > absolute URLs: > > http://www.python.org/invented/framework/demo/moreinfo.html > http://www.python.org/invented/framework/demo/docs.html > http://www.python.org/invented/framework/apps.html > http://www.python.org/invented/stuff.html > http://www.python.org/index.html > http://www.zope.org > > I'm not so sure that urllib supports such operations, at least not in > any version of it that I have (from Python 2.0 or 2.1). Instead, > there's some fairly low-level split operations which aren't especially > useful in this case. In addition, you might need to use some parser to > get hold of any "base" elements in the HTML. > > I've written some page-mining tools which help with these kinds of > activities, and I suppose I should get round to releasing them at some > point. Let me know if you're interested! > > Paul This precisely what I'm looking for. As someone else pointed out in another post, urllib should have this but, sadly, does not. -- ----------------------- James A Roush jar @ mminternet.com ----------------------- From logiplexsoftware at earthlink.net Wed Mar 6 17:10:43 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 6 Mar 2002 14:10:43 -0800 Subject: Threading help? In-Reply-To: <20020306132612.4a5d756a.logiplexsoftware@earthlink.net> References: <3C867E68.B4C3FED2@accessforall.nl> <20020306132612.4a5d756a.logiplexsoftware@earthlink.net> Message-ID: <20020306141043.756855f4.logiplexsoftware@earthlink.net> On Wed, 6 Mar 2002 13:26:12 -0800 Cliff Wells wrote: > The approach I would take, based upon the information given, is to have > thread A retrieve the data every .1s (using time.sleep), when the data is > retrieved, put it on a Queue and go back to sleep. Thread B blocks on the > Queue until data is available. When data becomes available, B processes > that data and place it on a second Queue for thread C (thread C handling > HTTP requests) to deal with. Hm. Okay, I had to reconsider this. Clearly if the processing is slower than .1s and data is being added to it every .1s, the Queue is going to endlessly grow as more data is added to it. If this is the case, it might make sense to have more than one consumer thread (B) doing the processing. Also, if thread C is only interested in serving up the latest results, then rather than a Queue between threads B and C, I think I would use a shared object (protected by locks) for holding the last result. Thread C could simply take a copy of this object when it gets a HTTP request. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From amrit040 at yahoo.com Thu Mar 14 02:58:27 2002 From: amrit040 at yahoo.com (Amrit) Date: 13 Mar 2002 23:58:27 -0800 Subject: telnet References: Message-ID: <71c0a06e.0203132358.760f2444@posting.google.com> Try nslookup >From the man page """ ls [option] domain [>> filename] List the information available for domain, optionally creating or appending to filename. The default output contains host names and their Internet addresses. Option can be one of the follow ing: """ A. "M.Beis" wrote in message news:... > Hello everybody, > > I'm connected to a network with a number of telnet servers. I want to get a > list with the names (hostnames) of each availiable server. > > Any ideas?? > > Thanks > > Mike From stephen at xemacs.org Mon Mar 4 21:28:26 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 05 Mar 2002 11:28:26 +0900 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87n0xn21f9.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Bengt" == Bengt Richter writes: Bengt> With internal UTF-8 ordinary-string default encoding, I Bengt> think there would be a need for a plain old octet string as Bengt> a different type Already in my proposal, I think. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From evil_wicked at ofir.dk Wed Mar 13 12:54:11 2002 From: evil_wicked at ofir.dk (henrikb666) Date: Wed, 13 Mar 2002 17:54:11 -0000 Subject: Newbie: Undefined reference when initializing Python Message-ID: Please bear with me: I'm a hobby programmer who has been coding C and C++ for a couple of years under Linux RH 6.2 and I just know how to use Emacs and the most useful commands under Linux. Now I'd like to use Python embedded in a C++ program, but am not sure the program is installed properly. This is what I did so far: 1. DOwnload the V2.2 Python tar.gz 2. gunzip 3. tar -xvf 4. ./configure 5. make 6. as root: make install THe idea is now to do the following from the C++ code: void TServer::boot(void) { ... // Initialize Python. Py_Initialize(); ... } But this error occurs: [pos at localhost mymud]$ make g++ -I/home/pos/mymud/include/ -I/home/pos/xerces-c1_6_0- linux/include/ -I/home/pos/Python-2.2/ -I/home/pos/Python- 2.2/Include -g -c src/TServer.cc g++ -g -o mymud main.o TServer.o TDesc.o TChar.o TWorld.o Utility.o TCommand.o Constants.o TBase.o TPc.o TRoom.o TExit.o TMob.o TMobProtoFactory.o TZone.o Movement.o TXMLHandler.o TEvent.o - L/home/pos/xerces-c1_6_0-linux/lib -lxerces-c1_6_0 TServer.o: In function `TServer::boot(void)': /home/pos/mymud/src/TServer.cc:85: undefined reference to `Py_Initialize' collect2: ld returned 1 exit status make: *** [mymud] Error 1 I already include at the top of the TServer.cc file, so that's not it. Could it have something to do with my Makefile? Any help is appreciated as a search for "newbie" in the archive here didn't turn up anything relevant to this problem. Thanks for reading, Henrik Jensen From justin at iago.org Fri Mar 1 12:14:54 2002 From: justin at iago.org (Justin Sheehy) Date: Fri, 01 Mar 2002 12:14:54 -0500 Subject: Minor, minor style question In-Reply-To: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> (claird@starbase.neosoft.com's message of "1 Mar 2002 10:39:42 -0600") References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: claird at starbase.neosoft.com (Cameron Laird) writes: > Why would I prefer > string = "" > string = string + "abc " > string = string + "def " > string = string + "xyz" > over > string = "abc " + \ > "def " + \ > "xyz" > ? If those really are the two things being compared, there's a far better option: >>> string = ("abc" ... "def" ... "xyz") >>> string 'abcdefxyz' > I see a lot of the former in contexts I associate > with Visual Basic- or JavaScript-majority folkways. > Is there an attraction to the redundancy (and fragil- > ity!) I'm missing? Are \-s *so* deprecated? I can't stand either of the two styles you quoted. They are both ugly and more work than is needed. The first one also creates a potentially large number of wasteful intermediate strings. -Justin From m.faassen at vet.uu.nl Tue Mar 5 07:13:48 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 5 Mar 2002 12:13:48 GMT Subject: Minor, minor style question References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: Cameron Laird wrote: > Why would I prefer > string = "" > string = string + "abc " > string = string + "def " > string = string + "xyz" > over > string = "abc " + \ > "def " + \ > "xyz" > ? I see a lot of the former in contexts I associate > with Visual Basic- or JavaScript-majority folkways. > Is there an attraction to the redundancy (and fragil- > ity!) I'm missing? Are \-s *so* deprecated? > -- Note that a very pleasant alternative for strings in Python is: s = ("abc " "def " "xyz") Frequently the brace context is already taken care of anyway, such as in function calls: f("foo " "bar " "baz", 1, 15) Generally I try to avoid \ using tricks like this, though I'm not religious about it. Sometimes a backslash is nicest. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From ianb at colorstudy.com Tue Mar 19 15:03:46 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 19 Mar 2002 12:03:46 -0800 Subject: Python embedded like PHP References: Message-ID: <359f85cd.0203191203.2a8e4bd@posting.google.com> Andrew McNamara wrote in message news:... > Albatross encourages (but doesn't enforce) the separation of presentation > and logic. You might do something like this in Albatross: > >
      > >
    • >
      >
    Why, oh why, does it use HTML-like syntax? People keep implementing templating languages that do this over and over, and it's a bad, bad idea. Any moderately complex example of templating will violate the rules of HTML/SGML, with things like ">, which is horrible to read, will anger WYSIWYG editors to no end, and isn't at all necessary. All you have to do is use [] instead of <> -- it look about the same, will have all the good cognitive associations (how nesting works, etc), but is orthogonal to HTML, just like your templating system is orthogonal to HTML. I.e., you're templates would look like
      [al-for iter="reptile" expr='["Crocodile", "Python"]']
    • [al-value expr="reptile.value()]
    • [/al-for]
    This still causes problems with repeating table lines (since they'll be [al-for...] text between
    reads pretty well, and should make some intuitive sense even if you don't understand the scripting itself. All attributes are kind of hidden, and the dynamic statement is no more hidden than the thing it is replacing. Also, you're left with a mostly-intact tag -- al-td isn't an HTML tag, and software that understands HTML won't understand that tag. That means you can't preview the unrendered code in a browser and you can't let a WYSIWYG editor touch it. Ian From sjmachin at lexicon.net Fri Mar 1 00:32:06 2002 From: sjmachin at lexicon.net (John Machin) Date: 28 Feb 2002 21:32:06 -0800 Subject: ASV module, CVS modules References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: ron at ire.org (ron nixon) wrote in message news:<61ff32e3.0202281525.3e9bb102 at posting.google.com>... > Hello, I'm trying to use either of these two modules ASV by Laurence > Tratt at http://tratt.net/laurie/python/asv/ and CSV by Dave Cole at > http://object-craft.com.au/projects/csv/. I tried both of these and > get this error: > > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> import ASV > >>> my_data = ASV.ASV() > >>> my_data.input_from_file("c:\test_data.csv", ASV.CSV(), > has_field_names =1) > Traceback (most recent call last): > File "", line 1, in ? > my_data.input_from_file("c:\test_data.csv", ASV.CSV(), > has_field_names =1) > File "C:\PYTHON22\ASV.py", line 222, in input_from_file > file = open(input_file, "rb") > IOError: invalid argument: rb > >>> > > I get a similar message from CSV module. Anyone use either of these > and can tell me what's wrong? > Wow. You have two problems. Bill Gates has one. And one of either you or Dave Cole will get busted real soon now if you keep smoking that stuff :-) To be more explicit: You 1: Don't clutter the root directory of your C: drive with anything other than "necessary" directories, and files other than what Bill & other software providers dump in there. You 2: On Windows, either use forward slashes "c:/test_data.csv" (it works!) -- recommended -- or use raw strings r"c:\test_data.csv" if you must. The problem is that Python's escape handling intervenes; what Bill's software got to see in your case was equivalent to "C:" + a_bloody_tab_character + "est_data.csv" !!! Bill behaving badly: Seems like Bill chucks a wobbly if there is a_bloody_tab_character in a file name. I could be maligning Bill unjustly; could be GvR & Co -- I'll have a look at the Python source in a minute -- but I'd bet a couple of pots of beer that it's down to Bill. You and/or Dave in peril of the law: Last time I saw Dave's module it didn't presume to read files at all, it expected you to read lines and pass them to it one at a time. So either Dave has had a very recent rush of blood or something worse to the head and released unbeknownst to me a file-handling version of his module, or you are gravely mistaken when you assert "I get a similar message from CSV module". Hope this helps, John From frithiof.jensen at removethis.ted.ericsson.dk Tue Mar 12 09:43:18 2002 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Tue, 12 Mar 2002 15:43:18 +0100 Subject: Homepage of Gadfly not available? References: <3C8C8DA1.5040901@med.uni-tuebingen.de> <20020311140817.L25769@phd.pp.ru> Message-ID: <1015944219.970193@robert> "Harald Schneider" wrote in message news:a6iege$8hv$05$1 at news.t-online.com... > Maybe this helps: > http://www.zope.org/Members/mcdonc/RelationalDatabaseWiki/GadFly > http://cvs.zope.org/Products/ZGadflyDA/gadfly/#dirlist > Hmm - It would be great if someone could repackage the Zope teams updated version and distribute it as a stand-alone Python module on SourceForge, thus Keeping it Alive. From mwh at python.net Wed Mar 13 04:11:46 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 13 Mar 2002 09:11:46 GMT Subject: Is there a good reason why we cannot (as of 2.1.1) deepcopy complex objects? References: Message-ID: idot at vt.edu (Carl Banks) writes: > Strangely, I've found no mention of this anywhere: the docs, the > Python FAQ, or the Google archives. Umm, news to me! You can in 2.2, which seems to be the first version (at least since 1.5.2) where this is possible. I suspect this has gone unnoticed because: (a) not all that many people use copy.deepcopy (b) not all that many people us complex numbers. I don't think I've ever used the copy module for anything, and I've only used complex objects for playing around interactively. CHeers, M. -- 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 christophe.delord at free.fr Tue Mar 5 13:13:18 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Tue, 05 Mar 2002 19:13:18 +0100 Subject: Problem with SRE's regular expressions References: <3C83D5C6.7010303@free.fr> <3C83EA12.5030406@free.fr> Message-ID: <3C850ABE.8070501@free.fr> Thanks for your benchmark. In fact with <<([^>]|>[^>])*>> I have the same recursion limit problem and I use this expression : '<<((?:[^>]+|>[^>]+)*)>>' It's very close to your solution (just one more '+') I'm think of another solution : <<(>?[^>]+)*>> def match_with_big_groups_2(): r = re.compile(r'<<(>?[^>]+)*>>') for i in xrange(10000): r.match(vls) def non_grouping_match_with_big_groups_2(): r = re.compile(r'<<(?:>?[^>]+)*>>') for i in xrange(10000): r.match(vls) With these two expressions I can run a little faster. On my computer I get : 2.2 (#1, Feb 12 2002, 22:46:37) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] simple_version 62.705866 non_grouping_match 60.567762 match_with_big_groups 1.558770 non_grouping_match_with_big_groups 1.232597 nongreedy_match 27.859934 match_with_big_groups_2 0.933109 non_grouping_match_with_big_groups_2 0.779298 non_grouping_match_with_big_groups is 50X faster than simple_version non_grouping_match_with_big_groups_2 is 80X faster than simple_version I'll-rewrite-my-scanners-too-ly Y'rs, Christophe. Nick Mathewson wrote: > In article <3C83EA12.5030406 at free.fr>, Christophe Delord wrote: > >>Thanks for your explanation! >> >>In my real program, I had a more complex regexp. I need to match text >>enclosed in << ... >> >>I first have used such an expression : <<([^>]|>[^>])*>> >>but I prefered <<.*?>> because it is more readable. >> >>I'll listen to the advice and use my old regexp to see how faster it is >>this way ;-) >> >>Thanks, >>Christophe. >> > > # > # Actually, it looks like you can do at least sixty times better than > # the re you have above. > # > > import sys, time, re > > print sys.version > > def timefn(fn): > t = time.time() > fn() > t = time.time() - t > print "%40s %f" % (fn.__name__, t) > > m#Very Long String > vls = "<<" + " "*100 + ">>" > > def simple_version(): > ' This is the version from your post ' > r = re.compile(r'<<([^>]|>[^>])*>>') > for i in xrange(10000): r.match(vls) > > def non_grouping_match(): > ' This one uses non-grouping matches ' > r = re.compile(r'<<(?:[^>]|>[^>])*>>') > for i in xrange(10000): r.match(vls) > > def match_with_big_groups(): > ''' This one uses [^>]+ inside the group, in order to make each group > as large as possible. ''' > r = re.compile(r'<<([^>]+|>[^>])*>>') > for i in xrange(10000): r.match(vls) > > def non_grouping_match_with_big_groups(): > ' This version uses both of the above tricks. ' > r = re.compile(r'<<(?:[^>]+|>[^>])*>>') > for i in xrange(10000): r.match(vls) > > def nongreedy_match(): > " And for comparison, here's the one with the nongreedy match. " > r = re.compile(r'<<.*?>>') > for i in xrange(10000): r.match(vls) > > > timefn(simple_version) > timefn(non_grouping_match) > timefn(match_with_big_groups) > timefn(non_grouping_match_with_big_groups) > timefn(nongreedy_match) > > # > # Platform: > # 2.2+ (#30, Jan 29 2002, 21:20:45) > # [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] > # > # OUTPUT > # simple_version 37.967640 > # non_grouping_match 34.108361 > # match_with_big_groups 0.818009 > # non_grouping_match_with_big_groups 0.634849 > # nongreedy_match 16.892410 > > So it looks like the big win is to use [^>]+ inside your parenthesis. > It's a slight improvement to use (?: ) instead of ( ), but not much. > > Bonus observation 1: In this case, the overhead from matching a > parenthesized expression over and over is more than than the > backtracking overhead from '.*?' . > > Bonus observation 2: I purposefully put some '>' characters into the > test string. When I took them out, I found that the 60X performance > improvement turned into a 332X performance. Thus, the winning pattern > above is fastest of all when the parenthesized expression matches only > once. > > It-looks-like-I'm-going-to-have-to-go-rewrite-all-the-scanners-I'm- > maintaining-ly Y'rs > > -- Christophe Delord http://christophe.delord.free.fr/ From martin at v.loewis.de Tue Mar 5 18:36:02 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Mar 2002 00:36:02 +0100 Subject: undefined symbols when linking Python into a shared library References: <3C8540B5.E133D407@freenet.de> Message-ID: Michael Neuroth writes: > I link libpyhton.a into the shared library, I tried also to link > with the option -Xlinker -export-dynamic, as told by the python > documentation (section:Extending and Embedding the Python Interpreter, > 5.6 Linking Requirements). The shared library is a little bit lager, > but the resulting error is the same. How can I verify, that this > symbols are in the shared library? On Linux, use "nm -D foo.so" to see the symbols exported by foo.so. > What is the magic option to solve that (linker?) problem? You'll need to understand the problem first before trying to find a solution. I, for one, can only guess what is going on: most likely, your shared library really does not provide the symbol missing in _tkinter.so; this is probably not surprising, since the linker, when creating the library, had no clue that the symbol might be needed. In any case, it is a bad idea to incorporate libpython.a object files into a shared library, as this is non-PIC code. Regards, Martin From sdm7g at virginia.edu Tue Mar 26 17:24:53 2002 From: sdm7g at virginia.edu (Steven Majewski) Date: Tue, 26 Mar 2002 17:24:53 -0500 (EST) Subject: reduce vs. for loop In-Reply-To: Message-ID: On Tue, 26 Mar 2002, Sean 'Shaleh' Perry wrote: > > On 26-Mar-2002 m2 at plusseven.com wrote: > > > > Just out curiosity, > > why is fact2 a bit faster than fact1? > > > > def fact1(n): > > return reduce (operator.mul, range(1L,n + 1)) > > > > bigger problem here. fact2 returns a long, fact1 returns an integer. So > fact1(100) fails. > reduce(operator.mul, range(1,n+1), 1L ) fixes that, but it's even slower. -- Steve Majewski From sid at claudius87.plusserver.de Fri Mar 22 20:08:20 2002 From: sid at claudius87.plusserver.de (Juergen Gather) Date: Sat, 23 Mar 2002 02:08:20 +0100 Subject: Why do Windows sockets break after exactly 4 minutes? In-Reply-To: References: Message-ID: <10413617240.20020323020820@claudius87.plusserver.de> GT> sent message at Fri Mar 22 14:14:01 2002 GT> socket exception caught at Fri Mar 22 14:18:01 2002 GT> Traceback (most recent call last): GT> File "D:\junk\SocketTimeoutTest\client.py", line 13, in ? GT> data = s.recv(1024) GT> File "", line 1, in recv GT> socket.error: (10054, 'Connection reset by peer') GT> When I use a time shorter than 4 minutes in the time.sleep(), the output GT> from client.py looks like: GT> sent message at Fri Mar 22 14:20:43 2002 GT> Received 15 bytes: Goodbye, world! GT> closed socket at Fri Mar 22 14:20:58 2002 GT> So something is breaking the socket after 4 minutes. GT> I should note that this is on a Windows NT 4.0 SP6 box. Perhaps I'll try GT> Win2K to see if there's a difference there. I tried it under XP and there is exactly the same behaviour you describe above - only that its only 2 minutes (exact again!) until the socket breaks. Under FreeBSD there seems to be no such problem. I also tried to put client and server on different machines and everything is ok with server on the XP-Box and client on BSD while server on BSD and client on XP is breaking the socket after the "magic" 2 minutes. I can't tell if BSD or Windows behaviour is justified but it sure is irritating if code that looks platform independent (at least it does for me) decides not to be ;-). I suspect there should be some registry entry under Windows influencing this behaviour - any ideas ? Juergen From duncan at NOSPAMrcp.co.uk Mon Mar 11 03:56:35 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 11 Mar 2002 08:56:35 +0000 (UTC) Subject: Regular expressions newbie: something for templates References: Message-ID: "Thomas Weholt" wrote in news:idRi8.7723$eJ6.142517 at news2.ulv.nextra.no: > I'm not getting the hang of regular expressions. All I want to do is > this. > > Take string #1 : > > "This is the test $var1$ and this is $var2$" > > and turn it into > > "This is the test %(var1)s and this is %(var2)s" > When in doubt, avoid regular expressions. You might be better off doing something like this, which also allows you to escape a dollar sign into your output string: >>> s = "This is the test $var1$ and this is $var2$" >>> def template(s): ... lst = s.split('$') ... for i in range(1, len(lst), 2): ... if lst[i]: ... lst[i] = '%('+lst[i]+')s' ... else: ... lst[i] = '$' ... return ''.join(lst) ... >>> print template(s) This is the test %(var1)s and this is %(var2)s >>> print template('and this has $$ signs') and this has $ signs Optional enhancements would be to check the list length is odd (otherwise there was an unmatched dollar) and to replace all % with %% before starting. -- 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 kragen at pobox.com Wed Mar 20 03:05:57 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 20 Mar 2002 03:05:57 -0500 Subject: Status of PEP's? References: <5d283efe.0203062119.26642fd8@posting.google.com> Message-ID: <83ofhjhdei.fsf@panacea.canonical.org> daniels at mindspring.com (Alan Daniels) writes: > 1) Right now, we have complete orthogonality between "for" and "if". > "for i in seq:" will be called for each value where "if i in seq:" is > true. Adding "for i in 5" destroys this. for i < 5: for 0 <= i < 5: From p.vrijlandt at aig.azn.nl Fri Mar 1 11:02:11 2002 From: p.vrijlandt at aig.azn.nl (Patrick Vrijlandt) Date: Fri, 1 Mar 2002 17:02:11 +0100 Subject: Telnet connection References: <8z9f2rks.fsf@fido.trinitycapital.com> Message-ID: The problem could of course be in insufficient negotiation capabilities of telnetlib. Again, you would find out by using your browser or the standard windows Telnet client. "Bengt Richter" schreef in bericht news:a5nmas$mfe$0 at 216.39.172.122... > On 28 Feb 2002 23:46:47 GMT, bokr at oz.net (Bengt Richter) wrote: > > >On Thu, 28 Feb 2002 19:51:06 +0100, "Riss Nicolas" wrote: > > > >>Has somebody a python program where it is an telnet connection ? > > > >You appear to be running windows. What happens if you get into your browser > >and put > > > > telnet://192.168.0.9:32 > > > >in the location (i.e., what you are trying to connect to with your code)? > >Do you get a telnet client screen with a login prompt? > > > >Did you try \r\n in place of plain \n in your code? > > > > Whoa, I just realized your program seems to be missing > a couple of lines for waiting for a user prompt and sending > the user name. > > After that, wait for the password prompt. At least > that is typical. Or do you have some special telnet server > setup that bypasses that? Maybe it still needs a \r\n to > trigger it past the missing user entry? It's hard to say > with so little info. > > Or copy from the screen of a manual login and successful > connect with a couple commands. (Do you connect to an ordinary > shell or some special program)? > > BTW, if you somehow have wrapped your telnet program execution > in a try: do_it() except: pass, you could be missing a bug-caused > exception discussed in another thread. You might want to try > changing line 424 of telnetlib.py. In the other thread I wrote: > > I suspect line 424 > self.msg('IAC %d not recognized' % ord(opt)) > should be > self.msg('IAC %d not recognized' % ord(c)) > > Regards, > Bengt Richter > PS., explain in French if that helps. Someone will translate if needed. > Maybe even if not needed ;-) > From martin.franklin at westerngeco.com Tue Mar 19 06:20:11 2002 From: martin.franklin at westerngeco.com (Martin Franklin) Date: Tue, 19 Mar 2002 11:20:11 +0000 Subject: Checkboxes and Tortured Logic References: <4378fa6f.0203181538.5cde340e@posting.google.com> Message-ID: Marc wrote: > I know there's got to be a better way to do this than the way that I > found. But the only way I've been able to succesfully retrieve a value > from a checkbox (using the scant documentation I've been able to find) >From the docs.... (pydoc Tkinter.Checkbutton) class Checkbutton(Widget) | Checkbutton widget which is either in on- or off-state. | | _Misc__winfo_getint = __winfo_getint(self, x) from Tkinter.Misc | | _Misc__winfo_parseitem = __winfo_parseitem(self, t) from Tkinter.Misc | | __getitem__ = cget(self, key) from Tkinter.Misc | | __init__(self, master=None, cnf={}, **kw) | Construct a checkbutton widget with the parent MASTER. | | Valid resource names: activebackground, activeforeground, anchor, | background, bd, bg, bitmap, borderwidth, command, cursor, | disabledforeground, fg, font, foreground, height, | highlightbackground, highlightcolor, highlightthickness, image, | indicatoron, justify, offvalue, onvalue, padx, pady, relief, | selectcolor, selectimage, state, takefocus, text, textvariable, | underline, variable, width, wraplength. ..... So I guess you need the onvalue and offvalue parameters set... From loewis at informatik.hu-berlin.de Tue Mar 5 10:45:35 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 05 Mar 2002 16:45:35 +0100 Subject: I've got the unicode blues References: <3c846d80.95456984@news.isar.de> <3c848c0e.103279375@news.isar.de> Message-ID: gerson.kurz at t-online.de (Gerson Kurz) writes: > All tests were made using > > PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on > win32 > > from inside PythonWin. I see. That the stream reader doesn't work will be fixed shortly; the fix is Index: codecs.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/codecs.py,v retrieving revision 1.23 diff -u -r1.23 codecs.py --- codecs.py 19 Sep 2001 11:24:48 -0000 1.23 +++ codecs.py 5 Mar 2002 15:42:57 -0000 @@ -252,7 +252,7 @@ return self.decode(line, self.errors)[0] - def readlines(self, sizehint=0): + def readlines(self, sizehint=None): """ Read all lines available on the input stream and return them as list of lines. Regards, Martin From mlh at vier.idi.ntnu.no Fri Mar 15 19:27:24 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 16 Mar 2002 00:27:24 +0000 (UTC) Subject: Why I think range is a wart. References: Message-ID: In article , Bertrand Geston wrote: [...] >Let's keep things simple and understandable : >- lists are ordered sets, >- dictionnaries are "keyed" sets. The standard mathematical definition of sequences (as opposed to ordered sets) is a partial function mapping integers to elements. This seems awfully close to what you're calling "keyed" sets, by restricting the domain to integers. It also seems awfully close to Python lists (for instance). I see nothing inconsistent or illogical about list.keys. list.indices is an alternative, of course, but would not allow for polymorphic use. -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From shredwheat at attbi.com Wed Mar 6 22:45:36 2002 From: shredwheat at attbi.com (Pete Shinners) Date: Thu, 07 Mar 2002 03:45:36 GMT Subject: streaming images References: Message-ID: <3C86E417.9040803@attbi.com> Bill wrote: > I'm receiving images through the network from a server. I use python and > PIL to receive the image. I need to display the images in real time as they > come (meaning I cant save a bunch of them and create an animated GIF or > something like that). If I do an image.show() on each image I receive, a > seperate window will pop up for each image and the desktop gets cluttered. > Any ideas on how to do this? Is there a way for me to UPDATE the window > with a new image so that only that window stays open? Do I need something > else besides PIL to do this or will PIL be adaquate? you'll need to actually run your own graphics window. most gui libraries allow you to display PIL images. i might add it's fairly simple to do this with the pygame package (http://www.pygame.org) without PIL. in fact someone has already done something similar to this. there is a simple little utility that streams jpg images from an online webcam. http://www3.telus.net/futility/futility/software.html#pypanda From francis.meyvis at sonycom.com Fri Mar 29 06:06:02 2002 From: francis.meyvis at sonycom.com (Francis Meyvis) Date: Fri, 29 Mar 2002 11:06:02 GMT Subject: win32com client and McMillan installer 5.3b1 References: Message-ID: Hello, I found a miserable work around. The pythoncom16.dll is somewhere under the WINNT. I copied this as pythoncom.dll and the thing now works. Does someone have a nicer solution? Thx -- --- Kind regards, best wishes, francis meyvis Francis Meyvis wrote in message news:FVWo8.9$ta.1379 at nreader3.kpnqwest.net... > Hello, > > I've a bunch of python scripts that I'd like to convert into and exe. > This works well with the McMillan Installer except the script that > uses the win32com client stuff to access worksheets in an excell document. > From the traceback I see that there's an import error: > "No module named pythoncom" > > I tried it with McMillan installer 5.3b1 on > NT5 with python 2.2 and Mark Hammond's associated win32 extentions > NT4 with python 1.6 and Mark Hammond's associated win32 extentions > > Both give me the same result. > > Can someone point me to what I'm doing wrong? > I did a > p22 Makespec.py --name=tst script.py > p22 Build.py script.py > > I have some warnings about a delayed __import__ > According to the doc these have to be taken serious. > But the doc does not explain in a clear way to me > what I should do about it. > Extend the path?, add the modules manually to the spec file? > > Thx > --- > Kind regards, best wishes, > francis meyvis > > From mwh at python.net Thu Mar 21 08:15:36 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Mar 2002 13:15:36 GMT Subject: Unicode problem References: <3c98f206.24909027@news.tiscali.no> <3c98faad.27124282@news.tiscali.no> Message-ID: Duncan Booth writes: > gargravarr at whoever.com wrote in news:3c98faad.27124282 at news.tiscali.no: > > >>if you don't tell Python what 8-bit encoding you want > >>to use for a Unicode string, Python will assume ASCII. > > > > How do I tell Python what 8-bit encoding I want to use ? Can I tell > > Python so I don't have to use encode? > > site.py uses sys.setdefaultencoding to set the default encoding but it then > does 'del sys.setdefaultencoding' to stop anyone else messing with it. > > Your options (entirely at your own risk): > Edit site.py to select a different default encoding. > Edit site.py to remove the line that deletes sys.setdefaultencoding > OR to recover a reference to setdefaultencoding: > import sys; reload(sys) or: write a sitecustomize.py Cheers, M. -- > so python will fork if activestate starts polluting it? I find it more relevant to speculate on whether Python would fork if the merpeople start invading our cities riding on the backs of giant king crabs. -- Brian Quinlan, comp.lang.python From aahz at pythoncraft.com Sun Mar 31 18:35:21 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 18:35:21 -0500 Subject: Cannot find what I'm sure is a simple command... please help. References: <3ca7978b.251291804@mammoth.usenet-access.com> Message-ID: In article <3ca7978b.251291804 at mammoth.usenet-access.com>, A. Jones wrote: > >I seem to have either overlooked, or completely missed a function that >allows one to open a specific line of a file. There isn't one, unless every line of your file is the same length (fixed-length records). You need to read one line at a time until you get to the correct line. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From martin at v.loewis.de Sun Mar 31 05:39:09 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 12:39:09 +0200 Subject: PEP 285: Adding a bool type References: Message-ID: Tim Peters writes: > In context, your original int(b) suggestion was in response to my: > > people have a legitimate need to make an arbitrary true/false > expression produce 0 and 1 too, if only to preserve 0/1-based > true/false output. operator.truth() has always been the best > way to do exactly that. Alternatives like "(boolexpr) + 0" and > "(boolexpr) and 1 or 0" and "(0,1)[boolexpr]" reek in comparison. > [...] > So you may say that "clearly the assumption there is that b is a bool", but > it's not at all clear that was a *reasonable* assumption in the context in > which you first said it: I've been thru the business twice now of > explaining why int() isn't suitable for the cases I was talking about. > int(bool) is not a case I was talking about. Your list of alternatives that reek in comparison was puzzling. int(bool(obj)) doesn't reek to me: it is obvious what it does, it does that efficiently, and it requires less typing than operator.truth(obj). In that context, I took Guido's response as "why are you bringing up this silly list of alternatives, yet ignoring the obvious alternative: int is the right way to get an int from a bool": int(bool(obj)). Regards, Martin From bernie at 3captus.com Fri Mar 22 19:17:22 2002 From: bernie at 3captus.com (Bernard Yue) Date: Sat, 23 Mar 2002 00:17:22 GMT Subject: sgmlParser infinite loop? How to empty and re-user parser object? References: Message-ID: <3C9BC9E5.89AE2D1F@3captus.com> Nick Arnett wrote: > > Anyone know of circumstances under which sgmlParser will hang, presumably in > an infinite (well, exceeding my patience, anyway) loop? I don't seem to be > able to reliably reproduce this, but occasionally during processing of a > large number of pages, I seem to get stuck in it. I'm doing very simple > parsing, basically just extracting the contents of tables. I'll re-try the > same set of documents and it'll hang in a different spot. If it weren't so > unpredictable and infrequent, I'd dig into it with the debugger... > My record is 1300 web pages and I did not get the problem you've mentioned. > Still fairly new to Python... I'm wondering if I should be re-using a parser > object for each document I'm processing in a loop -- and wondering if the > fact that I'm not is causing these freezes. But if I call it without > re-instantiating it, I get the same text parsed again... and I can't see how > to tell it to not do that. Calling reset doesn't seem to do the trick, > even though I seem to have the appropriate reset method that calls the > parent reset. > I am not reusing the parser object in my script either (but you can). You should consider post the program fragment you used. > Thanks for tips. > > Nick > -- > narnett at mccmedia.com > (408) 904-7198 Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From sandskyfly at hotmail.com Sun Mar 10 03:45:09 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 10 Mar 2002 00:45:09 -0800 Subject: scripting Outlook express with Python Message-ID: Does anyone have any experience, code, etc...? I guess my first question should be: is it possible? regards, Sandy From amckay at merlinsoftech.com Wed Mar 13 19:38:20 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Wed, 13 Mar 2002 16:38:20 -0800 Subject: Zope In-Reply-To: <3C8FED4D.A8C0470@3captus.com> References: <3C8FED4D.A8C0470@3captus.com> Message-ID: <200203140037.g2E0bbq00444@mail.merlinsoftech.com> On March 13, 2002 04:20 pm, Bernard Yue wrote: > Are there anybody using Zope 2.4.3 with Python 2.2 in production > environment? Problems? Lots of people are reporting segfault / crashes with Python 2.2 / 2.1.2 at the moment. Is this your problem? My other problems Im keeping personal ;) -- Andy McKay From akuchlin at ute.mems-exchange.org Tue Mar 26 15:31:54 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 26 Mar 2002 20:31:54 GMT Subject: PEP262 - database of installed packages References: Message-ID: In article , David Ascher wrote: > PPM bdist target works which we're looking at replacing soon. PPM3 (for > Perl only so far) is a major rewrite of PPM which added a bunch of cool > features. For info on that, see: http://aspn.activestate.com/ASPN/PPM. Is the PPD format changing in PPM3 at all? --amk From ralph at penguin.com Tue Mar 19 08:12:58 2002 From: ralph at penguin.com (Ralph) Date: Tue, 19 Mar 2002 13:12:58 GMT Subject: socket.gethostbyname() AttributeError Message-ID: Pythoners: I assumed that for scoket.gethostbyname(host), I was to pass a host of the type "theodore.chipmunks.com" and that I would get back an IP address as a doted quad. Obviously I am wrong about the form of the arguement I am to pass to the function, because I am getting an AttributeError message. Can anyone offer some insight? Thanks Raplh From aahz at pythoncraft.com Fri Mar 29 00:07:41 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Mar 2002 00:07:41 -0500 Subject: The Python Way References: Message-ID: In article , Skip Montanaro wrote: > >I wrote that I should look at replacing code like this > > self.cache_lock.acquire() > try: > fiddle_some_cache... > finally: > self.cache_lock.release() > >with code like this > > some_cache = self.some_cache_queue.get() > fiddle_some_cache... > self.some_cache_queue.put(some_cache) > >I eventually realized I can avoid the try/finally however. If something >happens within fiddle_some_cache... in the second code example I'd wind up >with an empty queue. So, if I needed try/finally in the acquire/release >case, I will need it in the get/put case. Silly me... However, if you construct your dataflow such that an empty queue isn't a problem, you don't need to use try/finally in your second example. If you're *just* using a queue to avoid an RLock() on a shared structure, go ahead and use the RLock(); my point about using Queue.Queue is that too many people try to pass data around using primitive/poor constructs. Another point is that if your program would be broken (i.e. "should crash") if fiddle_some_cache fails, you probably shouldn't bother with the try/finally. Go ahead and force a core dump. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From skip at pobox.com Mon Mar 18 19:14:36 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Mar 2002 18:14:36 -0600 Subject: Dictionary as non-iterable object? In-Reply-To: <265fffe3.0203181601.21c10ba@posting.google.com> References: <265fffe3.0203181601.21c10ba@posting.google.com> Message-ID: <15510.33516.309182.177054@12-248-41-177.client.attbi.com> Rob> The deal is this: using the IDLE interpreter (directly from Rob> www.python.org), I can do the following: >>>> D = {(4, 6): 13, (4, 3): 12, (5, 2): 11, (2, 5): 8, (1, 2): 9} >>>> for x,y in D: Rob> print D[(x,y)] Rob> 13 Rob> 12 Rob> 11 Rob> 8 Rob> 9 Rob> 10 >>>> Rob> Fine, right? Unfortunately, ActiveState's latest version does not Rob> allow me to do this, saying that I can't iterate over a dictionary's Rob> keys. The construct for k in dict: ... is new with Python 2.2. I don't think ActiveState has yet released a stable version of ActiveState Python that is based on 2.2. In the meantime, if you are committed to ActiveState's product, you'll have to use for k in dict.keys(): ... -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From skip at pobox.com Wed Mar 6 12:08:15 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 11:08:15 -0600 Subject: PEP 284, Integer for-loops In-Reply-To: References: Message-ID: <15494.19711.723922.527327@beluga.mojam.com> David> for_test: target_list "in" expression_list | David> or_expr less_comp or_expr less_comp or_expr | David> or_expr greater_comp or_expr greater_comp or_expr Why is an or_expr non-terminal between the two comparisons? Shouldn't it be a target_list? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From gvdbogae at vub.ac.be Mon Mar 4 17:25:20 2002 From: gvdbogae at vub.ac.be (Geert-Jan Van den Bogaerde) Date: 04 Mar 2002 23:25:20 +0100 Subject: Stedents Question In-Reply-To: <3C83EA76.BEA9C041@ccvcorp.com> References: <3c80126f_1@news.iprimus.com.au> <3C83EA76.BEA9C041@ccvcorp.com> Message-ID: <1015280720.1373.2.camel@gandalf> On Mon, 2002-03-04 at 22:43, Jeff Shannon wrote: > > > Geert-Jan Van den Bogaerde wrote: > > > On Sat, 2002-03-02 at 00:45, Tony K wrote: > > > The question below is a tutorial question that stumps me. Any suggestions > > > would be appreciated. > > > Tony > > > > > > Write a Python function findABBC which takes a single string as parameter > > > and returns all substrings thereof which match the regexp pattern ab+c. You > > > are NOT allowed to use the re module. > > > > > > > Haven't used regexps in a while, but I believe that just means: > > > > def findABBC(str): > > return str == "a" + "b" * len(str[1:-1]) + "c" > > Except that the spec was to return all matching substrings. You're simply > testing to see if the entire string matches that pattern, and returning a boolean > true/false. (This could theoretically be used as a helper function in a > solution, though I suspect that there's a better way to go about it.) You are of course quite right. I misread the original question. Geert-Jan > > Jeff Shannon > Technician/Programmer > Credit International > > > -- > http://mail.python.org/mailman/listinfo/python-list > From emile at fenx.com Fri Mar 22 09:19:58 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 22 Mar 2002 06:19:58 -0800 Subject: __* name mangling documentation References: Message-ID: "Eric Brunel" wrote in message news:a7fcb1$1m9h$1 at norfair.nerim.net... > Michel Pelletier wrote: > > http://www.python.org/doc/current/ref/id-classes.html > > > > sort of left me hanging on why __ name mangling exists and why it would be > > used. I think the question may want to be 'why does it still exist?' Possibly the answer is backwards compatibility. > > Simple: private attributes and methods: > >>> class C: ... def __init__(self, val): ... self.__priv = val ... >>> c = C(2) >>> c._C__priv # they're not hidden...(if you know the rule) 2 > I can't figure out what could be "tricky" about private attributes or > methods: they can only be accessed from inside the class's instances, and > that's all there is about them... Can you provide an example of what you > mean by "tricky"? > More specifically, they're known as class-private variables and are (normally) accessible only to the class's instance when accessed from within the defining class : >>> class D(C): ... def test(self): ... print 'my private val is ',self.__priv ... >>> d = D(3) >>> d.test() my private val is Traceback (most recent call last): File "", line 1, in ? File "", line 3, in test AttributeError: D instance has no attribute '_D__priv' >>> http://aspn.activestate.com/ASPN/Mail/Message/886237 discusses other problems with mangling. -- Emile van Sebille emile at fenx.com --------- From greg at cosc.canterbury.ac.nz Sun Mar 3 18:41:05 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 04 Mar 2002 12:41:05 +1300 Subject: dirwalk.py generator version of os.path.walk References: Message-ID: <3C82B491.D74EA9AD@cosc.canterbury.ac.nz> Tim Peters wrote: > > If I were Jim, I'd continue leaving recursion out of this specific > application. An explicit "todo list" trivially supports either > breadth-first or depth-first traversal (a choice Jim explicitly mentioned as > something he wants to control). That's fine. I was just trying to make sure that Jim didn't reject recursion for the wrong reasons. His comment about lack of tail-recursion supported suggested a possibly hazy understanding of the issues, so I tried to indulge in a little fog-dispersal. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From aahz at pythoncraft.com Sat Mar 30 15:54:10 2002 From: aahz at pythoncraft.com (Aahz) Date: 30 Mar 2002 15:54:10 -0500 Subject: Stopping a thread from an imported file References: <4378fa6f.0203290918.21be5409@posting.google.com> Message-ID: In article <4378fa6f.0203290918.21be5409 at posting.google.com>, Marc wrote: > >I am writing an application that has a front end Tkinter GUI and a >back end process. The back end process is being imported into the GUI, >which acts as the main thread in the program. When the 'GO' button is >clicked, the GUI starts a thread which calls a function that sends >control to the back end. > >The problem is that when this function has ended, the thread does not >die. So when the button is clicked to start the application again, it >won't start because it thinks the thread is still active. I don't have the time to track down your problem, but if you go to my web site, you can see an example of a working program that may help you. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From philh at comuno.freeserve.co.uk Sat Mar 30 15:05:35 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 20:05:35 +0000 Subject: PEP 285: Adding a bool type References: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Message-ID: On 30 Mar 2002 01:36:43 -0800, Paul Rubin wrote: >Guido van Rossum writes: >> Dear reviewers: >> >> I'm particularly interested in hearing your opinion about the >> following three issues: >> >> 1) Should this PEP be accepted at all. > >I don't see much need for it. Nor do I. Python works OK as it is, asnd this proposal adds nothing new semantically (because bool must act the similarly to int, for compatibility). The only advantage I see is that code is slightly more self-documenting, e.g.: return True instead of: return 1 > There's no need to turn Python into Java. Indeed. Python, as it stands, is a much clearer and nicer-to-code-in langauge than Java, C, C++, etc. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From xx758 at cam.ac.uk Wed Mar 27 13:16:57 2002 From: xx758 at cam.ac.uk (Xiao-Qin Xia) Date: Wed, 27 Mar 2002 18:16:57 +0000 Subject: velocity of python,jython,java,jit Message-ID: Hi, If a python program can be translated into java bytecode by jython, anybody compared the velocities when run with python, jython, java, JIT (a just-in-time compiler, JIT compiles the Java bytecode into native machine code on-the-fly)? Cheers, Xiao-Qin From logiplexsoftware at earthlink.net Tue Mar 26 13:27:26 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 26 Mar 2002 10:27:26 -0800 Subject: wxPython and wxFlexGridSizer problem In-Reply-To: References: <3C9FBE22.A72B4A27@ccvcorp.com> Message-ID: <20020326102726.1c0524ff.logiplexsoftware@earthlink.net> On 26 Mar 2002 10:49:46 GMT Uwe Schmitt wrote: > Jeff Shannon wrote: > > > | Are you sure that you want to use ShowModal()?? How are you setting up your > | window? > > | This function looks okay to me, as far as it goes, but it's hard to say what > | might be going on if we don't know where window is coming from. I presume that > | it's a wxDialog of some sort? If so, why aren't you subclassing wxDialog and > | putting this code in your __init__(), then calling ShowModal() from the function > | that creates the dialog? > > I got the answer in the wxwindows-group: there is just > a window.Layout() call missing. Thats it and everything is fine.. That may be the case, but Jeff brought up some good points. It looks odd to create a window in this fashion (it looks procedural rather than OO). A more typical approach would be something like: class testtt(wxDialog): def __init__(self, parent, id): wxDialog.__init__(self, parent, id, "") basicSizer = wxBoxSizer(wxVERTICAL) gridSizer= wxFlexGridSizer(cols=2) t=wxStaticText(self, -1, "Eingabe:") tt=wxTextCtrl(self, -1, "", size=wxSize(100,-1)) gridSizer.AddMany([ (t, 0, wxALL | wxALIGN_RIGHT), (tt, 0, wxALL |wxALIGN_LEFT) ]) gridSizer.SetSizeHints(self) gridSizer.Fit(self) self.SetSizer(gridSizer) self.SetAutoLayout(true) self.Layout() And then elsewhere: dlg = testtt(None, -1) dlg.ShowModal() Also, I notice that your calls to gridSizer.Add are incorrect. The second argument is supposed to be a boolean flag indicating whether the widget should be expanded in the sizer's primary direction (in the case of a wxFlexGridSizer, I'm not sure what that means, but you still need the argument, at least as a placeholder). The wxALL and wxALIGN_* flags should be the third argument. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From trentm at ActiveState.com Thu Mar 14 03:35:27 2002 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 14 Mar 2002 00:35:27 -0800 Subject: Python Version Strategy? In-Reply-To: ; from bosahv@netscapenospam.net on Thu, Mar 14, 2002 at 07:56:13AM +0000 References: Message-ID: <20020314003527.A9718@ActiveState.com> [Bo Vandenberg wrote] > I'm confused by what is going on with the python versions from various > sources. > > Python.org has a final 2.2 (I use that) but Activestate has a python 2.1 as > its recommended python and only a 2.2 beta last I looked. 2.2 is the latest stable Python release (modulo your own definition of stable). It was released 21 Dec 2001. If your definition of stable is pretty high then you might want to consider using Python 2.1.2 (i.e. Python 2.1 with two addition bugfix releases). ActivePython (from ActiveState) does not have a final 2.2 build just because we are behind (discliamer: I work at ActiveState). Expect an ActivePython 2.2 very soon. > Redhat, and most (all?) of the linux distros seem to be slow to fully > upgrade and I feel like this is raining in my cornflakes. Yup. As I understand it the core Python folks don't really have any pull for what default Python version gets installed for the various Linux distros. > I'm not even beginning to think of when the next version of python (3?) > comes out. The next version of Python will almost certainly be 2.3. The release schedule is here: http://python.sourceforge.net/peps/pep-0283.html Tentative future release dates. 30-Aug-2002: 2.3 (final release) 26-Aug-2002: 2.3c1 (release candidate) 14-Aug-2002: 2.3b2 17-Jul-2002: 2.3b1 19-Jun-2002: 2.3a2 22-May-2002: 2.3a1 > Anyone think they have inside information on all this? Yup. :) > What's a forward thinking newbie, with no old code to support to do??? Just get the latest Python 2.2 and start hacking! If you like new things that come along then upgrade as it comes. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From sasoft at gmx.de Thu Mar 7 19:28:19 2002 From: sasoft at gmx.de (stefan antoni) Date: Thu, 7 Mar 2002 19:28:19 -0500 Subject: [GERMAN] "ziegenproblem" Message-ID: <20020308002819.GA1571@blackscarab> sorry that i won't be able to explain this in english, i don't know the name of this problem in english, and the website which is about this problem is also in german. i want to write this basic code in python: http://www.google.de/search?q=cache:Uugc3CH9SOQC:home.spektracom.de/ellrich/Ziegen.htm+ziegenproblem+basic+programm&hl=de i am still going to school, and we talked about this problem in a math lesson. since i haven't got a basic-interpreter, i'd like to translate this code into python, but i don't understand the code. anybody who knows basic and python as well? -- stefan antoni -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 240 bytes Desc: not available URL: From Dave.Haynes at sia-mce.co.uk Sat Mar 23 04:29:32 2002 From: Dave.Haynes at sia-mce.co.uk (Dave Haynes) Date: 23 Mar 2002 01:29:32 -0800 Subject: Customisation of comparison operators References: Message-ID: Tim Peters wrote in message news:... > Yup, that's dodgy all right. Yes I suppose it is. And since Dodginess is anti-Pythonic, I think I'll change my approach. Thanks for the information though. I wasn't aware of _contains_, and directly following your reply, it appears in documentation. put-that-time-machine-back-where-it-came-from-ly y'rs - dave From clive at capedomain.co.za Mon Mar 25 02:13:23 2002 From: clive at capedomain.co.za (Clive Crous) Date: Mon, 25 Mar 2002 09:13:23 +0200 Subject: embedded python ... Message-ID: I'm having a great deal of trouble embedding any pyhton script that doesan "import math". the few examples of embedded python I have managed to come across give the same result if I add an "import math" to one of their scripts. can anyone give me a clue ? it must be possible as I can import math in blender scripts ;) Error : --------------------------------------------------------- Traceback (most recent call last): File "./blue.py", line 2, in ? import math ImportError: /usr/lib/python2.1/lib-dynload/math.so: undefined symbol: PyExc_OverflowError --------------------------------------------------------- any help greatly appreciated thanks Clive Crous From walter at livinglogic.de Thu Mar 7 16:23:32 2002 From: walter at livinglogic.de (Walter =?ISO-8859-1?Q?D=F6rwald?=) Date: Thu, 07 Mar 2002 22:23:32 +0100 Subject: Handling bad tags with SGMLParser References: <6c80b2a1.0203070848.6a25b499@posting.google.com> Message-ID: <3C87DA54.1060201@livinglogic.de> Ken Causey wrote: > I'm working with a piece of software which uses SGMLParser to parse > HTML content so that a small subset of tags can be handled specially. > The result is then passed onto a browser for rendering. Failure is > not an option. > [...] You might either try sgmlop, which is part of PyXML (http://sf.net/projects/pyxml/) or use Marc-Andr? Lemburgs Python version of tidy (http://www.lemburg.com/files/python/mxTidy.html) Hope that helps! Bye, Walter D?rwald From iddwb at moroni.pp.asu.edu Mon Mar 4 19:37:07 2002 From: iddwb at moroni.pp.asu.edu (David Bear) Date: 04 Mar 2002 17:37:07 -0700 Subject: chopping a string Message-ID: there's gotta be an easier way. I have a string " something somethingelse " note the leading a trailing whitespace. I'd like to grab the first word and strip whitespace. I came up with string.join(string.split(string.strip(str))[:1]) but I'm thinking, there must be a better way? better means (faster) (smaller).. -- David Bear College of Public Programs/ASU 480-965-8257 ...the way is like water, going where nobody wants it to go From h.jehadalwan at student.kun.nl Sat Mar 2 12:27:56 2002 From: h.jehadalwan at student.kun.nl (husam) Date: Sat, 02 Mar 2002 18:27:56 +0100 Subject: a simple 'else' decrease speed by 1000 times. References: <3C80BBAC.2060600@student.kun.nl> <3C80E535.7000407@student.kun.nl> Message-ID: <3C810B9C.6050208@student.kun.nl> hi Chris, I think that I've found a mistake in the script. The mistake is outside the function I posted. I corrected it and now in I'm testing it again. The script takes alot of time to excute, so if the test fails again, you will see a posting from me within days. From bkelley at wi.mit.edu Thu Mar 7 13:54:44 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 07 Mar 2002 13:54:44 -0500 Subject: Python and computer graphics References: <3C8785EA.5010509@student.kun.nl> Message-ID: <3C87B774.7010600@wi.mit.edu> husam wrote: > hi, > can anybody points me to usefull resources (books, urls) about using > python for computer graphics that help for building skills in this > subject from scrash? > > thanks in advance > You might want to check out the vtk toolkit which has a good python binding. There are plenty of books and manuals available http://public.kitware.com/VTK/buy-books.php Brian Kelley From netlangau at yahoo.com.au Sat Mar 16 15:40:48 2002 From: netlangau at yahoo.com.au (Patrick) Date: Sun, 17 Mar 2002 07:40:48 +1100 Subject: Good book on Python? References: Message-ID: "orangefree89" wrote in message news:slrna9559u.g52.orangefree89 at localhost.localdomain... > On Fri, 15 Mar 2002 18:37:53 +0000, Chris wrote: > > > Thank you. > > I downloaded number 4. > > However, it is in a strange form (Tex) for a windows user. > > Is it any use to me in that form? > > And can it be obtained in any other form? > > (It does look good.) > > Yassas. I'm pretty sure it is also available in pdf. http://www.ibiblio.org/obp/thinkCS.php From gcordova at hebmex.com Wed Mar 13 15:03:15 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 13 Mar 2002 14:03:15 -0600 Subject: Newbie regex question. Message-ID: <19650FF08A99D511B19E00B0D0F0632301D6894A@SRM201002> > > >>> import re > >>> s= 'yadda widget1 widget2 yadda' > >>> regex = re.compile('yadda (widget1) (widget2) yadda') > >>> for match in regex.search(s).groups(): print match > ... > widget1 > widget2 > > This works here. Although I would strongly caution you to do: > > re_match = regex.search(s) > if re_match != None ...... > > just in case the regex fails. > you can get away with only: re_match = regex.search(s) if re_match: .... The comparison vs. None is not necessary, if you only need to know the boolean value of True|False, since None is False (er, bool(None) == False). You know. Also, comparing vs. None is better done with "var is None" rather than "var == None". Salutations. -gustavo From dale at riverhall.NOTHANKS.co.uk Mon Mar 25 19:35:32 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Tue, 26 Mar 2002 00:35:32 +0000 Subject: forgetting state References: <98b6685d.0203231539.1459d00d@posting.google.com> Message-ID: "logistix" wrote: >It's a feature, not a bug ;) > >One of the big bullet items for python is that it operates in a dynamic >environment. The programmer can modify the environment at runtime. In a >dynamic environment, you don't want to trust the system to decide what >existing objects should be killed (other than gc) or what existing objects >do or don't need to be fixed. It's up to the programmer to explicitly do >this if he/she wants to. An even more unforgivable sin than not having the >system "fix" broken objects/dependencies/etc is to allow the system to break >currently functioning and running objects. It's very difficult (probably >impossible) to write a general-purpose, "if-it-ain't-broke-don't-fix-it" >algorithm. Given this, it makes sense that the only way to ensure that >you've returned to the initial state of the environment is to kill it and >create a new one. > >Now I'm not saying you need to agree with this (you obviously don't), but it >is a genuine philosophical decision on how things should operate, as opposed >to an oversight or bug needing to be corrected. There are probably lisp or >smalltalk programmers at the other end of the spectrum who think that an >image of the enviroment should be saved automatically when you shut down the >interpreter. Then when you open it up again you're NOT in any sort of >'initial state', but right where you left off, bugs and all. > >There are also people who get very upset that 1) there is no mechanism for >static typing in Python, 2) there are no plans to add it, and 3) (even worst >of all!) noone cares. This is another philosophical decision and not an >oversight. > >And, of course, with all philosophical decisions, it's really hard to prove >who's right and who's wrong. [Except mob rule, and it looks like the mob has >spoken.] > This, somewhat verbosely, completely misses the point. If you're debugging a program and execution stops at some point, for any reason, you don't want to have to completely leave your development environment and restart it just so you can run from the beginning again. All the twaddle about dynamic environment and existing objects is utterly irrelevant. If my program has failed, I don't want them any more. I want a nice shiney new environment with a fresh set of objects. There really should be a "throw it all away and let me start again" button. -- Dale Strickland-Clark Riverhall Systems Ltd From skip at pobox.com Wed Mar 20 20:58:46 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 20 Mar 2002 19:58:46 -0600 Subject: How Can I Determine the Operating System with Python? In-Reply-To: References: Message-ID: <15513.15958.313096.169148@12-248-41-177.client.attbi.com> Jill> How can I put a check in my script which will allow me to Jill> determine whether I'm running on Windows or Linux at execution Jill> time? Check the value of sys.platform: Python 1.5.2 (#1, Nov 27 2000, 02:23:30) [GCC 2.95.2 19991024 (release)] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import sys >>> sys.platform 'sunos5' vs. Python 2.3a0 (#4, Mar 11 2002, 21:35:57) [GCC 3.0.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.platform 'linux2' -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From andrew-pythonlist at puzzling.org Wed Mar 20 00:53:00 2002 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 20 Mar 2002 16:53:00 +1100 Subject: NameError assigning to class created in a function Message-ID: <20020320055300.GB24737@ritsuko.xware.cx> (Tested on Python 2.2) This fails: def f(x): class Private: x = x return Private x(1) but this works: def f(x): y = x class Private: x = y return Private x(1) but this also fails: def f(x): y = x class Private: y = y return Private x(1) So, it seems that you can't assign to a variable in a class if it has the same name as the variable you are assigning from. Except that it works outside a function: x = 1 class C: x = x It's easy enough to workaround, but annoying. Is this a genuine bug? If so, I'll submit it to the SF bug tracker... -Andrew. (Please CC: me as I'm not currently subscribed to the list/newsgroup) From garry at sage.att.com Mon Mar 4 13:12:54 2002 From: garry at sage.att.com (Garry Hodgson) Date: Mon, 4 Mar 2002 18:12:54 GMT Subject: Adding static typing to Python References: <24c39b2c.0202181531.187fad4c@posting.google.com> <3C71B291.B8574221@ccvcorp.com> <20020219095832.GE2611@lilith.hqd-internal> Message-ID: <3C83B926.5D76525C@sage.att.com> Drew Csillag wrote: > > On Tue, Feb 19, 2002 at 10:58:33AM +0100, Gerhard H?ring wrote: > > Le 19/02/02 ? 03:18, Grant Edwards ?crivit: > > > In article , Chris Gonnerman wrote: > > > > > > > Ultimately, adding static typing to Python results in a different > > > > language; it's not Python anymore. > > > > > > > > If you don't like Python because the typing isn't strong, use Ada, > > > > or C++, or Pascal... > > > > > > You might also want to take a look at Modula-3. Anybody used > > > to Python will recognize many of the language features. > > > > Modula-3 also looks great, as did Sather to mee. But both seem seem to > > have no compilers that are actively maintained. > > > > So I'm still leaning towards Ada 95 and C++ for statically typed > > languages. > > If you want really statically typed, you probably want to take a look > at Eiffel. check out ocaml, too. -- Garry Hodgson Let my inspiration flow Senior Hacker in token rhyme suggesting rhythm Software Innovation Services that will not forsake me AT&T Labs 'til my tale is told and done. garry at sage.att.com From daniels at mindspring.com Thu Mar 7 00:19:48 2002 From: daniels at mindspring.com (Alan Daniels) Date: 6 Mar 2002 21:19:48 -0800 Subject: Status of PEP's? References: Message-ID: <5d283efe.0203062119.26642fd8@posting.google.com> Michael Chermside wrote in message news:... The objection you quoted was from me originally, so I feel compelled to respond to it here. [snippety doo dah, snippety ay...] > 1) I think that "for i in range(len(items)):" is awkward, annoying, > and detracts from Python. There should be a better way. I agree. The nicest counter-proposal I've seen so far is... for i in indices(items): print i > *PLEASE* disregard the whole "set theory" argument. I don't think > that anyone defending PEP 276 is suggesting it as the motivation... I know, I know... I *was* on a rant, true, but I never used the "set theory" argument as a straw man. In fact, I was disappointed that this was the only provided justifcation for seeing an integer as a sequence. I was hoping for something more substantial, and less tongue-in-cheek. There's still some MAJOR problems I see with PEP 276: 1) Right now, we have complete orthogonality between "for" and "if". "for i in seq:" will be called for each value where "if i in seq:" is true. Adding "for i in 5" destroys this. 2) If you can iterate over integers, a newbie will rightfully wonder why it is that you cannot iterate over floats. "for i in 5" may be up in the air, but I doubt that anyone would agree that "for i in 5.0" could ever be meaningful. I brought this up before but no one responded to it. If anyone has any feedback on this I'd appreciate it. 3) PEP 276 still doesn't handle the case where you need "steps", such as something like: for i from 1 to 10 step 2: print i Or something along that line. I'm using Basic-style syntax here as an example, not a recommendation. :-) 4) I actually *like* that you have to use xrange(len(seq)) to iterate over the indices of a sequence (strange, I know). In my own code, I try to refer to indices as little as possible. When I see this... for index in xrange(len(seq)): Instead of this... for item in seq: ...I take that as a subtle hint that I need to rethink that part of the code. But that's mostly a matter of individual style. Anyway, done ranting (again!). Have a good one. From python at rcn.com Tue Mar 26 04:18:56 2002 From: python at rcn.com (Raymond Hettinger) Date: Tue, 26 Mar 2002 04:18:56 -0500 Subject: Difference between eval and exec ?? References: Message-ID: "Thomas Weholt" wrote in message news:uEWn8.8$Vme.170401280 at news.telia.no... > Eval and exec seem to have the same effect. What's the real difference? One is for expressions and the other for statements. Eval computes the value of an expression like, 3*x+1. Exec is for commands like import this or print that. Exec itself is a statement that compiles and runs code strings as if you had typed them in a .py file and ran the file. Eval is an expression that can be embedded in other expressions or used on the right hand side of an assignment: >>> x = eval('3+4') * 10 >>> print x 70 > > In this case : docs != enlightenment. Hmm, this raises the question of whether my answer == enlightenment or answer is enlightenment or answer in ['obfuscation', 'muddledthought', 'misinformation'] > > Best regards, > Thomas Weholt > > > Raymond Hettinger From nixdisciplenews at hotmail.com Wed Mar 20 23:07:36 2002 From: nixdisciplenews at hotmail.com (Felix) Date: Wed, 20 Mar 2002 23:07:36 -0500 Subject: Python & IRC Message-ID: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> Greetings everyone, I'm not sure if you guys here might be able ot help me but i have been looking up and down for a irc client that alllows me ot script in python. I found one but it doesn't seem that the owners of this client are making any type of head way in it's development. I know Xchat allows to use python as a scripting language but that is with the linux version not windows. If anyone here has experience with irc and creating scripts for a particular irc client please your help would be greatly appreciated in pointing me in the right direction. From amir.hadar at israel.sun.com Tue Mar 19 11:45:59 2002 From: amir.hadar at israel.sun.com (Amir Hadar) Date: 19 Mar 2002 08:45:59 -0800 Subject: nested_scopes with execfile Message-ID: <10ecacee.0203190845.4fa4e35d@posting.google.com> Hi I've encountered a problem when executing a file within a function: #----- Test1.py ------------------ from __future__ import nested_scopes def f(): execfile("Test2.py") f() # EOF Test1.py ------------------- #--------Test2.py ---------------- def f1(): print "OK it works" def f2(): f1() f2() #EOF Test2.py -------------------- When executing the Test1.py the following error is displayed: Traceback (most recent call last): File "", line 1, in ? File "C:\PROGRA~1\Python22\Test1.py", line 6, in ? f() File "C:\PROGRA~1\Python22\Test1.py", line 4, in f execfile("Test2.py"); File "Test2.py", line 8, in ? f2() File "Test2.py", line 6, in f2 f1() NameError: global name 'f1' is not defined The reson that I need this is because I want to make a "Load" funtion that will execute the given file (e.g. Load("Yada.py")) and then will run a function in that file (e.g. def Init():). In the example I gave the second file ("Test2.py") is loaded to the local environment of the function f() in the first file (Test1.py). Therefore the functions f1 and f2 are in that env. Now, When f2 calls f1 it should resolve its variables in the enclosing environment which is the env of f (Test1.py) but it doen't. Help Me. Amir. From timr at probo.com Wed Mar 6 02:33:13 2002 From: timr at probo.com (Tim Roberts) Date: Tue, 05 Mar 2002 23:33:13 -0800 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> Message-ID: <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> sam_collett at lycos.co.uk (Sam Collett) wrote: >I can get file attributes using os.path.getsize and os.path.getmtime >etc, but I am not sure how to convert them into something more >understandable > >e.g. >File Size to display in bytes (if < 3kb), kilobytes (if < 2MB) and >megabytes (> 2MB). How would you do that (the value I get is 12345L - >what is the L?) Do it the hard way: def ShowSize(raw): if raw < 3000: return "%d" % raw elif raw < 2000000: return "%dk" % (raw / 1000) elif raw < 2000000000L: return "%dM" % (raw / 1000000) else: return "%dG" % (raw / 1000000000L) Actually, I usually use a few more cases so that I always get two significant digits: 1.2k, 23k, 840k, 2.4M, etc. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mt_horeb at yahoo.com Fri Mar 29 15:13:24 2002 From: mt_horeb at yahoo.com (Sloth) Date: 29 Mar 2002 12:13:24 -0800 Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> Message-ID: <67abb823.0203291213.3870b623@posting.google.com> Again, thanks for all of the thoughtful replies. I've tried each of them, and I still get the same result: 1) The server starts and will serve HTTP. 2) Upon submitting a GET request, the Windows ME OS "beeps" once 3) The page hangs without returning the result. 4) The WinME machine needs to be powered down completely, or it will hang indefinitely. Strange result, I'm sure you'll all agree... My guess is that this has more to do with WinME than anything else. Apache serves CGI just fine. Tomcat will also serve Servlets without complaining. Any experience in the group with WinME or a similar issue with Win 9x? Thanks again! Jeremy. sandskyfly at hotmail.com (Sandy Norton) wrote in message news:... > Jeremy wrote: > > > I want to be able to do - have Python start a CGI server, serve a > > page, get form data, get data from a database, and display dynamic > > content. I don't need anything industrial strength, just something > > that can handle a single user. > > > OK. This one has bugged me before even though it's actually quite simple: > > > > [1] create the script that will instanciate CGIHTTPServer (server.py) > # this is my favorite part (-: > from CGIHTTPServer import test as serve > if __name__=='__main__': serve() > > [2] create an html file which is going to call your python cgi script (test.html) > > > CGI Test > > >
    > > >
    > > > > > [3] create a folder in the same directory as the two files above (cgi-bin) > > [4] create the script that will be called by your html file (testcgi.py) > #!python > > import cgi > print "Content-Type: text/plain\n\n" > form = cgi.FieldStorage() > for name in form.keys(): > print "Input: " + name + " --> " + form[name].value + "\n" > print "Finished!" > > [5] point your browser to http://localhost:8000/test.html > > and enjoy. > > ciao > > Sandy From rinnes at integraonline.com Sun Mar 17 20:05:07 2002 From: rinnes at integraonline.com (Robert Innes) Date: 17 Mar 2002 17:05:07 -0800 Subject: Python on an ARM Linux Graphics Client Plus Message-ID: <55ddffcb.0203171705.3fb1d286@posting.google.com> Been killing myself trying to build this to no avail. I know it can be done but I have not been able to get a good version. Could some kind person help me preserve what little hair I have left and tell me how they did it or point me to a binary that I can copy to my system? Thanks in advance Bob From store_li at sina.com Tue Mar 12 10:07:37 2002 From: store_li at sina.com (Ricky) Date: Tue, 12 Mar 2002 23:07:37 +0800 Subject: Is there any wxPython turtor? References: <3C865341.8D190235@cablespeed.com> <3C876878.E5E9FC6D@engcorp.com> Message-ID: I can't ping it. "Peter Hansen" wrote in message news:3C876878.E5E9FC6D at engcorp.com... > Ricky wrote: > > > > Thank you, I find a lot of resources. > > > > But wxpython.org is still not available for me. > > It's very likely it's your problem, not the site's. I can > see it fine, and could before as well. Try doing a > "ping wxpython.org" and if that works, it's your browser > or firewall settings that are bad. > > -Peter From stevewilliams at wwc.com Sat Mar 16 06:32:02 2002 From: stevewilliams at wwc.com (Steve Williams) Date: Sat, 16 Mar 2002 11:32:02 GMT Subject: Python-DB2 module and DB2 Connect References: <3C90A125.4020208@stroeder.com> <3C90BF28.8080301@stroeder.com> Message-ID: <3C932F02.259AD2A1@wwc.com> =?ISO-8859-15?Q?Michael_Str=F6der?= wrote: > Michael Str?der wrote: > > > > Anyone here which had success with using DB2-Python-0.991 (see > > ftp://people.linuxkorea.co.kr/pub/DB2/) build against DB2 Connect? > > Seems to work. (DB2 Connect under Linux against DB2 OS/390 6.x) > > Ciao, Michael. With DB2 UDB EE 7.1 on AIX 4.3.3.1, Python 1.5.2 and DB2.py 0.991 create table X(Y decimal(5,2), Z integer) cursor.execute("insert into X(Y,Z) values ?, ?",('123.45','10')) fails with SQL0408N, SQLSTATE=42821, type mismatch. However, cursor.execute("insert into X(Y,X) values cast(? as decimal(5,2)),cast(? as integer)",('123.45','10')) succeeds. The failing insert succeeds on Windows 2000 with mxODBC and ODBC connected to the same database. The Windows CLI/ODBC settings don't seem to show any particular magic. Steve Williams From chris_mk at hotmail.com Thu Mar 28 18:58:56 2002 From: chris_mk at hotmail.com (Christopher) Date: 28 Mar 2002 15:58:56 -0800 Subject: Image in a module question References: <3CA2E042.2080307@attbi.com> Message-ID: Thanks for the feedback, I looked at the code and it gave me some great ideas. Although, a little too late, lol (I actually may end up using it). I ended up 're-inventing the wheel' although, in my case, it was kind of fun (though, I still need help). I couldn't figure out the image2py module that came with PIL (I kept getting errors when I tried to import the resulting file). So I wrote my own. It ends up doing what I wanted but at a price, the resulting module is much larger than the original picture (this has to do with the fact that I was getting errors when I tried to use the data in strings, so I made a list instead. Any way, I'll post my code at the end of this post (please be gentle, I am still struggling through the learning phase of this whole programming thing ;-) ). Pete Shinners wrote in message news:<3CA2E042.2080307 at attbi.com>... > i've got a working tool that does this. although it uses pygame to load > and display the image (could probably be switched to PIL without too > much effort) > > http://www.pygame.org/pcr/submissions/01142002b.html """ CK_Image2Py To save an image in a module: Make_Module() To open an image in a module: import ImageTk from Tkinter import * myImage = CK_Image2Py.Open_Module() # Enter the module root = Tk() # create a Tk() object myNew = ImageTk.PhotoImage(myImage) # Convert the image into Tk Label(root, image = myNew).pack() # Include the image in an object root.mainloop() # Run the Tk object """ import sys import SysSetUp import zlib import tkFileDialog import Tkinter import Image import StringIO import ImageTk from Tkinter import * def Find_Image(): myPicFile = tkFileDialog.askopenfilename() return myPicFile def Compress_Image(Img_File_Name): myString = file(Img_File_Name, 'rb').read() myCompString = zlib.compress(myString) return myCompString def SaveString(Compressed_String): myModule = tkFileDialog.asksaveasfilename() myList = [] for x in Compressed_String: append_this = r"""%s""" % x myList.append(append_this) myString = 'IMAGE_List = %s' % myList file(myModule, 'wb').write(myString) def Decode_Module(module_list): module_string = '' for x in module_list: module_string += x myString = zlib.decompress(module_string) return myString def Make_Image(Image_String): myImage = Image.open(StringIO.StringIO(Image_String)) return myImage def Make_Module(): myImageFile = Find_Image() myCompressedImage = Compress_Image(myImageFile) SaveString(myCompressedImage) def Open_Module(): myModule = Find_Image() myModulePath = myModule[:myModule.rfind(r"""/""")] sys.path.append(myModulePath) myModuleName = myModule[(myModule.rfind(r"""/""")+1):][:-3] exec("from %s import IMAGE_List" % myModuleName) myImageString = Decode_Module(IMAGE_List) The_Image = Make_Image(myImageString) return The_Image def Open_Specific_Module(Module_Name): myModuleName = Module_Name[:-3] exec("from %s import IMAGE_List" % myModuleName) myImageString = Decode_Module(IMAGE_List) The_Image = Make_Image(myImageString) return The_Image if __name__ == "__main__": import Image if len(sys.argv) == 1: myImage = Open_Module() # Enter the module mainloop() else: Open_Specific_Module(sys.argv[1]) root = Tk() # create a Tk() object myNew = ImageTk.PhotoImage(myImage) # Convert the image into Tk widget = Label(root, image = myNew) widget.pack() # Include the image in an object root.mainloop() # Run the Tk object From nospam at mega-nerd.com Sat Mar 9 19:16:37 2002 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sun, 10 Mar 2002 00:16:37 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> Message-ID: <3C8AA5E4.982FC689@mega-nerd.com> brobbins333 at shaw.ca wrote: > > I understand the problem of rounding errors with binary numbers. > However, the rounding functions of other languages work around it and > return a usable result. What have they got that Python hasn't got? Possibly other scripting languages have a feature which includes the current printing representation with the floating point object. This would however surprise me somewhat. Have you tried that specific example with other languages? I looked at Perl and it doesn't have a round function. Apparently the preferred method in Perl is sprintf ("%.2f", 56.78923) which returns a string instead of a float. Once a float is represented as a string you get the behviour you are after. > ps -- your name is very familiar. i think i've read one of your books. I only have one, "SAMs Teach yourself C for Linux Programming in 21 days". I also have a couple of Free Software packages out there. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ "If dolphins are so smart, why do they live in igloos?" -Eric Cartman From jimd at vega.starshine.org Fri Mar 29 02:31:16 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 29 Mar 2002 07:31:16 GMT Subject: Streaming XML-RPC? References: <3C9F51EE.5000203@jerf.org> <3C9FAF96.5DE9A0@bgb-consulting.com> Message-ID: In article , Magnus Lie Hetland wrote: >In article , Skip >Montanaro wrote: >> Don> Are there any decent (finished/tested) Jabber libraries for Python? >>Don't know what its status is, but there is jabberpy: >> http://jabberpy.sourceforge.net/ > It's LGPL, which may make it unsuitable for some projects (like the > standard Python library). But it seems to support the basic protocol. Why would LGPL be allergic to the Python License? From dgallion1 at yahoo.com Thu Mar 7 20:10:59 2002 From: dgallion1 at yahoo.com (Darrell) Date: Fri, 08 Mar 2002 01:10:59 GMT Subject: Seek fame(*) & fortune(**) as a Python developer References: Message-ID: Skip Montanaro wrote: > Whether or not you want to be able to check files into the CVS repository, > if you want to contribute, you should probably subscribe to the python-dev > mailing list. You can subscribe here: > > http://mail.python.org/mailman/listinfo/python-dev > Have you changed to acceptance criteria? Last time I tried to join that list they told me to go away. Filled my time up with other things since then. --Darrell From logiplexsoftware at earthlink.net Thu Mar 28 18:22:14 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 28 Mar 2002 15:22:14 -0800 Subject: Exceptions and modules / namespaces question In-Reply-To: <1136f745.0203281521.76a1a62c@posting.google.com> References: <1136f745.0203281521.76a1a62c@posting.google.com> Message-ID: <20020328152214.5bba0cbb.logiplexsoftware@earthlink.net> On 28 Mar 2002 15:21:24 -0800 Preston Landers wrote: > The problem, in a nutshell, is that I can't seem to catch an exception > in the same module it was defined in if the function that raised the > exception is in a different module, because of naming issues. > > -------module2.py: > > import module1 > > def raise_foo_exception(): > raise module1.FooException("HELLO") > > -------module1.py: > > import exceptions, sys > > class FooException(exceptions.Exception): > pass > > def main(): > > try: > import module2 > module2.raise_foo_exception() > except FooException, e: > print "Got it!" > except: > xi = sys.exc_info() > print "Didn't get it. Got this instead:", xi[0], xi[1] > > if __name__ == "__main__": > main() > > ---------result: > > Didn't get it. Got this instead: module1.FooException HELLO > > > > The question is, how do I explicitly catch FooException in main() > without doing a catch-all except: and then examining the type of my > exception, and making a decision based on that. It's kinda clunky. try: import module2 module2.raise_foo_exception() except module2.FooException, e: print "Got it!" except: xi = sys.exc_info() print "Didn't get it. Got this instead:", xi[0], xi[1] -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From john at yahoo.com Sun Mar 31 12:07:04 2002 From: john at yahoo.com (John Warney) Date: Sun, 31 Mar 2002 17:07:04 GMT Subject: newbie question on lists, getting an error on basic addition Message-ID: >>> alist = [1, 2, 3, 4] >>> counter = 0 >>> answer = 0 >>> alist [1, 2, 3, 4] >>> counter 0 >>> answer 0 >>> while counter < 6: ... answer = answer + alist[counter] ... counter = counter + 1 ... Traceback (most recent call last): File "", line 2, in ? IndexError: list index out of range >>> answer 10 why am i getting this error when it works??? Rob From trentm at ActiveState.com Thu Mar 28 14:25:44 2002 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 28 Mar 2002 11:25:44 -0800 Subject: PEP262 - database of installed packages In-Reply-To: ; from akuchlin@ute.mems-exchange.org on Tue, Mar 26, 2002 at 08:31:54PM +0000 References: Message-ID: <20020328112544.A13176@ActiveState.com> [A.M. Kuchling wrote] > In article , > David Ascher wrote: > > PPM bdist target works which we're looking at replacing soon. PPM3 (for > > Perl only so far) is a major rewrite of PPM which added a bunch of cool > > features. For info on that, see: http://aspn.activestate.com/ASPN/PPM. > > Is the PPD format changing in PPM3 at all? Yes, a couple of tags were added under the tag to enable a PPD to decribe (1) what language it is suitable for (in our current usage, Perl or Python) and (2) what range of versions of that language interpreter it will work for. Trent -- Trent Mick TrentM at ActiveState.com From paul at boddie.net Mon Mar 18 06:17:26 2002 From: paul at boddie.net (Paul Boddie) Date: 18 Mar 2002 03:17:26 -0800 Subject: Relieved but disappointed: The Pariah thread References: Message-ID: <23891c90.0203180317.7e8c92d0@posting.google.com> Tim Churches wrote in message news:... > > [...] I was a bit disappointed that no-one at all commented > on the pictorial reference which I gave to sum up my view of the > .NETification of Python: > http://www.sciam.com/2002/0102issue/010250100.html I think that someone posted a reference to that picture before, hence the lack of reaction. Amusingly, not only does the picture involve a python, but it looks like it comes from an actual Monty Python sketch. ;-) Paul From jason at jorendorff.com Tue Mar 12 03:48:33 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Tue, 12 Mar 2002 02:48:33 -0600 Subject: Ho to use a regular expression group reference as hash key In-Reply-To: Message-ID: Raymond Hettinger wrote: > >>> import re > >>> target = 'A sample sentence with entry1 and entry2' > >>> person={"entry1":"value1","entry2":"value2"} > >>> re.sub( r'b\w+\b', lambda word: person.get(word,word), target ) > 'A sample sentence with entry1 and entry2' The fourth line isn't exactly right. Should be: >>> re.sub(r'\b\w+\b', lambda word: person.get(word, word.group(0)), target) 'A sample sentence with entry1 and entry2' ## Jason Orendorff http://www.jorendorff.com/ From jimmy at retzlaff.com Sat Mar 30 16:22:13 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sat, 30 Mar 2002 13:22:13 -0800 Subject: PEP 285: Adding a bool type Message-ID: Greg Weeks wrote: > I would, though, be happy to see built-in variables bound to 0 and 1. I assume you mean that the only change would be to implicitly have built-ins like: False = 0 True = 1 There is a trap with this approach in that some people will come to conceptualize False/True as being instances of a Boolean type, even though they are not. Consider code like: if MyCoolFunction(12.3) == True: print 'cool' If MyCoolFunction returns a "true" value which is not 1 (e.g., -1), then this code will not take the path suggested by the misconception that True is an instance of a proper type (which would imply robust implementations of comparison operators). This trap is common in C/C++ code that #defines true and false. Some people have to be constantly reminded not to compare to true, and those reminders all too often come in the form of long debugging sessions. Jimmy From usenet at thinkspot.net Mon Mar 25 02:24:10 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 24 Mar 2002 23:24:10 -0800 Subject: files and reading from them References: Message-ID: On Mon, 25 Mar 2002 06:30:30 GMT, "Avi Homes" wrote in comp.lang.python in article : > > What i would like to do is pull a readline or somesuch.. and have it take in > the whole thing, and then just let me assign that to a empty name, and turn > it into a new dictionary.. like say > file.seek(1) > //thats how i'd go to the first place in the file correct? > X=file.readline() > > and now i can say print X['IName'] ... and its turned into a dictionary.. i > am most likely going about this *all* wrong. Technically, you can accomplish this by x = eval(file.readline()) if you know for a fact that your line of text from the file will be a correctly formatted, string representation of a dictionary, and that you can depend on that 100%, no ifs, ands or buts. Whether this is the best way to accomplish what you want is another question. Shelve and pickle (as mentioned elsewhere) are some modules that should help, possibly. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From bernie at 3captus.com Wed Mar 13 21:04:06 2002 From: bernie at 3captus.com (Bernard Yue) Date: Thu, 14 Mar 2002 02:04:06 GMT Subject: Zope References: <3C8FED4D.A8C0470@3captus.com> Message-ID: <3C90058B.8813C41A@3captus.com> Andy McKay wrote: > On March 13, 2002 04:20 pm, Bernard Yue wrote: > > Are there anybody using Zope 2.4.3 with Python 2.2 in production > > environment? Problems? > > Lots of people are reporting segfault / crashes with Python 2.2 / 2.1.2 at > the moment. Is this your problem? > Yes, indeed. Just needed some confirmation. Thanks Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From QnickQm at alum.mit.edu Wed Mar 13 10:22:18 2002 From: QnickQm at alum.mit.edu (Nick Mathewson) Date: Wed, 13 Mar 2002 15:22:18 GMT Subject: structseq and keywords? References: Message-ID: As the original author of the structseq patch, I should respond. In article , Michael Hudson wrote: > quinn at vomit.ugcs.caltech.edu (Quinn Dunkan) writes: [...] > In the current implementation, you're not really expected to create > structseq objects. Why would you? I agree with this. One of the explicit design decisions was that since it's so easy to create a lookalike class in Python, there's not a lot of reason to expose structseq as a metatype. In the case of its uses today (localtime, stat, statvfs), there didn't seem to be a lot of reason to want to create these objects yourself. BTW, people should not (IMO) be creating new structseq-based interfaces at all. Here's why: The structseq interface is meant to be used in cases where legacy code expects a tuple, but where an attribute-based interface would be more sensible. If you're creating a new interface, and you want an attribute-based interface, don't use a structseq in the first place. >> I've been meaning to give python access to structseqs, since I think >> it would be useful for python as well as C code. > > Hmm. I think they're a bit specialized for that. You could probably > whip up something nearly equivalent... [...nice Python equivalent of structseq elided...] > Doesn't do everything structseqs do, but that's mostly a matter of > typing. Watch out, though: If you're supporting legacy code that expects a tuple, you'd better support _all_ the tuple operations out there: somplace, there is going to be an eccentric who's been using slices and concatenations to manipulate the things. (And if you're _not_ supporting legacy code that expects a tuple... don't use a structseq-ish class at all.) If-a-camel-is-a-horse-designed-by-committee-then-is-a-llama- a-horse-designed-for-backward-compatibility-with-a-sheep?-ly Y'rs, -- Nick Mathewson Remove Q's to respond. No spam. From greg at cosc.canterbury.ac.nz Thu Mar 7 20:32:06 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 08 Mar 2002 14:32:06 +1300 Subject: PEP 284, Integer for-loops References: Message-ID: <3C881496.4CB548F4@cosc.canterbury.ac.nz> Bjorn Pettersen wrote: > > If it can only be used in one context in the > language I'm left to wonder if it's not just extra "noise" for everyone > to have to learn... Just in case anyone's forgotten, it can also be used in a list comprehension: r = [i for 0 <= i < 10] If efficiency is a concern, the compiler could recognise this as a special case and substitute an appropriate range() call. (And too bad about the difference wrt side effects on i -- I don't care!) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From aahz at pythoncraft.com Sun Mar 31 20:50:39 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 20:50:39 -0500 Subject: python name spaces References: Message-ID: In article , Daniel Ortmann wrote: > >I must admit I am frustrated by Python's seeming lack of powerful name >space support. I'd just like to point out that Python's namespace support is different from Perl's. For example, in Python you can do this: def foo(): pass foo.permissions = 'author' -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From akakakhel at attbi.com Sat Mar 9 18:53:43 2002 From: akakakhel at attbi.com (Ali K) Date: Sat, 09 Mar 2002 23:53:43 GMT Subject: The Text Widget References: <5Hzg8.72869$vP.290047@rwcrnsc51.ops.asp.att.net> <3C82E8C4.24531DE7@tds.net> Message-ID: I want to know how to write inside a text widget from inside my program. The following code didn't work. def enterPress: comm = input.get() history.insert(INSERT, comm) here input is the entry widget from which i am gathering my data and history is the text widget i am trying to write to. This code adds some text into the textbox, but not on a new line. How do i get it to do that? "Eric Brunel" wrote in message news:a5vcb6$2vbb$1 at norfair.nerim.net... > Edward K. Ream wrote: > > First, note that if you bind to a key-press () event, when the > > event handler is called the Text widget hasn't been changed yet(!) > > Other frameworks provide a "text will change" event and a "text did > > change" event, but AFAIK Tk does not. > > Tk does: it's simply that the event "" is a short-cut for > "", called when the key is depressed, so before the insertion > happened. To do a binding after the text has been inserted, the event is > "". > > For Ali's problem, I don't exactly understand what you want to do. When > reading your mail, it seems to me that a sub-class of Tkinter.Text with a > redefined "insert" method may do the trick. Or is it more complicated? > > HTH > - eric - From siu99aw at rdg.ac.uk Sun Mar 3 06:24:38 2002 From: siu99aw at rdg.ac.uk (Alex Willmer) Date: Sun, 03 Mar 2002 11:24:38 +0000 Subject: C/C++ to Python translater References: <5e8bd451.0203011049.5d12d3a2@posting.google.com> <3C811653.871C5BEF@tds.net> Message-ID: <3C8207F6.8000008@rdg.ac.uk> David Abrahams wrote: > "Edward K. Ream" wrote in message > news:3C811653.871C5BEF at tds.net... > >>leo.py contains a script called c2py.py that I have used to translate >>all my C++ code to Python. It does about 80% of the work and is mostly >>intended to be run from inside Leo. IIRC there is another entry in >>c2py.py script to translate "exterior" files and this can be run from >>idle, say. Munging source to Python is actually remarkably easy to do. > > Biggest problem I'm having is that I can't find it. > http://prdownloads.sourceforge.net/leo/leo-1.0.zip doesn't contain a file > called c2py.py. Did you have something else in mind? > Perhaps this is what you're looking for? http://mail.python.org/pipermail/python-list/2002-January/079454.html Regards Alex From greg at cosc.canterbury.ac.nz Thu Mar 7 21:54:29 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 08 Mar 2002 15:54:29 +1300 Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> Message-ID: <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> Bengt Richter wrote: > > The problem is to do it by using an existing source of text, without > changing the text, and without using an external file to delimit it. Even something like q'delim' doesn't allow you to easily use completely arbitrary text, because you still have to pick *some* string that doesn't occur in the text. Although you don't have to modify the text, you do have to inspect it in order to choose a suitable delimiter. I have another idea that doesn't suffer from that problem. def string my_string: This is a free-form string constant. Its value consists of all the text at this indentation level, verbatim, with the indentation stripped off. It can contain ', ", ''', """, \ or any other characters. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From robin at jessikat.fsnet.co.uk Tue Mar 12 06:08:07 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 12 Mar 2002 11:08:07 +0000 Subject: Has Mark Hammond attained pariah status yet? References: Message-ID: In article , Simon Brunning writes >> From: Tim Churches [SMTP:tchur at optushome.com.au] >> >> So asks an article on Mark in the IT section of today's Sydney Morning >> Herald - see >> http://www.it.mycareer.com.au/news/2002/03/12/FFXMFP3LOYC.html > >Not with those of us who use the Win32all package which he has so generously >donated to the community, no. > >I-know-you-were-joking-but-a--wouldn't-have-been-out-of-place-ly y'rs, >Simon Brunning >sbrunning at fuckmicrosoft.com .... all the evidence suggests that python.net (or whatever it will be called) will not be python as we know it. Apparently .net will not support multiple inheritance etc etc. There was an interesting recent article on the subject of what .net/cli is not able to do. Another example of embrace and strangle. -If only Bill Gates had a mustache and lived in Baghdad-ly yrs- Robin Becker From jason at jorendorff.com Wed Mar 13 01:13:50 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Wed, 13 Mar 2002 00:13:50 -0600 Subject: Question about scientific calculations in Python In-Reply-To: Message-ID: Jason Orendorff wrote: > Numeric lets you mix arrays and scalars randomly and it happily > distributes multiplication and so forth. So the resulting code > looks a bit more like the original formulas. Some folks like that. Keep in mind, though, that the code I wrote creates a huge 2D array when it is presented with largeish 1D arrays as arguments. So if s_vector is 10000 elements and r_vector is 10000 elements, then a 800-MB array is created. If you've got the RAM, this is okay; otherwise you're in trouble. Also, does anyone have weave.blitz? I'd like to see how it does compared to the other approaches. ## Jason Orendorff http://www.jorendorff.com/ From mac at magusdesigns.com Wed Mar 6 18:24:15 2002 From: mac at magusdesigns.com (99miles) Date: 6 Mar 2002 15:24:15 -0800 Subject: Web scripting with Python (1st post here, also :-) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: Hi- Well, there are sample scripts that install with Python. They can be helpful. The documentation is also all available on python.org good luck- Mac inerte at hotmail.com (Julio Nobrega) wrote in message news:<40c3f5da.0203061114.18f7fea6 at posting.google.com>... > Hi! > > I am used to do web scripting using PHP. As a new adventure, I am > trying to learn Python. I really wished I could write 'desktop' apps > with Python, but from what I read (and from what I am planning), > that's a little far away from my current trouser snake knowledge (I > also heard you all like those kind of quotes ;-) > > So, I am looking for examples that might help me. Yes, I saw Zope. > Waaaaay too much. Also read Web Programming Topic Guide on python.org, > way less practical than I like. Picky, ain't I? :-) > > I searched for complete (yet simple), or incomplete (yet with > explanations) apps on cgi-resources, parnassus and hotscripts, but I > don't have background to decide what's good or bad Python. And surely > I don't want to start with the wrong foot :-) > > Well, enough is enough, isn't? Where do I start? It's for a weblog > (Kuro5hin-like) system. > > Anyone have a tip for me? Examples? Squisdot is the way to go? > > Btw, sorry for any grammer mistakes. My coconuts are in a tropical > zone and english is not my primary language. If anyone does want to > talk in Portuguese, I can :-) > > Thanks a lot, > > Julio Nobrega. From fredrik at pythonware.com Sun Mar 3 17:32:21 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 03 Mar 2002 22:32:21 GMT Subject: new images from strings using PIL References: Message-ID: "BL" wrote: > pixels = "1 2 3 4 5 6" //test pixels > im = Image.fromstring("I", (2,1), pixels) //create a 3x2 image from pixels try this instead: >>> pixels = "1 2 3 4 5 6" >>> i = Image.new("L", (3, 2)) >>> i.putdata(map(int, pixels.split())) >>> list(i.getdata()) [1, 2, 3, 4, 5, 6] >>> i.getextrema() (1, 6) (getdata returns a sequence object of an undefined type. to see what's in it, convert it to a list or tuple before printing it) From spokra at home.com Sun Mar 3 14:24:26 2002 From: spokra at home.com (Steven Pokrandt) Date: 3 Mar 2002 11:24:26 -0800 Subject: SocketServer.py Message-ID: When using the StreamRequestHandler the read incoming data. how can one tell if the tcp connection has gone away? I don't see a mothod to check EOF in the socketserver class. From amuys at shortech.com.au Wed Mar 13 19:16:45 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 13 Mar 2002 16:16:45 -0800 Subject: Another socket/thread question References: <3C8FA777.8A5B07D1@accessforall.nl> Message-ID: <7934d084.0203131616.488b4ace@posting.google.com> Ype Kingma wrote in message news:<3C8FA777.8A5B07D1 at accessforall.nl>... > Ken wrote: > > > > Hey everyone.. > > > > I've got a thread that continously listens to a socket, and reports what it > > receives. Blocking is turned on, and I would like it to stay that way since > > the only thing the thread has to do, is listen to the socket. > > > > My question is when the socket needs to be closed (program shuts down, or > > that user is being disconnected by the server) is it possible to interupt a > > socket.recv ()? > > When you close the socket from another thread or by the server, > the pending socket.recv() should terminate with some error condition. > It's best to test both situations, however. > Far cleaner to open a control pipe to the thread and have the thread wait on both the socket and the pipe. This applies equally to multi-process and multi-threaded models. This has the added advantage that you can extend the shutdown protocol to do other things such as request status, stats, or state-changes. One hassle with this might be x-platform semantics, as I believe windows is broken in this regard. Still I would assume windows can still do pid/interface restricted tcp or preferably unix domain sockets, which would allow you to emulate the above. Andrae Muys From loewis at informatik.hu-berlin.de Thu Mar 7 09:41:51 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 07 Mar 2002 15:41:51 +0100 Subject: HP-UX 10.2 deprecated? References: Message-ID: Anthony Baxter writes: > This has come up many times in the past - what is needed is for someone > with deep HP/UX knowledge and exposure to a bunch of different HP/UX > versions to volunteer to fix it. If HP offered something like Compaq's > TestDrive machines, or donated some boxes to the sourceforge compile > farm, someone might be able to look at it. At the moment, there's no-one > who's stepped forward to fix this. So I think your suggestion to add a Resolution: HP-UX into the SF bug tracker is quite attractive :-) Martin From thoa0025 at mail.usyd.edu.au Fri Mar 29 21:51:33 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sat, 30 Mar 2002 02:51:33 GMT Subject: execfile() - change python version? Message-ID: Hi, i was wondering if there is a way to change which version of python processing the file when execfile(). i wish to use python2.2 on the main file, and python2.1 on the file passed into the argument of execfile(). reason being: there is some sort of mis configuration error on the server i am using python on. cheers trung From bokr at oz.net Sun Mar 10 18:58:48 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 23:58:48 GMT Subject: win32 extension: rare PythonService problem References: Message-ID: On 10 Mar 2002 21:55:37 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >But I'd check the event logs (run "%SystemRoot%"\system32\eventvwr.exe) first Oops, misplaced quote, that won't work verbatim. Try "%SystemRoot%\system32\eventvwr.exe" Or (at least on NT4), find it via start>programs>adminstrative tools>Event viewer Regards, Bengt Richter From gvdbogae at vub.ac.be Tue Mar 5 10:15:34 2002 From: gvdbogae at vub.ac.be (Geert-Jan Van Den Bogaerde) Date: Tue, 5 Mar 2002 16:15:34 +0100 (MET) Subject: Generators and iterators In-Reply-To: Message-ID: On 5 Mar 2002, Bertrand Geston wrote: > Hello, > > I just quickly red the page about new features in Python 2.2 and tried - for > fun - to test it. It must be obvious but I really don't see why, in the > console transcript below, z.next() send back None and not 1,2 and 3 > whereas it does it correctly 3 times, no more no less. > > TIA. > > B. > > Sorry for the methods and class names. Here is it: > > PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see > 'Help/About PythonWin' for further copyright information. > >>> from __future__ import generators > >>> def t(): > ... yield 1 > ... yield 2 > ... yield 3 > ... > >>> tt = t() > >>> tt > > >>> tt.next() > 1 > >>> tt.next() > 2 > >>> tt.next() > 3 > >>> tt.next() > Traceback (most recent call last): > File "", line 1, in ? > StopIteration > >>> class Z: > ... def __init__(self): > ... self.ttt=t() > ... def __iter__(self): > ... return self > ... def next(self): > ... self.ttt.next() You probably want return self.ttt.next() here instead of just self.ttt.next() Geert-Jan > ... > >>> z=Z() > >>> for i in z: > ... print i > ... > None > None > None > >>> z=Z() > >>> z.next() > >>> z.next() > >>> z.next() > >>> z.next() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in next > StopIteration > -- > http://mail.python.org/mailman/listinfo/python-list > From tdi01fhu at syd.kth.se Fri Mar 29 04:28:34 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Fri, 29 Mar 2002 10:28:34 +0100 Subject: The Python Way Message-ID: >>> Aahz 03/29/02 04:42 AM >>Thinking of automatic locking concepts, has there >>been a PEP for (can't remember if >> was c.l.py or python-dev), but no PEP. Actually, >>the discussion came >>up with something a bit more general, along the >>lines of pre- and post-code: On a side note, what does PEP stand for?, Ive been seeing it all over the mails but I have no clue what it is. :) /Fredrik From dsavitsk at e-coli.net Thu Mar 14 16:46:10 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 14 Mar 2002 21:46:10 GMT Subject: basic statistics in python References: <3C910734.9030109@northwestern.edu> Message-ID: "Louis Luangkesorn" wrote in message news:3C910734.9030109 at northwestern.edu... > I don't recognize bi-serial correlations, maybe there is a better name? it is used to validate test items. the fmla is ... x = score on item y = score on all other items n = number of people taking the test n(sigma(xy)) - (sigma(x))(sigma(y)) ----------------------------------- sqrt( ((n)(sigma(xx))-(sigma(x))(sigma(x))((n)(sigma(yy))-(sigma(y))(sigma(y)) ) something like that, there may be a parenthesis or 2 out of place btw, thanks for all the suggestions. it still isn't clear what the best solution is, but i am thinking that dumping data to R or SPSS via COM might be the least painful. -d From phr-n2002a at nightsong.com Wed Mar 6 18:07:22 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 06 Mar 2002 15:07:22 -0800 Subject: Python daemon instead of CGI programs References: <88bc63c6.0203061444.30ad9c44@posting.google.com> Message-ID: <7x7kope1n9.fsf@ruckus.brouhaha.com> writeson at earthlink.net (Doug Farrell) writes: > What do you think of this idea? Am I completely off base and missing > some other obvious solution? It's a sound idea, but there's already a FastCGI protocol that amounts to the same thing and is used for the same reasons. Someone has almost certainly already implemented FastCGI servers in Python. From mxp at dynalabs.de Wed Mar 6 17:15:26 2002 From: mxp at dynalabs.de (Michael Piotrowski) Date: Wed, 06 Mar 2002 23:15:26 +0100 Subject: HP-UX 10.2 deprecated? References: <1015292901.342132@cswreg.cos.agilent.com> <1015438469.628881@cswreg.cos.agilent.com> Message-ID: weeks at vitus.scs.agilent.com (Greg Weeks) writes: > Michael Piotrowski (mxp at dynalabs.de) wrote: > : When the ANSI C compiler is installed, cc always calls this compiler, > : but without -Aa or -Ae it operates in K&R mode on 10.20. To ensure > : that -Ae is always used, you can ... say > : > : CC='cc -Ae' ./configure > > With this, "make" does indeed create an executable. But "make test" fails > both times on test_threads, dying at the end with: > > test_thread > *** Termination signal 14 > > Stop. > > Oddly enough, signal 14 (ALRM) is ignored the first time "test_thead" is > listed. Yes, I'm getting something similar: ... test_sha test_signal test test_signal crashed -- exceptions.RuntimeError: (22, 'Invalid argument') test_socket test_socket_ssl test test_socket_ssl skipped -- Use of the `network' resource not enabled test_socketserver test test_socketserver skipped -- Use of the `network' resource not enabled test_sre sh: 20651 Alarm call *** Error exit code 142 However, I'd guess that this problem's neither in test_thread nor in test_sre but actually in test_signal (manages to send SIGALRM, but fails to catch it because it crashes), but I'll have to check that. -- Michael Piotrowski, M.A. From op73418 at mail.telepac.pt Wed Mar 27 10:51:23 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 27 Mar 2002 15:51:23 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Message-ID: On Tue, 26 Mar 2002 20:04:50 -0800, Geoff Gerrietts wrote: >Quoting Courageous (jkraska at san.rr.com): >> >> >I'd say the skills required to write clear, readable >> >software and clear, readable novels are not entirely >> >disjoint! >> >> Oh certainly not, you just haven't backed up to a big >> enough perspective of the cognitive domain. :) > >I think poetry and code are actually very similar. Some day I may >write a paper on that thesis, but I'm still living the experience >today.... Poetry and coding are similar in that they are both creative activities needing inteligence, imagination, etc. But there is also a world of difference between the two. A simple way to see this is how they relate to their heritage, their common dead. Best regards, Gon?alo Rodrigues From michael at stroeder.com Wed Mar 6 06:58:55 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 06 Mar 2002 12:58:55 +0100 Subject: [ANN] istring 1.0.1 released; announce list created References: Message-ID: <3C86047F.1080601@stroeder.com> Steven D. Arnold wrote: > >>>>from neo.istring import istring as i >>>>n = 100 >>>>s = i("Value is $n") >>>>s >>>> > "Value is 100" Maybe it's me but I can't see the advantage over using >>> n = 100 >>> s = "Value is %s" % (n) >>> s 'Value is 100' How about providing a more complex example illustrating the benefits of istring? Ciao, Michael. From sab at NOSPAM.freeuk.com Fri Mar 22 11:19:48 2002 From: sab at NOSPAM.freeuk.com (G. Willoughby) Date: Fri, 22 Mar 2002 16:19:48 -0000 Subject: how do i get RGB from HEX? Message-ID: Hi, i have been trying to do this for to long now, i know there is an easy way, please somebody put me out of my misery! i need to get the RGB value of a HEX number (eg, #DCDCDC). can anyone help? thanks, G. Willoughby From jeff at ccvcorp.com Thu Mar 21 16:11:11 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 21 Mar 2002 13:11:11 -0800 Subject: nested_scopes with execfile References: <10ecacee.0203190845.4fa4e35d@posting.google.com> <10ecacee.0203200516.32cb4d57@posting.google.com> Message-ID: <3C9A4C6F.5E0EAD19@ccvcorp.com> Amir Hadar wrote: > Thanks for repalying. > > I suppose you are right but this is not the correct behaviore with > nested_scopes on. As I anderstend execfile should behave as if I cut > and past the file to that position my self (as appose to import). I think (though I'm not in a position to test) that your problem comes from the fact that future directives only apply to the current file. When Test2.py is compiled, nested_scopes is not active. You have two options that I can see, that should fix your problem. One is to simply require that *all* files import nested_scopes. Of course, depending on the situation regarding your control of other developers, this may not be feasible. The other solution is to use Python 2.2, in which nested scopes are the default. Jeff Shannon Technician/Programmer Credit International From mxp at dynalabs.de Fri Mar 8 11:59:35 2002 From: mxp at dynalabs.de (Michael Piotrowski) Date: Fri, 08 Mar 2002 17:59:35 +0100 Subject: PARTIAL SOLUTION: Compiling Python 2.2 with GCC in HPUX 10.20 does not work References: <3C8875FE.9030700@vip.fi> Message-ID: pekka niiranen writes: > First of all, thank you guys for your help. > > I managed to compile Python 2.2 in HP-UX 10.20 with the following hacks: > [...] > 7) Python-2.2 source I > edited by adding line "int h_errno;" to Modules/socketmodule.c > at line 161 just above the > '#ifndef RISCOS' block: > > int h_errno; > > #ifndef RISCOS > #include > #else > #include > #define NO_DUP > int h_errno; /* not used */ > #endif > #else You can avoid this by adding -D_XOPEN_SOURCE_EXTENDED to the compiler flags... > 8) I configured python with script: > #! /usr/bin/sh > unset LANG > gmake distclean > CC=gcc ./configure --with-gcc --with-threads=no --without-cxx > --prefix=/opt/python > gmake ... e.g.: CC='gcc -D_XOPEN_SOURCE_EXTENDED' ./configure etc. [...] > And summary looks like: > > 1 test failed: test_fpformat I get the same results; if I find the time, I'll have a look at it--I don't think it's a major problem. -- Michael Piotrowski, M.A. From No at Spam.Please Thu Mar 7 11:13:38 2002 From: No at Spam.Please (Weet Vanniks) Date: Thu, 07 Mar 2002 17:13:38 +0100 Subject: Bug in the standard module random ? Message-ID: <3C8791B1.6BBC1981@Spam.Please> Hi, The gammavariate function of the standard module is documented as taking two parameters, the first one alpha is required to be > -1 and the second beta is required to be >0. However, examining the implementation, it seems that the requirement for alpha is to be >0. In spite of this, I still have a problem since I called the gammavariate function with a parameter alpha equal to 0.2 and it fails logically on the following line: ainv=_sqrt(2.0 * alpha - 1.0) Apparently, the implementation requires alpha to be > 0.5. Am i missing something or is it a bug? Best regards Weet ## -------------------- gamma distribution -------------------- def gammavariate(self, alpha, beta): # beta times standard gamma ainv = _sqrt(2.0 * alpha - 1.0) return beta * self.stdgamma(alpha, ainv, alpha - LOG4, alpha + ainv) From zoomq at itcase.com Thu Mar 21 03:02:32 2002 From: zoomq at itcase.com (Zoom Quiet) Date: Thu, 21 Mar 2002 16:02:32 +0800 Subject: how to read full file into buff for re using? Message-ID: i'm chinese python fresh men; help please! how to read full file into buff for re object using? such as: re.sub() ??! -- /======================\ | Time is unimportant; | only life important! \======================/ From henrik.motakef at web.de Fri Mar 1 03:51:25 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 01 Mar 2002 09:51:25 +0100 Subject: Python GUI References: Message-ID: <86zo1sy8ky.fsf@apo.hmotakef.int> "Avi Homes" writes: > some type of gui builder or somesuch for python Just because nobody mentioned it yet: You can use the Qt Builder (included in the default Qt distribution) with PyQt as well. hth Henrik From cce at clarkevans.com Sat Mar 23 09:58:18 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Sat, 23 Mar 2002 09:58:18 -0500 Subject: two ideoms at one blow: line-reading and regexp-matching In-Reply-To: ; from scarblac@pino.selwerd.nl on Thu, Feb 21, 2002 at 04:12:08PM +0000 References: <7xit8rhebq.fsf@ruckus.brouhaha.com> Message-ID: <20020323095818.A245@doublegemini.com> On Thu, Feb 21, 2002 at 04:12:08PM +0000, Remco Gerlich wrote: | Are you sure? writing 'if (a=3) {' must be the most common bug in C | programs. I wouldn't call it successful. In fact, Python already caught | three of those for me this week as syntax errors - that would have been bugs | in C. I'd note that good "C" style is to always put the constant as the LVALUE in this way the above looks "funny". In other words when checking for equality in C, write "if (3==a) {" this way if you forget the extra = you don't shoot yourself in the foot (it is a syntax error). A good lint program should be able to flag these cases for you. After a while any equality test where the variable is on the left just "looks funny"... Best, Clark From tim.one at comcast.net Mon Mar 4 03:53:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 04 Mar 2002 03:53:18 -0500 Subject: Can somebody kill getpathp for me? In-Reply-To: <3C81C613.8000409@skippinet.com.au> Message-ID: [Tim] > If, e.g., I set PYTHONHOME to \Python22, then execute python while *in* > my \Python21 directory (these both referring to PythonLabs distros), > then Python 2.1.2 comes up with sys.path pointing entirely at Python 2.2 > directories. This is insane, but shows that PYTHONHOME works the way > getpathp.c says it works. [Mark Hammond] > insane by design ;) PYTHONHOME was supposed to be a global override. What's insane is that *I* would do such a thing, not that PYTHONHOME believes me. It's great that PYTHONHOME believes me. The other form of insanity is that there is no "global override" for *all* of sys.path. Indeed, the lack of a global, no-kidding, I-really-mean-it, don't-you-dare-try-to-outguess-me-at-all override is exactly Chris's problem. > Didn't someone promise to document all this once? Well, you did, but you were Australian then, and we won't hold you to what you promised before you became a tad civilized . > ... > Or, use MSVC or some other resource editor to change the single string > resource in the compiled Pythonxx.DLL (ie, no need to rebuild the DLL). > This will cause a different registry key to be used (by the core, and > also by extensions that are registry aware). Hmm. In the absence of a global no-kidding whole-sys.path override, maybe someone would like to contribute a Python script to fiddle the DLL. *That* should end this thread . you-can-lead-a-python-to-a-rat-but-you-can't-make-it-eat-ly y'rs - tim From johnl at axis.com.au Wed Mar 20 19:03:51 2002 From: johnl at axis.com.au (John Lehmann) Date: 20 Mar 2002 16:03:51 -0800 Subject: Slices... what are they good for? Message-ID: I had forgotted slices existed, until I was making an object that I was pretending was a tuple. I was shocked to find that this didn't work: >>> l = ['a', 'b', 'c'] >>> l[1:2] 'b' >>> l[ slice(1,2) ] Traceback (most recent call last): File "", line 1, in ? TypeError: sequence index must be integer -- | John J. Lehmann, jlehmann(@)cgi-australia.com + Chicago Bulls star has filed papers seeking to annul his 9-day-old + marriage to the former Playboy and Baywatch babe, saying he was of + "unsound mind" when the wedding took place. From maxm at mxm.dk Mon Mar 11 08:10:24 2002 From: maxm at mxm.dk (Max M) Date: Mon, 11 Mar 2002 13:10:24 +0000 Subject: Newbie Import two coloums of floating point data into python HOWTO References: <7eb201fc.0203110422.1e9c7dec@posting.google.com> Message-ID: <3C8CACC0.8080102@mxm.dk> Andybee wrote: > Can some one tell me how to import two coloumns of data in a ascii > text file,into two arrays in python? I cant seem to work it out. The > data is genereated in matlab and I want to import it into python What is the data format? Presumably it is a text file, but how is the data seperated etc. We need to know more. regards Max M From jimd at vega.starshine.org Wed Mar 27 21:56:36 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 28 Mar 2002 02:56:36 GMT Subject: seek in a file References: Message-ID: In article , Andreas Penzel wrote: >"Steven Majewski" wrote: >> Are the files too big to fit in memory ? >the file is about 1 MB, i have to test out working By today's standards 1Mb is tiny. It should easily fit in memory on any reasonably recent (last decade or so) computer. >> What do you want to do with the lines ? >> ( I hope you weren't planning on trying to modify a line in a file: >> because of the variable length on lines, if you don't write >> exactly the same number of chars back, you will either overwite >> the next line, or leave an extra partial line after your edited >> line. Most text editors read the whole file into memory and then >> write out a new file after it's modified in memory. ) >In the file are barcodes of products, one per line. >The program has to look if the scanned code from the barcode-scanner is >identically with one in the file included. This is important because the >barcode-scanner sometimes works not correct. All i need is an search-routine >that compares the scanned code with the codes in the file. If there is an >code, the programs waits for the next code. So I'd load the file into a dictionary: f=open('.../barcodes.list','r') barcodes = {} for x in f.readlines(): barcodes[x]=None And then my validation would look like: while 1: code=BCodeReader.readline() while code not in barcodes: tryAgain() # use valid code in transactions # until operator signals to quit # or forever as you like. Of course I'm assuming you have some sort of object "BCodeReader" that acts enough like a file that you could support a readline() method on it. In some cases it could actually be a regular file object, created with the Python open() built-in, but I don't know about your hardware. I'm also assuming you'd write a "tryAgain" function. Of course I recognize that this might be a multi-user system (possibly with lots of POS terminals attached, and the bar code scanners attached to those). In that case consuming a meg or two of memory for the barcodes dictionary *for each process* might get expensive. In that case you could create a client/server pair. The server could simply return "true" or "1" any time it receives a valid code and "false" or "0" every time it gets an invalid one. It could be written in about a dozen lines of Python and it could probably handle a few hundred concurrent connections (over UNIX or Internet domain sockets). The client size could be written as a small class to include in your application probably also less than a dozen lines of code. From jeff at ccvcorp.com Mon Mar 25 15:46:20 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 25 Mar 2002 12:46:20 -0800 Subject: Launching Tkinter or wxWindows frames from interpreter References: <3C9E638B.1260E9DC@yahoo.com> Message-ID: <3C9F8C9C.8838A871@ccvcorp.com> bptonner at yahoo.com wrote: > I want to launch frames to plot graphs from the Idle interpreter prompt. In general, this will not work under IDLE or PythonWin. The problem is that having multiple message loops within a single process doesn't work. The solution is to run your code in a different process. You can do this by either (1) running the script from a shell prompt, and switching back and forth between that and your IDE, or (2) switching to an IDE that runs code out-of-process. I *believe* that IDLE-Fork (on sourceforge) will do this, and most (if not all) of the commercial Python IDEs do as well. Jeff Shannon Technician/Programmer Credit International From grante at visi.com Sun Mar 10 20:19:43 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Mar 2002 01:19:43 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> <1a9n8us1629mrvei40hdkuuerc1j6p318m@4ax.com> Message-ID: In article , Geoff Gerrietts wrote: > Quoting Grant Edwards (grante at visi.com): >> In article <1a9n8us1629mrvei40hdkuuerc1j6p318m at 4ax.com>, Courageous wrote: > >> I would think that for an isolated app, .so's would slow down >> load times. With a statically linked program all you do is a >> single memmap() call (well, ignoring a few details). With >> .so's you've actually got to resolve all of the symbols and do >> the linking step (not required for statically linked images). >> >> Since you've got the same number of bytes to swap in off disk, >> that should be a wash. > > I can't speak for the windows world, but in the Linux world, .so's end > up saving some time because the dynamic linker doesn't actually move > things into the program's address space until needed -- it does this > on a page-by-page basis. That is true for all text pages. It doesn't matter how they are linked. > Consequently, less start-time latency at a slight cost when > you use the feature. I don't see why. > My data comes from: http://www.suse.de/~bastian/Export/linking.txt I just read it, and it does say that .so's are demand-loaded. But, static images are also demanded-loaded. It does show that lazy binding alleviates the start-up penalty I had described. -- Grant Edwards grante Yow! This is my WILLIAM at BENDIX memorial CORNER visi.com where I worship William Bendix like a GOD!! From db3l at fitlinxx.com Tue Mar 26 23:23:04 2002 From: db3l at fitlinxx.com (David Bolen) Date: 26 Mar 2002 23:23:04 -0500 Subject: win32process.CreateProcess inherit handles not working ? References: <9364c0c7.0203201912.1ba8fde6@posting.google.com> Message-ID: teyc at cognoware.com (Chui Tey) writes: > I've been trying to get this going for a while and I'd appreciate it > if someone can point out what's wrong with the following test? It works > fine on Win98 but fails on NT and W2K. I am using Python 2.1 I don't know that this is the most elegant solution, but I've used DuplicateHandle rather than security attributes to create inheritable handles in the past successfully. It was a while ago, but I seem to recall getting into trouble with SAs because they also include the DACL which defaults to no access unless you explicitly assign it a NULL DACL, and it's just sort of a pain in the neck in terms of extra steps just to inherit the darn handle properly. I don't know that it's what is happening here, but perhaps Win98 is ignoring the security information whereas NT/W2K aren't. I tried modifying your code to use DuplicateHandle and it seems to work fine on my NT4 SP5 system. I'm sure there's a way to make it work with a security attribute as well (and avoid the extra file handle), but this isn't all that bad. So something like: - - - - - - - - - - - - - - - - - - - - - - - - - def _CreateProcess(app, args, filein, fileout): """Returns the pid. app = executable name args = list of arguments filein = name of file to redirect to stdin fileout = name of file to redirect the stdout to """ import win32process import win32file import pywintypes import win32event import win32api import win32con u_filein = pywintypes.Unicode(filein) u_fileout = pywintypes.Unicode(fileout) SI = win32process.GetStartupInfo() SI.dwFlags = win32process.STARTF_USESTDHANDLES hInput = win32file.CreateFile( u_filein, # filename win32file.GENERIC_READ, # mode win32file.FILE_SHARE_READ, # share None, # security attributes win32file.OPEN_EXISTING, # creation disposition win32file.FILE_ATTRIBUTE_NORMAL, # flags 0 # hTemplate file ) hOutput = win32file.CreateFile( u_fileout, # filename win32file.GENERIC_WRITE, # mode win32file.FILE_SHARE_WRITE, # share None, # security attributes win32file.CREATE_ALWAYS, # creation disposition win32file.FILE_ATTRIBUTE_NORMAL, # flags 0 # hTemplate file ) hStdInput = win32api.DuplicateHandle(win32api.GetCurrentProcess(), hInput, win32api.GetCurrentProcess(), 0,1, win32con.DUPLICATE_SAME_ACCESS) hStdOutput = win32api.DuplicateHandle(win32api.GetCurrentProcess(), hOutput, win32api.GetCurrentProcess(), 0,1, win32con.DUPLICATE_SAME_ACCESS) SI.hStdInput = hStdInput SI.hStdOutput = hStdOutput SI.hStdError = hStdOutput cmdline = app + " " + " ".join(args) hProcess, hThread, pid, threadid = \ win32process.CreateProcess( app, # lpApplicationName cmdline, # command line None, # Process security attributes None, # Thread security attributes 1, # Inherit handles win32process.DETACHED_PROCESS, # None, None, SI) win32event.WaitForSingleObject(hProcess, win32event.INFINITE) win32file.CloseHandle(hInput) win32file.CloseHandle(hOutput) win32file.CloseHandle(hStdInput) win32file.CloseHandle(hStdOutput) return pid - - - - - - - - - - - - - - - - - - - - - - - - - -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From plopp at dummyaddress.doh Sun Mar 31 14:44:35 2002 From: plopp at dummyaddress.doh (Mikke M.) Date: Sun, 31 Mar 2002 21:44:35 +0200 Subject: Possible to save router logs? References: Message-ID: "Paul" wrote in message news:bbde2416.0203310724.4150665d at posting.google.com... > I have a D-Link 704 cable/DSL router. Unfortunately, it has very > limited logging capabilities(in that it doesn't save logs, it just > rights over them when the space fills.) What I would like to do is > right a program to save the logs to my hard drive every 12 hours or > so. I normally have to access the web page with the url being the > local IP of the router, then type in a password to get access to the > logs. Has anyone attempted something like this? I know this is kinda > general, but any feedback would be appreciated. It might give me an > idea of where to begin. Thank you. Sure.. First of all you have to log on to the router. My DL-704 shows this html code: ---(SNIP!)---
    System Password 
    ---(SNIP!)--- The tricky part for me was getting the encoded password to submit to the router, so I rewrote the FORM ACTION command to read:
    Then I saved the html to a file and opened it, and logged on to the router using that file and copied the entire address line from internet explorer and pasted it into my python script: ---(snip!)--- import urllib2 MR=urllib2.Request("http://my.router.ip/cgi-bin/logi?RC=@D&ACCT=root&PSWD=TH E ENCODED PASSWORD GOES HERE..&URL=admin&KEY=3A2D.36D6.3A43%2F3100%2BADB0 at Winnie+193s&htm=2.56+build +20") URL=urllib2.urlopen(MR) ---(snip!)--- Now you are logged on to your router and it will gladly show any of its internal webpages you request from it witin a couple of minutes.. Then go on to get the system log page: ---(snip!)--- MR=urllib2.Request("http://my.router.ip/syslog.htm") URL=urllib2.urlopen(MR) LOGPAGE= URL.read() ---(snip!)--- Now you should have the entire system log webpage in LOGPAGE, the rest of the work is up to you. :-) /Mikke From robin at jessikat.fsnet.co.uk Fri Mar 1 09:54:22 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 14:54:22 +0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7F6765.94A82394@engcorp.com> Message-ID: In article , Robin Becker writes >In article , Thomas Heller > writes >..... >>> Is there a proper way to get the 8.3 name? >> >>>>> import win32api >>>>> win32api.FindFiles(r"c:\Program Files") >>[(49, , , >>, 0, 0, 100, 1244528, ' >>Program Files', 'PROGRA~1')] >>>>> win32api.FindFiles(r"c:\Program Files")[0][-1] >>'PROGRA~1' >> >>Thomas >> >> >thanks, but it would still be better to get the popen methods to work >properly wouldn't it? after investigation it seems that module nt is using cmd.exe /c string to run programs and I can't find any way to quote things in the string. A typically rubbish M$-ism. -- Robin Becker From tim.one at comcast.net Sun Mar 10 23:16:02 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 10 Mar 2002 23:16:02 -0500 Subject: Help newbie w/Numpy Install ?? In-Reply-To: <3C8C1C4F.7770642A@mcn.net> Message-ID: [jrc] > I'm brand new to Python - tho experienced somewhat > with programming, compiling, etc. I just downloaded > Python v2.2 but have yet to install. Install it, and work your way through the included tutorial. You're in for a treat! > I'm going to run it on Windows ME. (I have MSVC 6.0 but not > installed, hopefully don't need all that.) Probably not. > I can't seem to understand, on sourceforge / numpy > pages, the following two issues: > > a) Exactly which files do I need to download to make > NumPy work with Python 2.2 - or is that even possible? This can't be answered until you can ask a better question . To get started, download only Numeric-20.3.win32-py2.2.exe. That's assuming you want to use version 20.3 of NumPy (I can't answer that for you), and don't want any NumPy addons at the start (ditto). > b) Will I need my c-compiler to get NumPy to work? Nope. Note that you'll usually get better help with NumPy on its mailing list: http://sourceforge.net/mail/?group_id=1369 From max at alcyone.com Wed Mar 27 02:30:49 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 26 Mar 2002 23:30:49 -0800 Subject: Python vs. C/C++/Java: quantitative data ? References: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> <3CA10CA8.DFF48898@gmx.de> <7x663iam5u.fsf@ruckus.brouhaha.com> Message-ID: <3CA17529.4B8502@alcyone.com> "G. Sumner Hayes" wrote: > Agreed. As long as we're stating personal opinions, C is harder than > Python but easier than Java or C++, both in learning the language and > writing large, maintainable projects. You're saying that Java is harder than C? Why? Are you taking all the _concepts_ that have to be mastered in order to use both competently and judging that object orientation is more complicated in whole than a more complicated syntax, pointers, etc.? -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From mickey at tm.informatik.uni-frankfurt.de Sat Mar 2 20:30:12 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 3 Mar 2002 03:30:12 +0200 Subject: PEP 234 little bug? References: <3c817238@nntp.server.uni-frankfurt.de> <3C817FC1.A155DBAB@earthlink.net> Message-ID: <3c818ab3@nntp.server.uni-frankfurt.de> Hans Nowak wrote: [...] > Hm, I don't think so. I think it does not say that the *file* > object should have a next() method... rather, it says that > it's its own iterator, and the iterator has the next() > method. Maybe the wording could have been a bit more careful, > but essentially it's true what is says. And iterating over > files has indeed been implemented in 2.2. Yes, I was aware of that - I just thought the line "is implemented" would mean the inclusion of the (proposed) fileobject.next() method [which as a matter of fact is _not_ implemented], not the iterator itself. Thanks for your response. Later, Mickey. From cfelling at iae.nl Wed Mar 13 17:39:06 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 13 Mar 2002 23:39:06 +0100 Subject: trouble testing for existance of variable References: <4bbaa6d6.0203121352.4358f14@posting.google.com> Message-ID: googlePoster wrote: ... > try: > curr_color = vim.eval("colors_name") > except NameError: Ah code, now we know:) It's ofcourse not Python's fault, but incorrect vim usage:) So I looked it up (don't use vim myself, but instructed my daughters to:) and vim has this nifty function to check for the existance of a varibale. :echo eval("colors_name") :python print eval("colors_name") returns 0 or 1 depending on the existence of "colors_name", so why not: curr_color = ( vim.eval( 'exists("colors_name")' ) and vim.eval('colors_name') or None ) -- groetjes, carel From jeff at ccvcorp.com Wed Mar 27 18:14:16 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 27 Mar 2002 15:14:16 -0800 Subject: problems with circular references References: Message-ID: <3CA25247.D51E75BF@ccvcorp.com> Terry Reedy wrote: > "jimh" wrote in message > news:a7tbd4$qc7$1 at web1.cup.hp.com... > > I am working on python code that consist of quite a few files (about > 50; > > each file contains one class). All errors returned by functions are > numeric > > and are defined in the individual files. There is a > MessageCatalog.py class > > which will map these numbers into strings. > > I would probably follow the standard Python idiom of using exceptions > instead of numeric error codes, and look at standard library modules > for precedents. I very much agree with Terry. If you define a series of exceptions in a separate file, then there's no need for mapping error numbers to strings -- the strings are part of the exception. This will simplify your code in many ways, not the least of which is not having to worry about checking for a numeric error code at *every* level. Exceptions are *so* much cleaner, and make it much easier to deal with an error at the most appropriate level (instead of manually propagating an error condition through multiple levels of call stack). ----- MyErr.py --------- class FooError(Exception): pass --------------------------- ------ MyFoo.py --------- import MyErr ... try: MyObject.Foo(): except MyErr.FooError: CancelFoo() ---------------------------- Jeff Shannon Technician/Programmer Credit International From mcherm at destiny.com Thu Mar 14 11:26:02 2002 From: mcherm at destiny.com (Michael Chermside) Date: Thu, 14 Mar 2002 11:26:02 -0500 Subject: [].keys() and [].items() (Was: Why I think range is a wart) Message-ID: <3C90CF1A.5010307@destiny.com> Courageous writes: > >Question: Which is better: items(x) or x.items()? > > Note the question in the PEP, but leave the decision to Guido. > > C// I disagree. It'e easier for Guido (and everyone else who reads PEPs) if the PEPs make a clear and specific proposal instead of listing a whole smorgasbord of options. Now if it's a trivial issue, like naming it "items" or "indexed", then that's fine. But using items(x) vs x.items() is not trivial: there are lots of arguments for or against one that don't apply to the other (eg: the need to implement the items() method when creating a list-like class). So to make the PEP process work, the PEP author should try to make these decisions, based on input from the community during discussion and on the author's own designer intuition. Alternatives that were rejected should be noted, but the PEP itself should make a very specific proposal. Then the BDFL applies his OWN designer's intuition, combined with input from the community. -- Michael Chermside From news.Andreas at gmx.net Sat Mar 23 05:32:13 2002 From: news.Andreas at gmx.net (Andreas) Date: 23 Mar 2002 02:32:13 -0800 Subject: load html frameset out of Python script References: <30cf5082.0203221039.791cab07@posting.google.com> Message-ID: <30cf5082.0203230232.7a887cf@posting.google.com> news.Andreas at gmx.net (Andreas) wrote in message news:<30cf5082.0203221039.791cab07 at posting.google.com>... > Hello everybody, > > I am trying to set up a html site with frames. I want to load the > frameset out of a Python script. > Frameset definition: > > "http://www.w3.org/TR/html4/frameset.dtd"> > > > right frame > > > noresize marginheight="0" marginwidth="0"> > noresize marginheight="0" marginwidth="0"> > noresize marginheight="0" marginwidth="0"> > marginheight="0" marginwidth="0"> > > > No frame support of your browser! > > > > > > I load this with the following code: > > File = "%s" % ('frameset.html') > PageHandle = open(File, "r") > PageInput = PageHandle.read() > PageHandle.close() > Display(PageInput) > > ...the html file will be found but I can see just an empty page. > > What can I do to realize this problem? > Is it possible to write in a specific frame from my scripts? Sorry for this annoying posting! This problem drives me crazy for hours. However, I found the problem behind the code of my Display() function after a long break and a big coffee. But I still don't know how to put html code into a specific frame out of my Python scripts. Any suggestions? Regards, Andreas From cruciatuz at cruciatuz.de Mon Mar 4 19:53:58 2002 From: cruciatuz at cruciatuz.de (cruciatuz) Date: Mon, 4 Mar 2002 19:53:58 -0500 Subject: text manipulation examples In-Reply-To: <61ff32e3.0203040951.2408cef4@posting.google.com> References: <61ff32e3.0203040951.2408cef4@posting.google.com> Message-ID: <20020305005358.GB2143@blackscarab> On Mon, Mar 04, 2002 at 09:51:39AM -0800, ron nixon wrote: > ... examples of string manipulation of text files, which are often > lacking in the books I've gotten so far(if I'm wrong, please point me > to the book.) Can anyone point me to examples or have examples I could > take a look at. perhaps: http://py-howto.sourceforge.net/regex/regex.html can help you -- Stefan Antoni ---------------------------- Mon M?r 4 19:52:23 EST 2002 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 240 bytes Desc: not available URL: From martin at v.loewis.de Wed Mar 27 18:30:48 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 28 Mar 2002 00:30:48 +0100 Subject: unicode experiments + questions References: Message-ID: "Irmen de Jong" writes: > Adding the well-known iso-8859-1 (iso-latin-1) to the list > results in an exception: Latin-1 encoding error: ordinal not in range(256) > as expected, because I found out that the Euro symbol is not > in latin-1 but *is* in latin-9 (iso-8859-15). Indeed, this was one of the driving forces for the introduction of latin-9. IMO, Latin-9 is a bad choice as a data format - you have to give up other characters in return, and all the advantages of Latin-1 (it being the default encoding in many places) are lost. So you may as well use UTF-8 instead, and gain access to all characters supported in Unicode. Regards, Martin From bergeston at yahoo.fr Fri Mar 22 10:29:50 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Fri, 22 Mar 2002 16:29:50 +0100 Subject: CGI, etc. References: Message-ID: "Gerhard H?ring" wrote in message news:slrna9m09g.1ic.gerhard at koesesoy.opus-gmbh.net... > In article , dsavitsk wrote: > > "Sheila King" wrote in message > >> http://www.python.org/topics/web/ > > > > btw, the instructions linked to here for doing CGI on windows under iis are > > out of date (only covering 9*/NT). For win2k (server and professional) see > > http://www.e-coli.net/mag.shtml (or http://www.e-coli.net/pyiis.html and > > http://www.e-coli.net/pyiis_server.html specifically) > > I'd suggest to inform webmaster at python.org. > > Gerhard I second this suggestion because, as a newbie not involved in the Python community (btw really really cool), my first thought after the mail of "dsavitsk" was "Ah, Ah this Python site is not really up to date" Have a nice WE. From gerhard at bigfoot.de Wed Mar 20 00:54:05 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 20 Mar 2002 05:54:05 GMT Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: Aahz wrote in comp.lang.python: > [...] Unless you're on a shoestring, consider getting a commercial > database; you should probably also check to see whether MySQL or > PostgreSQL will give you better performance. Just to avoid misunderstandings: of course you can get commercial support for open-source RDBMs. At least for the major ones: PostgreSQL: PostgreSQL Inc., Redhat MySQL: MySQL AB, Nusphere SAPdb: SAP Firebird: IBphoenix I also think that an RDBMs is the way to go for the OP's problem. If at some point too many requests run against the database, you can optimize performance by putting logic into the database (stored procedures). If you're brave, you can even use Python as a language for stored procedures running in PostgreSQL :) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From bkc at Murkworks.com Wed Mar 6 11:52:34 2002 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 6 Mar 2002 11:52:34 -0500 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> Message-ID: <3c864a78$1_3@news.newsgroups.com> "Curtis Jensen" wrote in message news:3C850173.4050004 at bioeng.ucsd.edu... > The only disappointing parts for me were: > No chapters on extending Python with C. You can find a respectable (IMHO) chapter on extending and embedding in "Professional Linux Programming", Wrox Press. Strange place to bury it, but if you're in a bookstore some time check it out. I'd like to know your opinion. (I wrote it) -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! Check out our new Unlimited Server. No Download or Time Limits! -----== Over 80,000 Newsgroups - 19 Different Servers! ==----- From bergeston at yahoo.fr Mon Mar 18 05:25:50 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Mon, 18 Mar 2002 11:25:50 +0100 Subject: Why I think range is a wart. References: Message-ID: OK, I will try to take your point of view: Following you, lists are a special kind of dictionnary where: - keys are regular sequence of integers, - keys are automatically managed : - automatically created when an element is put in the list, - modified for each element being over a removed or an inserted element. I have to admit that I have some difficulties to think like that. I see a list as being intrinsically different of a dictionnary because in a dictionnary, the key (even if it is an integer) is something related to the item. In a list, the index is the place of the item in the list. If you take the item out of the list, the index doen't make sense at all anymore. And if you need a dictionnary with integers keys, just build it: makeDictFromList = lambda list: dict(zip(range(len(list)), list)) I admit that this doen't apply that much to tuples that can be more easily seen as a special kind of dictionnaries if you really want it. B. PS Thanks to understand my bad english and to add some mathematical formalism that I miss. I really appreciate. "Magnus Lie Hetland" wrote in message news:slrna954bc.h7j.mlh at vier.idi.ntnu.no... > In article , Bertrand Geston wrote: > [...] > >Let's keep things simple and understandable : > >- lists are ordered sets, > >- dictionnaries are "keyed" sets. > > The standard mathematical definition of sequences (as opposed to > ordered sets) is a partial function mapping integers to elements. This > seems awfully close to what you're calling "keyed" sets, by > restricting the domain to integers. It also seems awfully close to > Python lists (for instance). I see nothing inconsistent or illogical > about list.keys. list.indices is an alternative, of course, but would > not allow for polymorphic use. > > -- > Magnus Lie Hetland The Anygui Project > http://hetland.org http://anygui.org From ron.l.johnson at cox.net Sun Mar 3 22:52:58 2002 From: ron.l.johnson at cox.net (Ron Johnson) Date: Mon, 04 Mar 2002 03:52:58 GMT Subject: Text Search Engine that works with Python References: Message-ID: On 04 Mar 2002, 00:27:23, William Park wrote: > Doug Farrell wrote: > > Hi all, > > > > I'm wondering if anyone knows of a text search engine that works with > > Python? What I'm looking for specifically is something that will > > compress the text and still allow searches and retrievals that can be > > exact matches or proximity based. The text I want to compress and > > search is huge (70 megs) and should compress down to half, not > > including any index files that might be required by the search engine. > > Anyone know of anything like this or any ideas? > > > > Thanks, Doug Farrell > > Perhaps, you can illustrate your problem with some concrete examples. > Otherwise, you'll be getting "use Linux" or "use gzip/bzip2" answers > which wouldn't be too useful for you (judging by the fact that you had > to ask in the first place). > Maybe he's talking about "zgrep". http://www.delorie.com/gnu/docs/gzip/zgrep.1.html However, the effort involved in decompressing the file might out- weigh the benefits from saving 35MB disk space. Unless you have an _old_ disk, it may be best to leave the text uncompressed. -- +------------------------------------------------------------+ | Ron Johnson, Jr. Home: ron.l.johnson at cox.net | | Jefferson, LA USA http://ronandheather.dhs.org:81 | | | | 484,246 sq mi are needed for 6 billion people to live, 4 ! ! persons per lot, in lots that are 60'x150'. | ! That is ~ California, Texas and Missouri. ! ! Alternatively, France, Spain and The United Kingdom. | +------------------------------------------------------------+ From anton at vredegoor.doge.nl Tue Mar 26 06:29:43 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 26 Mar 2002 12:29:43 +0100 Subject: list element of a class with the for statement References: Message-ID: On Tue, 26 Mar 2002 08:34:41 -0000, "cedric_briner" wrote: >class CRdb: > __fieldsName= [] > __keyname= [] > __records = ['first','secnd','third'] > __iRecord= 0 > >because I would like to write something like: > >db=CRdb() >for entry in db: > print entry This question should be answered by RTFM! But anyway, just to give a starting point: class CRdb: def __init__(self): self.__fieldsName= [] self.__keyname= [] self.__records = ['first','secnd','third'] self.__iRecord= 0 def __getitem__(self,i): return self.__records[i] def test(): db=CRdb() for entry in db: print entry if __name__=='__main__': test() From James_Althoff at i2.com Mon Mar 4 19:44:02 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 16:44:02 -0800 Subject: Status of PEP's? Message-ID: [Jeff Hinrichs] > Ok, so after 3 days of exposing myself as an object luddite, > I think I understand what is being asked for and why the proponents > are so strongly in favor of it. I have officially upgraded my > position to neutral on the matter. (at this rate, I might be in the > pro camp by Thursday ) I would like to thank everyone one (carel > and james) for taking the time to enlighten me (even if sometimes it > requires a 2x4') Not a problem! Converts, in fact, get special treatment . Seriously though, if nothing else, perhaps these PEP 276 discussions have helped to highlight Python's wonderful "everything is a first-class object" philosophy! Jim From jamie.carl at salientnetworks.com.au Thu Mar 21 19:39:05 2002 From: jamie.carl at salientnetworks.com.au (Jamie Carl) Date: Fri, 22 Mar 2002 00:39:05 GMT Subject: Execute external program Message-ID: <3c9a7d0e_1@news.iprimus.com.au> Hopefully this is a simple question. How can I get python to execute an external program such as 'bash' or whatever? Is there a line of code that will do this. No interface with STDIO needed so i can run blind. TIA Jamie Carl From gh_pythonlist at gmx.de Tue Mar 19 17:32:34 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 19 Mar 2002 23:32:34 +0100 Subject: Newbie: EOF Error when making arrays .fromfile In-Reply-To: <33e33d88.0203191243.454d39b8@posting.google.com> References: <33e33d88.0203191243.454d39b8@posting.google.com> Message-ID: <20020319223234.GA3851@lilith.hqd-internal> Le 19/03/02 ? 12:43, Matt Strange ?crivit: > hello all, i am very new to python and i'm using v2.2 on a Win98SE > machine. i needed to read in double-type data from an ASCII file > (http://dnijaguar.tripod.com/planet0.dat). this file contains 3000 > doubles separated by the tab("\t") value. after reading information > posted on this newsgroup, i decided that it would be best to first > translate this ASCII data into a binary file using a c++ program > (http://dnijaguar.tripod.com/atb.cpp). then, i could read in this > binary file (http://dnijaguar.tripod.com/bin0.dat) with the following > lines of python: > > >>> coord = array('d') > >>> coord.fromfile(open("bin0.dat",'r'),3000) Hmm. Works for me with your C++ and Python code. Perhaps (unlikely, though) Python and your C++ compiler use different sizes for float. Btw. these are 3003 values, if I see correctly. If you don't need raw arrays and can use a list instead, this very simple code does should do what you need: d = map(float, open("planet0.dat").read().split()) Btw. Python doesn't have the distinction between 'float' and 'double'. A Python float type is using a C double internally. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.7 ?C Wind: 2.3 m/s From -$P-W$- at verence.demon.co.uk Tue Mar 19 05:58:52 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 19 Mar 2002 10:58:52 -0000 Subject: Gadfly mirrors? References: Message-ID: In article , Harald Schneider wrote: >Thanks for this valuable hint! >For all others outside, the exact link is: >ftp://ftp.debian.org/debian-archive/dists/slink/main/binary-i386/interpreter >s/ > >One prob left: How do you unpack a *.deb file ? Debian packages are ar(1) archives. Unpacking that gets you some tar.gz files with the stuff you want inside them. Have a look at http://ibiblio.org/gferg/ldp/giles/repository/repository-2.html under "Binary packages" -- Paul Wright | http://pobox.com/~pw201 | From bernie at 3captus.com Wed Mar 13 19:23:33 2002 From: bernie at 3captus.com (Bernard Yue) Date: Thu, 14 Mar 2002 00:23:33 GMT Subject: possible string.strip memory leakage References: Message-ID: <3C8FEDFB.666F1187@3captus.com> Mike Brenner wrote: > There might be a memory leak in string.strip. > > I wrote a python function to strip blanks off the left and right of a string. When I discovered string.strip, I replaced the call to my version with string.split, and I got a large memory leakage. When I put the call back to calling my python function, the memory leakage went away. Did happen to me. So we need your Python version and OS you are running. Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From philh at comuno.freeserve.co.uk Sat Mar 30 16:19:56 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 21:19:56 +0000 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: On 30 Mar 2002 11:04:13 -0500, Andrew Koenig wrote: > >I wonder if this is the circle-ellipse problem over again? What is the circle-ellipse problem? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From narnett at mccmedia.com Wed Mar 20 12:36:21 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Wed, 20 Mar 2002 09:36:21 -0800 Subject: Word frequencies -- Python or Perl for performance? In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Bengt Richter [snip] > Others seem to have inferred what you are up to, but I'll have to > stick with > my original post until you say what you really are trying to do. All is not yet clear to me yet...! But this is related to identifying relatively distinct ideas in on-line discussions. I'm generating feature vectors to spot when a conversation forks, so to speak. The message meta-data and bodies are stored in MySQL, so it would be somewhat of a natural for me to stick word frequency data in a table. I just realized that the version of MySQL I'm using has full-text indexing (I had thought it wasn't showing up until 4.0, which is not ready for production use yet). However, there are some default behaviors in MySQL's full-text search that I don't like... and I'm not inclined at the moment to compile my own MySQL binary to change them, especially since I still won't get proximity and other capabilities. I suppose I should have asked about full-text search packages that will accomplish the same things, but I know too darn much about them and I want to get at the inverted indexes themselves. There's some unusual search weighting that I want to be able to do eventually. If there's an open source search engine that would let me add an externally calculated weighting factor, that would be terrific. > It's not even > clear that you're interested in anything but global word > frequencies over your > entire set of files, except for the clue that you think you may > need to store > something in a database ;-) I'm also interested in how the word frequencies change over time. As an example of why this is interesting, I took a look at them in Usenet postings after the Columbine shootings a few years ago. Spotting the features whose frequencies change fastest gives an idea of where the discussion is going. For example, "video games" showed up at high frequency initially, but dropped rapidly, while "parents" rose. Once you know the features that are changing rapidly, you can go grab the sentences that contain the greatest number of them, which yields a decent summary of the ideas that are moving, so to speak, in a discussion. The really, really (unreachably!) big picture here is that, as Tim O'Reilly and I like to say, I'm trying to figure out what the Internet is thinking today. I did a lot of my initial brainstorming on this stuff with the O'Reilly folks, who use this sort of analysis to get a handle on which open source software is gaining momentum and thus might deserve a book. Nick From shalehperry at attbi.com Sat Mar 16 16:12:43 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 16 Mar 2002 13:12:43 -0800 (PST) Subject: Begginers Guide - Exrcise. Help me, plz! In-Reply-To: Message-ID: On 16-Mar-2002 Jeffrey-man wrote: > Hello, everybody! > I'm a newbie and I'm just learning. I know, it's a stupid question, but I > want to resolve it. > Learning the Begginers Guide, I found an exercise. It tells me: > "Write a program that continually reads in numbers from the user and adds > them together until the sum reaches 100." > Can anybody help me? > > ----- > > sum_stop = 100 > num = input("Please enter the number: ") > > for sum in range(num+num,sum_stop): > print "Now the sum is", num+num > sleep(1) > > print "The sum is >/= 100!" > > ----- > > Maybe I'm doing something wrong? > > you misread the specification. You are to ask the user "give me a number", add that number to the previous one (hint: use zero the first time), then check if the new sum is less than the stopping point (100 in this case). If the stopping point is reached, cease asking for a number. Does that help? From marxdormoy at aol.com Wed Mar 27 10:43:52 2002 From: marxdormoy at aol.com (Marxdormoy) Date: 27 Mar 2002 15:43:52 GMT Subject: visual python Message-ID: <20020327104352.12035.00000368@mb-mk.aol.com> downlaod visual python ? website? From jgardn at alumni.washington.edu Sat Mar 16 01:30:41 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Sat, 16 Mar 2002 15:30:41 +0900 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> <3C91F553.D9E511CB@engcorp.com> Message-ID: <4sBk8.301$ID.1977@news.hananet.net> Peter Hansen wrote: > Gerhard H?ring wrote: >> Peter Hansen wrote in comp.lang.python: >> > Jonathan Gardner wrote: >> >> I am at a major disadvantage because I don't have access to a windows >> >> machine, and so I can't test anything directly. However, I do have a >> >> few people who actively test for the project at home. >> >> >> >> NSIS rocks. But AFAIR his problem is that he doesn't have a Windows >> box to build the installer on. > > D'oh! You're right, my brain wouldn't absorb that concept. Someone > writing a Windows installer in Python because he doesn't have a > Windows box to run the real Windows installers on. It boggles the > mind: how does he plan to test?! > =) Very carefully. I have a couple of guys who are willing to do the testing. Jonathan From niemeyer at conectiva.com Sun Mar 24 14:52:46 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sun, 24 Mar 2002 16:52:46 -0300 Subject: Embedding help In-Reply-To: <3C9DFC8B.5070700@Lindbergs.org> References: <3C9DFC8B.5070700@Lindbergs.org> Message-ID: <20020324165246.B20294@ibook.distro.conectiva> > (called once) setup(int type) > This would initialize python and a python class with the passed-in value > (Used internally by the python class). > This python class would also import other modules (both builtin and > custom; the custom ones would be pure python) [...] > My problem is the following: > How do I keep the class instance around so that I can maintain state? > The getPt function would return variables that in part are functions of > previous inputs, not just the current input. I'm not sure I could follow you here. State is maintained internaly by the python interpreter. Just don't reinitialize the interpreter between calls to your functions. If you want to save your instaces for further usage, just save them in static variables or lists, as you'd usually do. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From bokr at oz.net Fri Mar 29 20:58:59 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Mar 2002 01:58:59 GMT Subject: number of lines in a file References: Message-ID: On 29 Mar 2002 13:22:28 -0800, sjmachin at lexicon.net (John Machin) wrote: >"Joseph Youssef" wrote in message news:... >> hello, I am nwe to Python and I'm trying to write this script but I need >> it to check how many lines is in the file and I don't know how so I'm >> hoping someone could tell me. >> > >Welcome to Python. > >Others have suggested approaches which attempt to read the whole file >into memory, but may succeed very slowly or not at all in the event >that you have files that are larger than your machine's physical >memory; here's a slightly more robust approach: > >num_lines = 0 >f = file('path_and_file_name') >for line in f: > num_lines += 1 >f.close() > You can do a one-liner without reading the whole file at once ;-) reduce(lambda x,y: x+1, file('/path/and/filename').xreadlines(), 0) Regards, Bengt Richter From dgallion1 at yahoo.com Sun Mar 3 12:02:23 2002 From: dgallion1 at yahoo.com (Darrell) Date: Sun, 03 Mar 2002 17:02:23 GMT Subject: regular expression for nested matching braces References: Message-ID: Tim Peters Explains it here. http://groups.google.com/groups?th=ed6a75bc5eed7ee9&seekm=000401be9e6d%2427a98ec0%24029e2299 Searched on "tim peters match" It's result 203 --Darrell Paul M wrote: > Is it possible to create a regular expression for searching for the > outermost matching braces in a string in which there may be nested braces? > From fgeiger at datec.at Sat Mar 30 05:05:49 2002 From: fgeiger at datec.at (F. GEIGER) Date: Sat, 30 Mar 2002 11:05:49 +0100 Subject: GUI programming References: Message-ID: Have a close look at anygui at sourceforge. anygui enables your code being independent of any backend gui package on the target. If it does not yet fit your needs *yet* (still in early stage, but moving very fast!), look at wxPython. I know of 2 good builders here: wxDesigner (www.roebling.de, commercial but affordable) and Boa at sourceforge. Cheers Franz "Umesh Persad" schrieb im Newsbeitrag news:mailman.1017437568.25402.python-list at python.org... > Hi, > I am doing an assignment using python - > making a turkish checkers game. > > --------------------------------------- > | | > | | > | | > | checker board area | > --------------------------------------- > | | > | text fileds and buttons area | > | | > --------------------------------------- > > I wanted to have a user interface where > I can draw the game board as well as take > in text input below the board with some text > felds and buttons. I see there are many GUI toolkits > available. I am wondering which one should I use > (tkinter, wxpython?) that will be simple enough > to get me up and running qiuckly. Also are there > any examples that I can look at? > > Also, if any one is familiar with Tkinter, > how do I put up a window with a size > that I want? Also how do I place a canvas > on the window at a predefined size? > > Thanks a lot, > Umesh > > From tejarex at yahoo.com Wed Mar 6 16:19:42 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Wed, 06 Mar 2002 21:19:42 GMT Subject: Dictionaries in Lists References: Message-ID: "Avi Homes" wrote in message news:ayvh8.55100$6j2.3265866 at typhoon.austin.rr.com... > I was attempting to make a list of dictionaries, which to me feels like the > C equivlant of an array of structs, kind of. anyway, after making a > dictionary and putting some values into it, and trying to append it to a > list, python is not liking this. Am I approaching the idea the wrong way? i > would like to keep the data organized as dictionaries.. the code looked > something like > > Info{'IName':"Voodoo2",'IDescription':"blahblah} I see 2 syntax errors above. Show up *exactly* what you entered. Fire up interactive browser and cut and past result. > Listing=[] > Listing.append(Info) Terry J. Reedy From stojek at part-gmbh.de Thu Mar 7 09:21:02 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Thu, 07 Mar 2002 14:21:02 GMT Subject: wxVTKRenderWindow inside wxSplitterWindow Message-ID: <3c8772cb.20639421@news.easynews.net> HI, I want to use a wxSplitterWindow to render two different body with VTK. Here is what I tried #--------------------------------------------------------------------------- class ViewSplitter(wxSplitterWindow): def __init__(self, parent, ID): wxSplitterWindow.__init__(self, parent, ID) EVT_SPLITTER_SASH_POS_CHANGED(self, self.GetId(), self.OnSashChanged) EVT_SPLITTER_SASH_POS_CHANGING(self, self.GetId(), self.OnSashChanging) def OnSashChanged(self, evt): i=1 # some stuff def OnSashChanging(self, evt): i=1 # more stuff #--------------------------------------------------------------------------- def ShowCmModel(frame,title): f = wxFrame(frame, -1, title, size=(450, 300), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) #Without splitting everything works fine #win = vtk.wxVTKRenderWindow(f, -1) # Now trying to create two different RenderWindows in SplitterWindow splitter = ViewSplitter(f, -1) CMwin = wxWindow(splitter, -1) ABAwin = wxWindow(splitter, -1) splitter.SplitVertically(CMwin, ABAwin) win1 = vtk.wxVTKRenderWindow(CMwin, -1) win2 = vtk.wxVTKRenderWindow(ABAwin, -1) # All the rendering stuff..... #------------------------------------------------------------------------- My problem is the size of the two Render Areas. I cant make them fit the two splitted windows (they are very small) and they are not resized when I change the window size. As I didn't find any doc on wxVTKRenderWindow, I don't know what to do. I tried win1=vtk.wxVTKRenderWindow(CMwin, -1, size=CMwin.GetSizeTuple()) but that didn't work either. Any idea ? Thanks, Marcus From shalehperry at attbi.com Fri Mar 1 12:26:44 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 01 Mar 2002 09:26:44 -0800 (PST) Subject: Javascript to Python In-Reply-To: <2030665d.0203010912.1bb9c0ae@posting.google.com> Message-ID: On 01-Mar-2002 Sam Collett wrote: > Does anyone know of any good sites on Javascript > Python examples? > I have a function in javascript that returns the file extension: > > function FileExtension(sFilePath) > { > return Right(sFilePath,sFilePath.length-sFilePath.lastIndexOf(".")) > } > > so FileExtension("/path/to/file.doc") would return .doc > I would also want to return the filename (file) and the path > (/path/to/). How would I go about that? > import os, os.path >>> filename = '/path/to/foo.doc' >>> os.path.splitext(filename) ('/path/to/foo', '.doc') >>> os.path.splitext(os.path.basename(filename)) ('foo', '.doc') >>> os.path.basename(filename) 'foo.doc' >>> os.path.splitext(filename) ('/path/to/foo', '.doc') >>> os.path.splitext(os.path.basename(filename)) ('foo', '.doc') os.path has a bunch of nice path related tools like abspath() and join(). Check out the python docs. > What equivalents to the functions Right and Left (right side of > string, left side of string) > sorry, not quite sure what the Right side of a string is (-: > Also is there an easier way to do number incrementing (just me being > lazy): > while r<5 > print r > r=r+1 > > I have tried r++ to add 1 each time, and r-- to take away one, but > this does not work, so is the only way r=r+1 or r=r-1 ? > in python 1.5.2 and earlier the only way was r = r + 1. In the 2.x series the += operator was added (I think this works in javascript too, it works in most C like languages) r += 1. There is equivalents for the other standard math ops. From aahzpy at panix.com Tue Mar 12 19:22:08 2002 From: aahzpy at panix.com (Aahz) Date: 12 Mar 2002 19:22:08 -0500 Subject: is time.sleep a thread safe function? References: Message-ID: In article , Zihong Lu wrote: > >Recently, we have seen some weird behaviors in our python application >in Solaris 2.6, 2.7,and 2.8 platform. The application is a web based >server, that uses threads heavily. It runs fine in Linux and win32 >platforms, but in Solaris, it stopped accepting after ran for couple >of hours. One of our guesses is that the time.sleep() used through >out our application is not thread safe. Can any one please help us >eliminate/confirm this factor? Thanks. I'd be extremely surprised if time.sleep() were a factor, because it's implemented using select() on platforms that have it (which probably includes Solaris). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From gh_pythonlist at gmx.de Mon Mar 4 19:53:40 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 5 Mar 2002 01:53:40 +0100 Subject: Python standards In-Reply-To: References: Message-ID: <20020305005340.GA8780@lilith.hqd-internal> Le 05/03/02 ? 00:16, CSJedi ?crivit: > Can someone tell me if Python has proprietary or consensus standards such as > ANSI? No, there's no standard for the Python language. Thinking of it, there are several languages which have become very popular very quickly: Visual Basic, Perl and Java. Should this be a coincidence? Thinking about it, VB and Java are essentially single-vendor languages (Java less so, but still), and the vendors have probably little interest in standardizing the languages. As for Perl and Python, the implementations are open-source and there's only one Perl implementation that I know of and only two usable Python implementations (CPython and Jython). So again, there's little use for a standard here, perhaps mostly because there's no actual product to put the "ISO Python compliant" label onto. In Python-land, the situation is that there's a de-facto standard, namely the CPython implementation, which was the only implementation for a long time. As soon as a new feature is implemented in CPython, the Jython developers follow suit for their system. Its good to know that the CPython folks try to not introduce any language features which are impossible to implement in Jython. That was one argument against including the original "Stackless Python" into the core, for example. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 2.2 ?C Wind: 0.5 m/s From pedronis at bluewin.ch Thu Mar 28 19:06:51 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Fri, 29 Mar 2002 01:06:51 +0100 Subject: Exceptions and modules / namespaces question References: <1136f745.0203281521.76a1a62c@posting.google.com> Message-ID: <3ca3b040$1_3@news.bluewin.ch> The problem is that "import module1" in module2 is re-executing your main script a second time and so creating new definitions. The main script, as the "if __name__ == '__main__' " idiom hints, appear as loaded (in the module cache sys.modules) under such a name, so "import module1" triggers the loading of module1.py as distinct (new) module from the main script. Consider: #mod.py: class C: pass if __name__ == '__main__': import mod import sys print "module __main__: ",sys.modules['__main__'] print "module mod:", mod print "are the same?",{0: 'n',1: 'y'}[sys.modules['__main__'] is mod.C] print "class C in main script:",C print "class C from mod:",mod.C print "are the same?",{0: 'n',1: 'y'}[C is mod.C] Output: $python mod.py module __main__: module mod: are the same? n class C in main script: __main__.C class C from mod: mod.C are the same? n regards. From ocscwar at h-after-ocsc.mit.edu Wed Mar 13 16:45:44 2002 From: ocscwar at h-after-ocsc.mit.edu (Omri Schwarz) Date: 13 Mar 2002 16:45:44 -0500 Subject: Newbie regex question. References: Message-ID: "Sean 'Shaleh' Perry" writes: > On 13-Mar-2002 Omri Schwarz wrote: > > > > I have a regex = re.compile('yadda (widget1) (widget2) yadda') > > and want to search a string I know to have multiple > > instances of this regex. I'm a tad confused by > > the RE Howto, so I'd like to ask, how do I properly > > get a for loop to access the widget1 and widget2 > > strings of each instance? > > > > for instance in regex.search(string).groups() > > seems to be the right thing, but isn't working. > > > > >>> import re > >>> s= 'yadda widget1 widget2 yadda' > >>> regex = re.compile('yadda (widget1) (widget2) yadda') > >>> for match in regex.search(s).groups(): print match > ... > widget1 > widget2 > > This works here. Although I would strongly caution you to do: > > re_match = regex.search(s) > if re_match != None ...... > > just in case the regex fails. What I was trying to get was widget1 of instance 1 widget2 of instance 1 widget1 of instance 2 widget2 of instance 2 ... > -- Omri Schwarz --- ocscwar at mit.edu ('h' before war) Timeless wisdom of biomedical engineering: "Noise is principally due to the presence of the patient." -- R.F. Farr From sdm7g at virginia.edu Tue Mar 26 18:30:17 2002 From: sdm7g at virginia.edu (Steven Majewski) Date: Tue, 26 Mar 2002 18:30:17 -0500 (EST) Subject: seek in a file In-Reply-To: Message-ID: On Wed, 27 Mar 2002, Andreas Penzel wrote: > How to jump to a specified line in a file which is read-opened? > With seek() I can jump to an exact position of the complete file in > "byte-steps". > Is seek able to jump to a line-number? No Lines are variable length and delimited by a newline char ( or a pair of chars on Windows ). There's no way to find the start of the next line without reading the previous ones. Even systems, like VMS, that use a different method ( char count followed by chars ) still need to read each line, because they are still variable length records. In other words: this isn't just a language limitation of C or Python or a limitation of unix I/O libs. Fortran, for example, supports both direct (random access or 'seekable') access files and sequential access files, but direct access files must be fixed record length. > If not, what else can I do? file.readlines() returns a list of all of the lines in the file: lines = open( 'filename' ).readlines() The first line is in lines[0], the Nth line in lines[N-1]. Are the files too big to fit in memory ? What do you want to do with the lines ? ( I hope you weren't planning on trying to modify a line in a file: because of the variable length on lines, if you don't write exactly the same number of chars back, you will either overwite the next line, or leave an extra partial line after your edited line. Most text editors read the whole file into memory and then write out a new file after it's modified in memory. ) -- Steve Majewski From geiseri at yahoo.com Wed Mar 27 15:43:57 2002 From: geiseri at yahoo.com (ian reinhart geiser) Date: Wed, 27 Mar 2002 15:43:57 -0500 Subject: interactive python shell In-Reply-To: References: Message-ID: <200203271543.58084.geiseri@yahoo.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Wednesday 27 March 2002 04:11 pm, you wrote: > On Wed, 27 Mar 2002, ian reinhart geiser wrote: > > Well I was hopeing to run this as a "widget" as take input from a line > > edit and show the response on a listview widget. from the above > > directions this seems feasable, although I am not sure i want to be using > > sockets for something like this. > > Ah... this is somewhat easier then. The solution I was describing was a > console on a network server - you can basically telnet in and do remote > debugging. > hehe, actually that would be really cool, but is overkill for now... > > ah, this is a problem, because i want to be able to set the values of > > current running variables. i have a static data object from a cmodule i > > am importing that contains a fair amount of this information but i would > > like to keep away from global variables. > > Well, the problem is deciding what exactly do you mean by "current running > variables"? The issue is that your console will essentially be in a > different thread and call stack than the variables you want to inspect > (otherwise what you're looking for is simply a debugger), so you need some > way to access them, whether it be a reference to some all-encompassing > object or a global variable. if i import this debugger and pass it my main object as an argument would that work? that sounds about what you are saying i need. > > > I was looking at the interactive console class, but that seems not to > > work well from the GUI, or am I missing something? > > You can still use it just fine - override the raw_input and write methods > so that they get data from the widget and write it back out. OKay so interactive console is the beast i am looking for? Is there some sample code that shows off how it works? I think I see in my mind how the PyQt and the module side of things will work, but I am unclear how to make the interactive console get access to my global object. Thanks -ian reinhart geiser -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8oi8OPy62TRm8dvgRAq0+AKDq1oeNORv0KoswvtyY89TgKMVUKACg3AQ7 6oVU9JdluHPYMmnq1YmIyZE= =eVlG -----END PGP SIGNATURE----- _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From dale at riverhall.NOTHANKS.co.uk Wed Mar 20 11:46:19 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Wed, 20 Mar 2002 16:46:19 +0000 Subject: Develop-test-debug cycle References: Message-ID: Interesting. I've had a quick look. I'll explore later. Thanks. -- Dale Strickland-Clark Riverhall Systems Ltd From fperez528 at yahoo.com Wed Mar 6 06:54:06 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 06 Mar 2002 11:54:06 +0000 Subject: distutils question References: <3C8655CA.7080008@wi.mit.edu> Message-ID: Brian Kelley wrote: > I'm trying to bundle some example files using distutils and have been > running into some problems. > > setup(name="frowns", > version="0.2", > package_dir = {'':".."}, > > ... > data_files=[('examples', ['examples/example1.py', > 'docs/frowns.html'] > ... Take a look at Manifest.in and setup.py from http://www-hep.colorado.edu/~fperez/ipython/ (go to the downloads link). My solution is a bit kludgy, but it works for a problem very similar to what you have. You can also use Martin's PyXML, but that's a bit 'heavier'. My approach isn't nearly as flexible as what his will give you, but only uses standard distutils plus two or three lines of extra python code. Cheers, f. From tismer at tismer.com Tue Mar 5 04:23:45 2002 From: tismer at tismer.com (Christian Tismer) Date: Tue, 05 Mar 2002 10:23:45 +0100 Subject: microthreads and C calls Re: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> <7xzo1om5wt.fsf@ruckus.brouhaha.com> <3C8433CD.83B75D33@arakne.com> Message-ID: <3C848EA1.1000302@tismer.com> Frederic Giacometti wrote: ... > I could add the feature to the Python engine myself, but I need funding. > Sponsors...? No problem, I think there will be some time on my side to do that. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Kaunstr. 26 : *Starship* http://starship.python.net/ 14163 Berlin : PGP key -> http://wwwkeys.pgp.net/ PGP Fingerprint E182 71C7 1A9D 66E9 9D15 D3CC D4D7 93E2 1FAE F6DF where do you want to jump today? http://www.stackless.com/ From akuchlin at ute.mems-exchange.org Tue Mar 19 13:09:00 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 19 Mar 2002 18:09:00 GMT Subject: Still same bug even with email ver. 1.2 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> Message-ID: In article , Sheila King wrote: > On Mon, 18 Mar 2002 16:05:43 -0500, "David Rushby" >> I checked the release22-maint branch of Python out of SF CVS at approx >> 15:00 GMT on March 18. I took the next to last example in email.tex >> (the program that mails the contents of a directory) and ran it for >> three cases: Reported as bug #531966 on SourceForge. --amk From philh at comuno.freeserve.co.uk Fri Mar 29 12:46:33 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 29 Mar 2002 17:46:33 +0000 Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> <7o_o8.17314$Ou.7311@atlpnn01.usenetserver.com> Message-ID: On Fri, 29 Mar 2002 08:55:51 -0500, Steve Holden wrote: >"Fused" wrote in >message news:3ca43ef4.3666136 at news.tudelft.nl... >> I'm currently trying to master Python, but to succeed I need to >> exercise. However, I detest building programs that have already been >> built a kazillion times and aren't of use to anyone. >> Can anyone think of a program that I could build that would actually >> have use to someone (you?)? I'm trained in Delphi, know some Java and >> rudimentary C, so the programs don't need to be newbie-easy ( I like a >> challenge: the greater the challenge, the faster I'll learn ;-) ). > >I'd really like to see a Python mail/newsreader. That would teach you a lot, >and keep you busy for a while... IIRC there is already a Python mail client. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From cliechti at gmx.net Mon Mar 18 17:35:26 2002 From: cliechti at gmx.net (Chris Liechti) Date: 18 Mar 2002 23:35:26 +0100 Subject: Syntax color hightlight References: <3C966603.5010605@club-internet.fr> Message-ID: Fabien Henon wrote in news:3C966603.5010605 at club-internet.fr: > I am writing a text editor for POV-RAY (with Python-Tkinter) and > I'd like to know if it is possible to implement syntax color > highlighting for a specific language. > I'd like to implement <>,(),[] matches as well. > Is Tkinter powerful enough or do I have to use megawidget, > wxpython. yes it is. you might want to look at the Idle sources on your harddisk. chris -- Chris From bokr at oz.net Sat Mar 16 15:21:40 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Mar 2002 20:21:40 GMT Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy References: Message-ID: On Sat, 16 Mar 2002 16:50:18 GMT, "Fredrik Lundh" wrote: >Magnus Lie Hetland wrote: >> I find ServerProxy to be a more logical name, but the fact that I >> can't find it mentioned in the docs makes me a bit wary of using >> it... (On the other hand, ServerProxy is what's documented in the >> docstring. What is the history behind this duality -- and what is the >> motivation for the conflicting current usage? > >the original code used Server -- after all, the object is >representing a remote server. ^^^^^^^^^^^^ But not functioning as? This is in good part an English usage issue, but IMO the term 'proxy' should not be used except when the proxy duplicates the function and stands transparently in place of that for which it is a proxy. I expect a proxy for a server to implement the functionality it is a proxy for. Likewise a proxy for an object, or a function. But to my mind something that just provides an interface is not a 'proxy' for the thing (remote or not) it provides an interface to. If the interface were e.g., capable of fronting for a remote server or alternately a local (same machine) server, the local server might be a proxy (if providing the functionality) for the remote server, but the interface object would not be a 'proxy' for either IMO. ServerLAPI might be a better term, for Server-Local-Application-Program-Interface. I.e., it implies a bit of interfacing code or an object for that purpose, not proxy server functionality implemented within itself. A separate interface object for a proxy server might be called ProxyServerLAPI, whereas a module _implementing_ a proxy server would be called ProxyServer, even though they might provide identical methods for programming access. > >the (rather lame) ServerProxy alias was added later, after >enough people had flamed me over the original naming... > >> who thinks that SimpleXMLRPCServer should be called >> xmlrpclib.Server, with xmlrpclib.ServerProxy being used as the >> server proxy... > >most XML-RPC users don't use/need server functionality, >and shouldn't have to pay for something they don't use... > Regards, Bengt Richter From brobbins333 at shaw.ca Sun Mar 10 10:52:17 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Sun, 10 Mar 2002 15:52:17 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> Message-ID: <3c8b8112.27836128@news> OK, that makes perfect sense. In my case, I was simply looking for a predictable way to return a number with two decimal places -- knowing that it will be an approximation of Python's approximation. Obviously, using round() is not the way to go about this. I'll figure it out. Thanks for all the very informative responses. Bruce On 10 Mar 2002 12:12:10 GMT, scarblac at pino.selwerd.nl (Remco Gerlich) wrote: >brobbins333 at shaw.ca wrote in comp.lang.python: >> I understand the problem of rounding errors with binary numbers. >> However, the rounding functions of other languages work around it and >> return a usable result. What have they got that Python hasn't got? > >The other programs are liars - they show a rounded result, the way Python's >print does. > >It is not possible to represent 56.79 in a finite binary float - it's a >repetitive fraction in binary. > >Python decided not to hide this in the interactive interpreter. If you print >out a number, it looks the way it does in other languages. Under the hood, >they all do the same thing. > >-- >Remco Gerlich From martin at v.loewis.de Sun Mar 31 17:18:37 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Apr 2002 00:18:37 +0200 Subject: PEP 285: Adding a bool type References: Message-ID: Pearu Peterson writes: > Just a random thought ... > > Theorem: > ======== > Assume specification of PEP 285. The following statements hold truth: > > True is One > > and > > False is Zero, > > where One and Zero represent integers 1 and 0, respectively. It depends on what the meaning of 'is' is. Did you mean 'is' in the Python sense of checking identity? Then this theorem can't possibly true: type(One) is int and type(True) is bool implies One is not True. > > Proof: > ------ > According to PEP, True and False are instances of bool that is a subclass > of int. Therefore True and False can be considered as integers and it > makes sense to compare them with integers. If n is an integer then the > following statements hold > > True == n only if n is 1 > > and > > False == n only if n is 0. That is correct. However, a==b does not imply a is b. Regards, Martin From markus at ibp.de Wed Mar 6 05:50:21 2002 From: markus at ibp.de (markus at ibp.de) Date: 06 Mar 2002 11:50:21 +0100 Subject: what is happening at __init__ References: <3C8358C0.81D97AD8@doc.ic.ac.uk> Message-ID: Eric Brunel writes: > Your questions regarding the so-called "constructor" may simply show that > the term "constructor" is not so good after all. "Initializer"? After all, it's called "__init__". -Markus From Ken.Peek at Engineer.com Sat Mar 30 12:58:37 2002 From: Ken.Peek at Engineer.com (Ken Peek) Date: 30 Mar 2002 09:58:37 -0800 Subject: Another stab at a "switch/case" construct (for Python 3000): References: Message-ID: "Bjorn Pettersen" wrote in message news:... > > From: Steven Majewski [mailto:sdm7g at Virginia.EDU] > > > > On Fri, 29 Mar 2002, Bjorn Pettersen wrote: > > > > > > From: Steve Lamb [mailto:grey at despair.dmiyu.org] > > > > > > > > its called a directory pointing to functions = {'case':closed} > > > > > > > > I do not believe that any language which can have a hash > > > > of function pointers has any business with a case statement. > > > > > > But that only works when all the functions in all the branches take > the > > > same number and types of arguments -- hardly the general case. > > > > > > > table = {} > > > > table[key] = func, (args,...) > > ... > > > > def doit( k ): > > return table[k][0]( *table[k][1] ) > > Point taken, but is this an argument for or against the match/switch > statement ? > > Personally, I don't think it's worth adding a match statement unless we > can have ML style pattern matching... > > Not-sure-what-a-good-Pythonic-spelling-would-be-though'ly y'rs > -- bjorn Since we are no longer forcing only literals to be used (which would allow for compile time optimizations), I don't think there would be anything to stop you from allowing function calls (or other expressions) in the parameter list of a clause, which would allow you to do some pretty intricate calculations. This WOULD however redefine the way lists are parsed, and _I_ don't like that: branchon MyObject: [123, 456, "hello", [], (), xyz-abc, 42*etc, MyFunc(MyObject)]: # do some stuff # do some more stuff ["I want a branchon construct", "(and more whining)"]: # do some stuff # do some more stuff fallthrough # USEFUL a LOT! [MyOtherObject, (1,2,3), [4,5,6]]: # do some stuff # do some more stuff else: # no matching clauses, so: # do some stuff # do some more stuff def MyFunc(x): # test object "x" for all kinds of things, # and return "x" if you want a match, # else return something guaranteed to # fail, like (x,none) if x_is_a_match: return x else return (x,none) ===================== This would be clear and readable. Use your imagination-- FEEL THE POWER of this construct (to make more readable code)... I-am-not-trying-to-impress-you-with-my-python-knowledge'ly yours, --Ken Peek ===================== From brueckd at tbye.com Sun Mar 3 21:08:42 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sun, 3 Mar 2002 18:08:42 -0800 (PST) Subject: Rotor in Jython? In-Reply-To: <7xlmdaf2pz.fsf@ruckus.brouhaha.com> Message-ID: On 3 Mar 2002, Paul Rubin wrote: > > > > Put another way: sorting by key length, AES beats rotors hands down. > > > > Sorting by computational cost, rotors always win because you can just make > > > > the keys longer (without having to reimplement your crypto). > > > > > > Longer keys are only relevant if breaking the cipher requires searching > > > for the key. > > > > Heheh... that's essentially what cryptanalysis is - finding the key since > > in most cases the algorithm itself is known. If you're referring to > > non-brute force key searches, then key length is relevent there as well > > (unless the algorithm itself is flawed). > > Yes, that's the point. AES appears to be very attack resistant. No, it's better than DES but it's widely recognized that AES is actually susceptible to some of the same types of differential cryptanalysis. Personally I think it's plenty strong, but it's not immune. > Compared to AES, rotors have a pretty sorry history of falling to > cryptanalysis. There's no reason to think brute force is the best way > to solve a rotor cipher. But the sorry history of rotors has nothing to do with rotor strength and everything to do with short/obvious keys, the obvious starting text of the messages (e.g. "No news to report"), and the limitations of mechanical implementations. You can *always* make a rotor stronger by increasing the length of the key - and at no additional computational cost. -Dave From clpy at snakefarm.org Fri Mar 15 17:40:22 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Fri, 15 Mar 2002 23:40:22 +0100 Subject: Pretty Integers References: Message-ID: <3C927856.6F48EC69@snakefarm.org> Lindstrom Greg - glinds wrote: > > I would like to add commas to the integers I am writing (for example: > 12345678 --> 12,345,678). I have a fairly ugly method that relies heavily > upon mods, but am convinced there must be a "pretty" way to do it. How > would you go about this task? > How about some nice recursion? This is how I do it: #! /usr/bin/python def pretty_int(ugly_int): if len(ugly_int) <= 3: return ugly_int return pretty_int(ugly_int[:-3]) + "," + ugly_int[-3:] ugly_int = 12345678 print pretty_int(str(ugly_int)) cg. From peter at engcorp.com Tue Mar 12 00:59:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Mar 2002 00:59:50 -0500 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> <3C8C02B3.674898B0@engcorp.com> <3C8C0460.993A4F81@engcorp.com> Message-ID: <3C8D9956.5920AA52@engcorp.com> Magnus Lie Hetland wrote: > > In article <3C8C0460.993A4F81 at engcorp.com>, Peter Hansen wrote: > [...] > >Just posted to the TDD mailing list, coincidentally: > > > > http://www.math.ucr.edu/home/baez/crackpot.html > > > >Anyone care to calculate the total for our pet crackpot? :-) > > Well, I can give a reliable lower limit: 50 points. > > Just see item 32: "50 points for claiming that you have a > revolutionary theory but giving no concrete testable predictions." With slight paraphrasings for the change in industry from physics to computers, we can also add item 31 (40 points) for how "current programming methods are a sham and we'll see that once autocoding is finally appreciated", item 29 (40 points) referring to "the conspiracy among programmers preventing his work from getting its deserved fame", item 21 (20 points) for constant references to the Matrix, item 14 (10 points) for trying to get us all to do the work for him, and roughly 473 invocations of each of items 4 (3 points each) and 3 (2 points each), to wit: logically inconsistent and clearly vacuous statements, respectively. Resulting in a grand total Crackpot Index of about 3471, surely an all-time record. Somebody tell John Baez! -Peter From peter at engcorp.com Sun Mar 10 01:51:31 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 01:51:31 -0500 Subject: wxPython: generating event IDs? References: Message-ID: <3C8B0273.A3651580@engcorp.com> Grant Edwards wrote: > > I'm trying to figure out a simple way to attach commands to > buttons in wxPython. The standard method seems to be > > 1) Define a unique ID number > 2) Assign that ID number to the button > 3) Hook a closure to that ID number with EVT_XXXX() > > There must be a way to eliminate the need to predefine unique > ID numbers. I hate trying to maintain lists of numbers like > that (well, more accurately, I'm just bad at it). > > I thought about using the id() of the button, but you don't > know that until after the button is created, and you need to > pass the ID in when the button is created. > > There must be a simple solution that I've overlooked... This little method which I've used inside a wxFrame subclass demonstrates a slightly simpler approach than "define a unique ID number". Note the use of wxNewId() to make that part trivial. If you attach your commands to buttons using a method you can wrap the little bit of ugliness and never have to see it again: # define menus def setupMenus(self, menuList): self.mainmenu = wxMenuBar() for menuName, menuItems in menuList: _menu = wxMenu() _menuId = wxNewId() for itemName, itemHint, itemMethod in menuItems: if itemName == '---': _menu.AppendSeparator() elif type(itemName) == type(''): _itemId = wxNewId() _menu.Append(_itemId, itemName, itemHint) EVT_MENU(self, _itemId, getattr(self, itemMethod, self.menuIgnore)) self.mainmenu.Append(_menu, menuName) self.SetMenuBar(self.mainmenu) return From grey at despair.dmiyu.org Thu Mar 28 17:22:04 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 28 Mar 2002 22:22:04 -0000 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: On Thu, 28 Mar 2002 07:52:45 -0800, Ken Peek wrote: > Well, what do you think? case: Don't like it. We already have means to do what a case does and do it more elegantly. It would add a needless redundant portion to the language. unless: Do a deja search on while 1 on this newsgroup. It has been hashed to death. Short form, while can be manipluated to be any of the special case loops, until is a special case loops, we should not add things for special case loops when the generic construct, while, works just fine. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From elflord at panix.com Fri Mar 1 13:17:09 2002 From: elflord at panix.com (Donovan Rebbechi) Date: Fri, 1 Mar 2002 18:17:09 +0000 (UTC) Subject: Scripting C++ -- 2 -- a more concrete example. References: <3C7E6642.2030202@physics.ucsb.edu> <6bf54244.0203010925.38d237ed@posting.google.com> Message-ID: In article <6bf54244.0203010925.38d237ed at posting.google.com>, Craig Maloney wrote: > Donovan Rebbechi wrote in message news:... >> In article <3C7E6642.2030202 at physics.ucsb.edu>, Craig Maloney wrote: >> > If using a wrapper generator (e.g. SILOON) I don't see a way around the >> > marshalling of the call to get at the atom data structure. >> >> I don't really understand exactly what the problem is. >> > >> > Of course, this would be taken care of by a revamp of the design of the >> > class library... maybe making the crystal an atom factory that produces >> > new atoms in its own address space. But I would like to avoid thinking >> >> Now I'm really confused. If you're not using CORBA, the atoms are in the >> same address space, aren't they ? > > This is how I presumed that Boost also worked -- I must be mistaken. > After having seen yours and Ralf's comments, I now have the impression > that Boost works it's magic differently. > > Perhaps Craig Rasmussen could enlighten us as to how SILOON deals with > co-location issues such as the one above? > > From the SILOON doc/design.html page : Looks like SILOON is using some sort of client/server architecture, much like CORBA. Sip, which is what I use, doesn't do this. It simply wraps C++ objects. Basically, Python objects are represented in C as PyObject* pointers. What sip does is create a "derived" struct by aggregating a PyObject, and some additional stuff. So in the sip model, you'd just be using wrapped python objects. It's not completely automatic, because there are some choices that can't be made automatically. For example, there are tricky choices about ownership -- when you call "add", does the object you "add" to want to own a reference (bump up the reference count) ? You also do need to add code to return python tuples instead of using the C/C++ "return-by-pass-by-pointer" idiom. Like I said, even though it's not automatic, you get a good code generation ratio. Also, even in instances where it's not completely automatic (eg exception mapping), you can use generated code as a starting point. I use macros to map exceptions, which makes this a very simple process. Cheers, -- Donovan From brueckd at tbye.com Wed Mar 27 13:32:07 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 27 Mar 2002 10:32:07 -0800 (PST) Subject: instrumenting Python code In-Reply-To: Message-ID: On 27 Mar 2002, Aahz wrote: > In article , > Skip Montanaro wrote: > > > >Or, in 2.2, the new hotshot module, which is a lot more efficient at > >profiling than the profile module. > > Where is hotshot? I don't see it anywhere. It's not even on the Vaults > of Parnassus. It's a C module new in 2.2 - see Modules/_hotshot.c. -Dave From default_renegade at yahoo.com Sun Mar 3 13:52:58 2002 From: default_renegade at yahoo.com (default_renegade) Date: Sun, 03 Mar 2002 18:52:58 -0000 Subject: Trouble running programs Message-ID: Just started learning Python, but having trouble running a programs. First, I open IDLE, then open a new window Then I write a program and save it, then I close the window When I'm back at the Python Shell and select Run Script It gives me an error "Not Saved - The bugger for Python Shell is not saved. Please save it first!" However, I can run the program from the DOS prompt. From erno-news at erno.iki.fi Thu Mar 21 23:18:19 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 22 Mar 2002 06:18:19 +0200 Subject: Why do Windows sockets break after exactly 4 minutes? References: Message-ID: In article , Geoffrey Talvola writes: | I've noticed that Windows sockets seem to close all by themselves if there | is no activity for 4 minutes. Does anyone know why? Is it possible to | control this behavior? Just a link to some documentation of this behavior | would be greatly appreciated. usually when this happens, it means there is some sort of "stateful firewall" [sic] or NAT box in the way. if you can find out where it is and who controls it, it may be possible to alleviate the problem by increasing the timeout setting. or you can add some sort of periodical dummy message into your protocol to refresh the memory of the interloper box. -- erno From justin at iago.org Tue Mar 5 12:49:05 2002 From: justin at iago.org (Justin Sheehy) Date: Tue, 05 Mar 2002 12:49:05 -0500 Subject: Order of constructor/destructor invocation In-Reply-To: ("Reginald B. Charney"'s message of "Tue, 05 Mar 2002 05:37:37 GMT") References: Message-ID: "Reginald B. Charney" writes: > In Python, are destructors defined to be invoked in reverse order of > constructors? No. > The following program illustrates the problem: > > class HTML: > def __init__(self): print "" > def __del__(self): print "" > > class BODY: > def __init__(self): print "" > def __del__(self): print "" > > class PHP: > def __init__(self): print " def __del__(self): print "?>" > > if __name__ == "__main__": > print "Start of program" > h = HTML() > b = BODY() > p = PHP() > print "Body should appear before all destructors" A few comments: You really don't want to construct documents that way. There are a few good html generation libraries out there, and it is also easy to roll your own. Trying to generate documents as a side effect of object destruction not only won't work, it is a really bad idea. Also, I have no idea what makes you think that you are able to know anything about the order of the destructors. All three of the relevant objects here will lose their reference at the same time, so the order of their destruction is even less determined than usual. > Basically, I need to know if the order of destruction is guaranteed to be > the reverse of construction when reference counts on the objects are the > same (e.g., 1 on this case). Without this guarantee, I don't understand how > Python can effectively use destructors - it falls into the same hole as > Java. For me, this is a show-stopper. This makes no sense. When the reference count of an object is nonzero (e.g. 1), the destructor will not be called at all because the object is not yet eligible for reclamation. Order doesn't even come into it. Destroying an object before its reference count had dropped to zero would be unsafe and not very sensical. Perhaps you are using "destructors" to refer to some concept that is different from what the rest of us use that word for? -Justin From aahz at pythoncraft.com Thu Mar 28 22:42:01 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2002 22:42:01 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: In article , phil hunt wrote: > >class MyClass(BaseClass): > def __init__(self): > pass > def method1(self, a, b, c): > pass > def method2(self, d, e): > pass > def method3(self, f): > pass Where you write "pass", I prefer to write "raise NotImplementedError". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From Francois-regis.Chalaoux at sanofi-synthelabo.com Mon Mar 4 12:01:04 2002 From: Francois-regis.Chalaoux at sanofi-synthelabo.com (Francois-regis Chalaoux) Date: Mon, 4 Mar 2002 18:01:04 +0100 Subject: Réf. : Re: R?f. : Re: strange libtk8.3.so: open failed Message-ID: <"020305011813Z.WT09319. 17*/PN=Francois-regis.Chalaoux/O=RESEARCH/PRMD=SANOFI/ADMD=ATLAS/C=FR/"@MHS> Hi, I'm back ;-) >>What is the difference between this command line and the way >>you tried to use Tk? What is $LD_LIBRARY_PATH in your command line >>environment? This is not easy to get information from the administrator and I don't know very well the sun machines ... In fact, if root uses the /etc/profile, LD_LIBRARY_PATH contain /usr/local/lib; I canread it. Thus on command line *tk* should be imported. Not verify, I'm not root ... The administrator tells me that a python process through Apache is started by a root daemon, and that its LD_LIBRARY_PATH does not contain /usr/local/lib. I conclude root daemon should have a particular profile somewhere !? Not clear for me. Why not add this latest path in LD_LIBRARY_PATH for the root deamon if it is the problem ? The administrator tell me it is not a good idea to do that !! What do you think ? FR phd at phd.pp.ru%internet le 20/02/2002 09:42:30 Veuillez r?pondre ? phd at phd.pp.ru%internet at WTFR Pour : Francois-regis Chalaoux/FR-LABEGE/RESEARCH/SANOFI at Research cc : python-list at python.org%internet at WTFR Objet : Re: R?f. : Re: strange libtk8.3.so: open failed Mail-Followup-To: Francois-regis Chalaoux , python-list at python.org User-Agent: Mutt/1.2.5i On Tue, Feb 19, 2002 at 03:23:08PM +0100, Francois-regis Chalaoux wrote: > * The sun machine is: > SunOS lads01 5.8 Generic_108528-03 sun4u sparc SUNW,Ultra-60 > > * On command line Dynamic linker find libtk8.3.so and the librairie is there: > > lads01 /tmp/Python-2.1.1 % ldd /usr/local/bin/python > libtk8.3.so => /usr/local/lib/libtk8.3.so Looks good. What is the difference between this command line and the way you tried to use Tk? What is $LD_LIBRARY_PATH in your command line environment? Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From gcordova at hebmex.com Fri Mar 8 13:30:11 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Fri, 8 Mar 2002 12:30:11 -0600 Subject: Is current integer for-loop syntax a wart? Message-ID: <19650FF08A99D511B19E00B0D0F0632301D6892A@SRM201002> -Wart? It's not that ugly, or at least not "argh, the pain!!" kind of ugly, "it just is". Of course, it'd be nice to use the Ellipsis to create integer progressions, like the "Ints" object I sent to the list a few days ago, but it's only in the "it'd be nice" category, and if I really want it, I can "from IntsClass import Ints" to have access to it. Nothing to patch up the compiler and language for. -gustavo From aahzpy at panix.com Thu Mar 21 15:41:23 2002 From: aahzpy at panix.com (Aahz) Date: 21 Mar 2002 15:41:23 -0500 Subject: Problem with threads References: Message-ID: In article , Maric wrote: > >* I want to use TKinter with multi-threads, is there any solution ? http://www.pythoncraft.com/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From b_mcerlean at yahoo.com Fri Mar 22 10:33:55 2002 From: b_mcerlean at yahoo.com (Brian McErlean) Date: 22 Mar 2002 07:33:55 -0800 Subject: Sorting distionary by value References: Message-ID: Artur Skura wrote in message news:... > No, and it seems the problem is not with sorting. > I wanted to write a compact word counting script (well, in shell > it can be done in a 5 lines or so), just for fun. > > and > > import string,sys > > > a = string.split(open(sys.argv[1],'r').read()) > > known = [] > times = 0 > output = {} > > for i in a: > if i not in known: > for l in a: > if l == i: > times = times + 1 > known.append(i) > output[i] = times > times = 0 The first 3 lines are probably the major performance problem - for every element in the list, you are scanning through the list of words again (Your algorithm is O(N**2) with regard to the number of words) Instead, you can do it in one pass, storing the count for each word in a dictionary( which has approx O(1) (constant time) access. Words you haven't counted yet get put into the dictionary with a count of 1, and existing words get their count incremented. The loop then becomes: for word in a: count = output.get(word, 0) # Get count of word, or 0 if not present output[word] = count + 1 # Increment count. The output can remain the same: > items = [ (output[k], k) for k in output ] > items.sort() > items.reverse() > items = [ (k, v) for (v, k) in items ] > for k in items: > print k[0], k[1] > > it seems it's slow not because of sorting... > > Regards, > Artur Hope this helps, Brian. From martinkaufmann at yahoo.com Wed Mar 13 07:21:43 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Thu, 14 Mar 2002 01:21:43 +1300 Subject: Question about scientific calculations in Python References: Message-ID: <1pgu8u4nqjj8hbghv20s9osn9721uhlevg@4ax.com> On Wed, 13 Mar 2002 00:13:50 -0600, "Jason Orendorff" wrote: >Keep in mind, though, that the code I wrote creates a huge 2D array >when it is presented with largeish 1D arrays as arguments. > >So if s_vector is 10000 elements and r_vector is 10000 elements, >then a 800-MB array is created. If you've got the RAM, this is >okay; otherwise you're in trouble. The machine I'm using for my calculations has 2 GB of memory. And the vectors probably have only about n00-n000 entries. >Also, does anyone have weave.blitz? I'd like to see how it does >compared to the other approaches. I will try that tomorrow. Which part should I exactly blitz? Thanks, Martin From gerhard at bigfoot.de Thu Mar 28 21:21:00 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 29 Mar 2002 02:21:00 GMT Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> Message-ID: Sloth wrote in comp.lang.python: > I've looked at Apache, Xitami, Zope, Medusa, et. al and think they are > wonderful applications. On the other hand, they are overkill for what > I want to be able to do - have Python start a CGI server, serve a > page, get form data, get data from a database, and display dynamic > content. I don't need anything industrial strength, just something > that can handle a single user. Maybe it's just me, but I often have difficulties to understand the point of the "overkill" argument. > Any thoughts? I sincerely appreciate everyone's help! If you can spare 5 megs of RAM and a little disk space, just go for Apache (or Xitami, or whatever). When you're running the webserver and are not using it currently, it'll be swapped out anyway, so why bother? It's a myth that Apache is complex to get running, here's what you'd need to do on Windows: 1) Install Python 2) Install Apache 3) edit etc/httpd.conf and add the line ScriptInterpreterSource Registry at the end of the file. 4) Write your Python CGI scripts in cgi-bin and name them .py Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From emile at fenx.com Thu Mar 28 17:42:24 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 28 Mar 2002 14:42:24 -0800 Subject: Running zope as a WIN32 service References: Message-ID: pitbill > I've installed Zope 2.4 two weeks ago and didn't choose to run Zope as a > service :( > Now I want to run Zope as a service, because I'm bored of starting it via > the batch file. > from zservice.py: You can manually install, uninstall the service from the commandline. ZService.py [options] install|update|remove|start [...] |stop|restart [...]|debug [...] -- Emile van Sebille emile at fenx.com --------- From stojek at part-gmbh.de Thu Mar 28 10:58:26 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Thu, 28 Mar 2002 15:58:26 GMT Subject: question on struct.calcsize Message-ID: <3ca33d3f.26101031@news.easynews.net> Hi, could anyone explain the following, please. (Win NT, Python 2.1.1) >>> from struct import * >>> calcsize("i") 4 >>> calcsize("s") 1 >>> calcsize("si") 8 Thanks, Marcus From soerense at verwaltung.uni-mainz.de Wed Mar 6 04:37:12 2002 From: soerense at verwaltung.uni-mainz.de (Ruediger Soerensen) Date: 06 Mar 2002 10:37:12 +0100 Subject: Python song? (Re: Python isn't necessarily slow) References: <86n0xmg2q4.fsf@skitty.catseye.net> Message-ID: "Emile van Sebille" writes: > "Cliff Wells" > > Tim Legant wrote: > > > Oh, are you from across the pond? It was either Bronski Beat or the > > > Communards who did an interesting cover of Ain't Necessarily So in > the > > > early '80s - I think both groups were Brits.... It's in more of a > > > Broadway musical style than country, though. > > > > It was Bronski Beat (from "Age of Consent"). I don't recall who did > the > > original. > > > > I'm going bet it's from Porgy & Bess by Gershwin. > > -- > > Emile van Sebille > emile at fenx.com > > --------- > Yes. Sung by "Sportin' Life". There was a great movie where Sammy Davis jr. played him. -- R?diger "Black Hole" S?rensen || soerense at verwaltung.uni-mainz.de From tbabbitt at commspeed.net Thu Mar 7 11:18:38 2002 From: tbabbitt at commspeed.net (Tom Babbitt) Date: Thu, 7 Mar 2002 09:18:38 -0700 Subject: wxVTKRenderWindow inside wxSplitterWindow References: <3c8772cb.20639421@news.easynews.net> Message-ID: <1015518221.284284@news.commspeed.net> "Marcus Stojek" wrote in message news:3c8772cb.20639421 at news.easynews.net... > HI, > > I want to use a wxSplitterWindow to render two different > body with VTK. Here is what I tried > > > > #--------------------------------------------------------------------------- > > but that didn't work either. > > Any idea ? > > Thanks, > Marcus > You could try placing panels on the splitter windows and the place the wxVTK window on the panel (there is some mention of this in the demo code), on the other hand maybe a sizer will work. Tom Babbitt From store_li at sina.com Thu Mar 7 00:06:05 2002 From: store_li at sina.com (Ricky) Date: Thu, 7 Mar 2002 13:06:05 +0800 Subject: Is there any wxPython turtor? References: <3C865341.8D190235@cablespeed.com> Message-ID: Thank you, I find a lot of resources. But wxpython.org is still not available for me. "Michele Moore" wrote in message news:3C865341.8D190235 at cablespeed.com... > Ricky wrote: > > > I have downloaded wxPython 2.3. But, I found that the document come with it > > is not well enough. Is there any recommended good tutor of wxPython itself?? > > > > BTW: I don't know why I can't connect to www.wxpython.org, is it still > > alive? > > You might consider visiting: > http://wiki.wxpython.org/index.cgi/How_20to_20Learn_20wxPython > > Most of the actual API documentation is written for the C++ implementation > underneath, wxWindows, which is very thorough. Here's a good reference > for a number of tutorials: http://www.wxwindows.org/docs2.htm > > BTW, I was able to go to http://www.wxpython.org just fine just now. > > Michele > From maurelius01 at hotmail.com Fri Mar 22 17:08:55 2002 From: maurelius01 at hotmail.com (Marc) Date: Fri, 22 Mar 2002 17:08:55 -0500 Subject: mutlifile inheritance problem simplified References: <9896e047.0203211303.741f695a@posting.google.com> Message-ID: <3C9BAB77.B4E17C65@hotmail.com> I posted this previously but a typo confused the issue. I'll be more carefull this time, plus I've simplified the names. The issue has to do with using reload and inheritance, specifically having two classes in two different files inheriting from a base class in another file. Or maybe it's just inheriting and reloading, I haven't gone through the many permutations, but here's a simple example that doesn't work. I'm using Windows NT, Python 1.5.2, and IDLE 0.5 ************************ file a01.py class a: def __init__(self): self.name = 'a' ************************ file b01.py import a01 reload(a01) class b(a01.a): def __init__(self): self.name = 'b' a01.a.__init__(self) ************************ file c01.py import a01 reload(a01) class c(a01.a): def __init__(self): self.name = 'c' a01.a.__init__(self) ************************ file atest01.py import b01 reload(b01) import c01 reload(c01) B = b01.b() C = c01.c() print 'done' ************************* running atest01 (F5 in IDLE) give the traceback: >>> Traceback (innermost last): File "", line 1, in ? File "D:\PythonCode\pna\eyeTracking\tests\atest01.py", line 7, in ? B = b01.b() File "D:\PythonCode\pna\eyeTracking\tests\b01.py", line 8, in __init__ a01.a.__init__(self) TypeError: unbound method must be called with class instance 1st argument If I don't have the reload in c01.py and b01.py eveything works fine. Any ideas. Does anyone else find the same behavior here? Thanks, Marc From bosahv at netscapenospam.net Thu Mar 28 00:16:38 2002 From: bosahv at netscapenospam.net (Bo Vandenberg) Date: Thu, 28 Mar 2002 05:16:38 GMT Subject: Zope Install probs on Mandrake 8.2 Message-ID: I'm trying to install Zope from source on a fresh install of Mandrake 8.2. I'd appreciate it if anyone here has advice for this. "python wo_pcgi.py" fails building the extension modules saying "cannot stat `/usr/lib/python2.2/config/Makefile.pre.in': No such file or directory. This is indead true. Is there something a beginner should do at this point? Zope claims to run on python 2.1 will it run on 2.2??? Thanks in advance. From lluang at northwestern.edu Sun Mar 24 00:40:57 2002 From: lluang at northwestern.edu (Louis Luangkesorn) Date: Sat, 23 Mar 2002 23:40:57 -0600 Subject: using os.execl to call a java application Message-ID: <3C9D66E9.4070802@northwestern.edu> Hello: I am trying to use Python to call a Java application with parameters and I am trying to use os.execl to do this. When I am at the command line, the following works: C:\docs\ibmmodelswitch>c:\jdk1.3\bin\java depmmk1 22.0 20.0 10.0 0.0 0.0 20 20 5 5 5 5 0.009888807988285522 But when I try to call this from Python using os.execl, I get File "C:\docs\gmcode\prob4.py", line 74, in findrqsim os.path('c:\\docs\\ibmmodelswitch') TypeError: object of type 'module' is not callable >>> Lines 73 and 74 are as follows: os.path('c:\\docs\\ibmmodelswitch') rab[i,j] = os.execl('c:\\jdk1.3\\bin\\java','depmmk1',`itemmu[0]`,`itemmu[1]`,`itemlambda[0]`,`itemlambda[1]`,`itemlambda[2]`,`itemn[0]`,`itemn[1]`,`itemQ[0]`,`itemQ[1]`,`itemreorder[0]`,`itemreorder[1]`) I've tried to use the full path for 'depmmk1' in the os.execl() call. I've tried using one '\'\ for the directory, I've also tried to have the second arguement 'depmmk1.class'. The following also fails: os.path('c:\\docs\\ibmmodelswitch') rab[i,j] = os.execl('c:\\jdk1.3\\bin\\java','depmmk1') Anyone help? Or is there an even better way to do this? The next question I'm going to have is how to get a result from my Java application into Python. I can use a text file write/read, but if there is a more elegant way of doing this I'd appreciate hearing about it. Thank you much. Louis By the way, what I really want to do is this: os.path('c:\\docs\\ibmmodelswitch') rab[i,j] = os.execl('c:\\jdk1.3\\bin\\java','depmmk1',`itemmu[0]`,`itemmu[1]`,`itemlambda[0]`,`itemlambda[1]`,`itemlambda[2]`,`itemn[0]`,`itemn[1]`,`itemQ[0]`,`itemQ[1]`,`itemreorder[0]`,`itemreorder[1]`) Which gives the same error. Louis -- K Louis Luangkesorn lluang at northwestern.edu http://pubweb.nwu.edu/~kll560 PGP:0xF3E2D362 Whatsoever things are true, ... honest, ... just, ... pure, ... lovely, ... of good report; if there be any virtue, and if there be any praise, think on these things. - motto - Northwestern University From drevenhaug at hotmail.com Mon Mar 11 10:31:55 2002 From: drevenhaug at hotmail.com (Graz Bukanoff) Date: 11 Mar 2002 07:31:55 -0800 Subject: Is Python an object based programming langauge? Message-ID: Is Python an object based programming langauge? From theller at python.net Mon Mar 4 11:51:54 2002 From: theller at python.net (Thomas Heller) Date: Mon, 4 Mar 2002 17:51:54 +0100 Subject: Win32 2.2 & 2.1.2 References: Message-ID: "Robin Becker" wrote in message news:Uu$EsXAKB6g8EwJf at jessikat.demon.co.uk... > Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the > default for a win32 box. It would allow us to dip a toe in the water > without drowning. 2 ways AFAIK: 1. Install 2.2, then 2.1.2 *again* 2. Install 2.2, then change the file associations to use 2.1.2. Thomas From cliechti at gmx.net Thu Mar 28 16:02:42 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Mar 2002 22:02:42 +0100 Subject: rexec: I don't seem to understand "nok_builtin_names" References: <39503ed5.0203281151.25d2cdda@posting.google.com> Message-ID: danielm at cronus.res.cmu.edu (Dan Moskowitz) wrote in news:39503ed5.0203281151.25d2cdda at posting.google.com: > Can someone tell me why execing "open" works, but not "len"? > >>>> from rexec import RExec >>>> >>>> class MyRExec(RExec): > ... nok_builtin_names = RExec.nok_builtin_names + ("len",) > ... >>>> r = MyRExec() >>>> print 'invisible names: '+`r.nok_builtin_names` > invisible names: ('open', 'reload', '__import__', 'len') >>>> r.r_exec('open') >>>> r.r_exec("len('foo')") > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/depot/python2/lib/python2.1/rexec.py", line 264, in > r_exec > exec code in m.__dict__ > File "", line 1, in ? > NameError: name 'len' is not defined because "open" is bound to a restricted replacement function: >>> r.r_exec('print open') > see the rexec documentation for more details about the restricted "open" the same aplies to the other builtins, they're replaced with limited versions. chris -- Chris From jeff at ccvcorp.com Fri Mar 22 16:11:06 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 13:11:06 -0800 Subject: Sorting distionary by value References: Message-ID: <3C9B9DEA.3AF92183@ccvcorp.com> Artur Skura wrote: > for i in a: > if i not in known: > for l in a: > if l == i: > times = times + 1 > known.append(i) > output[i] = times > times = 0 > > it seems it's slow not because of sorting... Yes, you're scanning through the file once for *each* word you find, just to count occurences. Try this instead: words = string.split(open(sys.argv[1],'r').read()) wordcount = {} for word in words: wordcount[word] = wordcount.get(word, 0) + 1 items = [ (value, key) for key, value in wordcount.items() ] items.sort() items.reverse() # items = [ (k, v) for (v, k) in items ] # Why bother with the above?? for count, word in items: print word, count Jeff Shannon Technician/Programmer Credit International From benji_york at cal-na.com Fri Mar 22 17:33:42 2002 From: benji_york at cal-na.com (Benji York) Date: 22 Mar 2002 14:33:42 -0800 Subject: New SIG on logic/CLP programming in Python References: Message-ID: <59667b81.0203221433.261c8210@posting.google.com> nico at aries.logilab.fr (Nicolas Chauvat) wrote in message news:... > I'd like to entertain you with a new subject: logic programming and > constraint-propagation features in Python. I would be very interested in a finite domain constraint slover in/connected-to Python. though-not-volunteering-to-implement-it--ly y'rs Benji York From peter at engcorp.com Fri Mar 29 11:12:48 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 11:12:48 -0500 Subject: The Python Way References: Message-ID: <3CA49280.BF6B6C40@engcorp.com> FREDRIK HULDTGREN wrote: > > On a side note, what does PEP stand for?, Ive been seeing it all over > the mails but I have no clue what it is. > :) Why not try Google? http://www.google.com/search?q=pep+python From cfelling at iae.nl Mon Mar 4 23:28:08 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 5 Mar 2002 05:28:08 +0100 Subject: chopping a string References: Message-ID: David Bear wrote: > there's gotta be an easier way. I have a string > > note the leading a trailing whitespace. I'd like to grab the first > word and strip whitespace. I came up with > string.join(string.split(string.strip(str))[:1]) This looks very complicated, maybe you just ment: >>> string.split(" something somethingelse ", maxsplit=1)[0] 'something' To get the same effect with string methods be ware that you'll have to specify None as seperator to get the special space treatment: >>> " something somethingelse ".split(None, maxsplit=1)[0] 'something' The maxsplit=1 is there to speed things up, it stops after the first split. -- groetjes, carel From jeffbi at jetsoft.com Fri Mar 29 12:23:45 2002 From: jeffbi at jetsoft.com (Jeff Bienstadt) Date: Fri, 29 Mar 2002 09:23:45 -0800 Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> <7o_o8.17314$Ou.7311@atlpnn01.usenetserver.com> Message-ID: <3ca4a322@news.nwlink.com> "Andrei Kulakov" wrote in message news:slrnaa93j2.kqo.ak at ak.silmarill.org... > In article <7o_o8.17314$Ou.7311 at atlpnn01.usenetserver.com>, Steve Holden wrote: > > "Fused" wrote in > > message news:3ca43ef4.3666136 at news.tudelft.nl... > >> I'm currently trying to master Python, but to succeed I need to > >> exercise. However, I detest building programs that have already been > >> built a kazillion times and aren't of use to anyone. > >> Can anyone think of a program that I could build that would actually > >> have use to someone (you?)? I'm trained in Delphi, know some Java and > >> rudimentary C, so the programs don't need to be newbie-easy ( I like a > >> challenge: the greater the challenge, the faster I'll learn ;-) ). > > > > I'd really like to see a Python mail/newsreader. That would teach you a lot, > > and keep you busy for a while... > > > I'd like to second that. I use slrn and mutt and they're pretty good but > I'd hack on a few things, polish rough edges, etc if they were written > in python. A program that tries to do both probably won't be very good > at either, if I were you I'd either make a news or - an email reader. > > - Andrei I've just recently started working on a newsreader in Python (it was the underlying reason behind my earlier "IntSpan" posts). It's not much further along than the idea stage at this point, since I'm trying to sandwich it in between several other projects, but I have a few lines of experimental code that uses nntplib. I'm doing this primarily as a way to learn Python (why start small :->), but also so that I can have a news reader that a) works b) runs on both my Linux and Windows boxen c) isn't Outlook Express If anybody is interested in joining me on this, or just interested in hearing some of my thoughts on the subject, e-mail me --- I love collaborative projects. ---jkb From bkelley at wi.mit.edu Fri Mar 1 09:27:18 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 01 Mar 2002 09:27:18 -0500 Subject: ASV module, CVS modules References: <61ff32e3.0202281525.3e9bb102@posting.google.com> <3C7F4014.7090800@stroeder.com> Message-ID: <3C7F8FC6.8090500@wi.mit.edu> Michael Str?der wrote: > John Machin wrote: > >> >> You 2: On Windows, either use forward slashes "c:/test_data.csv" (it >> works!) > > > AFAIK this does not work on W2K anymore. I might be wrong. > It does on my system at least. file = open("c:/test_data.csv", "wb") > Ciao, Michael. > Brian Kelley From robin at jessikat.fsnet.co.uk Mon Mar 25 04:02:48 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 25 Mar 2002 09:02:48 +0000 Subject: 2.2 open References: Message-ID: In article , Delaney, Timothy writes ....... >> import types >> if type(__import__) == types.BuiltinFunctionType: >> ... > >Except that this will only tell you that it's of the same type as the >original __import__ - someone still may have replaced the builtin __import__ >before you get a go at it. > >In general, it shouldn't matter whether it is the builtin __import__ or not >- why do you need to know? If you wish to replace it with your own version, >you should just capture the original version and replace it with your own. >To do this in a thread-safe manner you should probably use the canonical >"swap" idiom ... > >import __builtin__ > >def _my_import (name, globals, locals, fromlist): > pass > >_orig_import, __builtin__.__import__ = __builtin__.__import__, _my_import > >print _orig_import >print __builtin__.__import__ > >Tim Delaney > Gordon McMillan's original archive_rt had code to detect the original so it could apply its startup. It's reasonable to suppose that this is quite hard since I am attempting to do this in the middle of starting up Python itself and as I have a compressed archive I can't gurantee access to stuff like warning.py types.py etc at the time of the test. There's probably a more direct way to test this though since I know exactly when the test is taking place and should succeed. -- Robin Becker From dominikush at yahoo.com Thu Mar 14 06:48:45 2002 From: dominikush at yahoo.com (dominikush) Date: Thu, 14 Mar 2002 11:48:45 -0000 Subject: How to access DataObject retrieved from win32clipboard? Message-ID: Hi, I copied some graphical elements from Powerpoint to the clipboard. My aim is to convert the clipboard data to png and store the image in a file. The problem is that I retrieve a DataObject from win32clipboard and I do not understand how to continue from there. Can somebody help me out here? >>> import win32clipboard >>> win32clipboard.OpenClipboard(0) >>> win32clipboard.EnumClipboardFormats(0) 49161 A strange data format. So, let's find out what it is: >>> win32clipboard.GetClipboardFormatName(49161) 'DataObject' So, let's try to get the `DataObject' from the clipboard: >>> data = win32clipboard.GetClipboardData(49161) >>> data '\xb8\x02\x05\x00' Ups, what's this? Looks like an identifier/handle to `DataObject'. But where's the object? How do I resolve the identifier? Any suggestions? Best regards, Dominikus From swojqh at comcast.net Thu Mar 7 19:32:04 2002 From: swojqh at comcast.net (swojqh at comcast.net) Date: Fri, 08 Mar 2002 00:32:04 GMT Subject: 5 dollar emails Message-ID: <8ETh8.84681$pN4.6393667@bin8.nnrp.aus1.giganews.com> Please check out 5 dollars an email...I earned over $850.00 last month simply by using this program. This company is free to join. You can get paid and earn prizes for surfing,reading email,t aking surveys, chatting and playing games. To read all about the program,you must click on the link and sign up. there are no obligations Just click on the link on the mail and it will take you to the sign-up page in a new window. Remember to refer all your friends, as this is how you will make more money. GOTO http://www.5DollarEmails.com/cgi-bin/signup.cgi?r=prowler00x at comcast.net From jeetkunedoh at yahoo.com Fri Mar 22 10:33:56 2002 From: jeetkunedoh at yahoo.com (J York) Date: 22 Mar 2002 07:33:56 -0800 Subject: mailman fails to deliver messages due to error Message-ID: <1a3ddea5.0203220733.6ffe40a8@posting.google.com> I'm having a problem with Mailman not delivering the vast majority of the messages that get sent to it. It receives the messages and stores them safely in qfiles. Then qrunner attempts to deliver those messages, then dies after a few are sent. >From the log files: $ cat qrunner Mar 22 08:46:03 2002 (11484) Could not acquire qrunner lock Mar 22 08:48:02 2002 (11568) Unlinking orphaned .db file: /home/mailman/qfiles/fbe8be0863231742102ffc6280894a3369d11118.db Mar 22 08:49:01 2002 (11731) Could not acquire qrunner lock $ cat error Mar 22 08:48:02 2002 qrunner(11568): Traceback (most recent call last): Mar 22 08:48:02 2002 qrunner(11568): File "/home/mailman/cron/qrunner", line 282, in ? Mar 22 08:48:02 2002 qrunner(11568): kids = main(lock) Mar 22 08:48:02 2002 qrunner(11568): File "/home/mailman/cron/qrunner", line 202, in main Mar 22 08:48:02 2002 qrunner(11568): os.unlink(root+'.db') Mar 22 08:48:02 2002 qrunner(11568): OSError : [Errno 2] No such file or directory: '/home/mailman/qfiles/fbe8be0863231742102ffc6280894a3369d11118.db' $ Qrunner is set to startup every minute. But I can watch the error log file and process list and watch qrunner die shortly after the above error. Like clockwork. When I check to see if the above file is there, it is not. Any ideas? My specs: Solaris 2.8 Python 2.1.1 (compiled w/ gcc 3.0.1) Mailman 2.0.8 Thanks J York From jcromwell at ciena.com Fri Mar 8 13:26:00 2002 From: jcromwell at ciena.com (Cromwell, Jeremy) Date: Fri, 8 Mar 2002 10:26:00 -0800 Subject: Is current integer for-loop syntax a wart? Message-ID: PEP 276 (Simple Iterator for ints) and PEP 284 (Integer for-loops), among others, are written from the perspective that the current integer for-loop syntax for i in range(10): is a wart. Is this true? That is, where does the Python community stand on this issue? If you will, please start your response by placing your description of the syntax in one of these categories. -Major wart This is painful to type and I would support almost any type of improvement. -Wart I don't like the current syntax and would like to see an improvement, but I could care less. -Wart? What's wrong with it? I guess it could be improved but I never thought about it. -Not a wart This is the most pythonic way to write an integer for loop. I would oppose almost any change. Not to bias the results, but I'd be just as interested to hear from the "Wart?" group as any other. References PEP 276, Simple Iterator for ints http://www.python.org/peps/pep-0276.html PEP 284, Integer for-loops http://www.python.org/peps/pep-0284.html -Jeremy Cromwell From op73418 at mail.telepac.pt Mon Mar 11 07:55:21 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 11 Mar 2002 12:55:21 +0000 Subject: Python on Windows soon forbidden by Micro$oft? References: Message-ID: <9v9p8us7kk8pp7q7l8m1g4gio1sv19ov11@4ax.com> On Mon, 11 Mar 2002 10:20:07 +0000, Eric Brunel wrote: >Hi all, > >Found the following link on comp.lang.tcl. A bit long, but worth reading... > >http://groups.google.com/groups?hl=en&selm=3B40A4A7.6E39BD%40brad-aisa.com&rnum=1 > >Regards, > - eric - It does not surprise me at all, it's in line with Microsoft's general policy up to date. Of Microsoft products in general, the best I have to say is repeat Dr. Samuel Johnson's quip to an author, "Your manuscript is both good and original; but the parts that are good are not original, and the parts that are original are not good." From kragen at pobox.com Tue Mar 19 13:40:52 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 19 Mar 2002 13:40:52 -0500 Subject: Process to process synchronization (unix) References: Message-ID: <83pu20ieob.fsf@panacea.canonical.org> "Gillou" writes: > I have a Zope application and another running process (in python too). > I need to transmit data and signal (hey ! data available, do your job !) in > an asynchronous way from the Zope app (in an external method) to the python > running process (that runs for another user). > The other process waits for the signal, takes given data, does the jobs and > waits further signal (...) > I'm 99.9% newbie in process to process communication. > What packages are helpful for this ? Why don't you use os.popen("otherprogram", "w") from Zope to start the other program, then write to the pipe whenever there is data available? Maybe that's not possible because of the way the other program starts and you have to use named pipes or sockets. But this would be simpler if it is possible. From janez.jere at void.si Sun Mar 10 18:32:00 2002 From: janez.jere at void.si (Janez Jere) Date: Mon, 11 Mar 2002 00:32:00 +0100 Subject: Zope stdin Message-ID: <3C8BECF0.30207@void.si> HHi, could anyone help me port my simple cgi to zope script. Problem which I am unable to solve is reading posted raw data (legacy client posts a xml document to my cgi and expects a result). Among all my attempts the closest solutions are: request.get(BODY) # BODYFILE a and request.stdin.read() # but it is not allowed to access read method. #echo cgi import sys, os length = os.environ['CONTENT_LENGTH'] print 'Content-Type: text/plain' print print sys.stdin.read(int(length)) Thank for help. Janez From maurelius01 at hotmail.com Sat Mar 23 11:39:46 2002 From: maurelius01 at hotmail.com (Marc) Date: Sat, 23 Mar 2002 11:39:46 -0500 Subject: mutlifile inheritance problem simplified References: <9896e047.0203211303.741f695a@posting.google.com> <3C9BAB77.B4E17C65@hotmail.com> <3C9C0B45.E3C51B0C@hotmail.com> Message-ID: <3C9CAFD2.13FE372D@hotmail.com> Aahz wrote: > > In article <3C9C0B45.E3C51B0C at hotmail.com>, > Marc wrote: > >Aahz wrote: > >> In article <3C9BAB77.B4E17C65 at hotmail.com>, > >> Marc wrote: > >>> > >>>I'm using Windows NT, Python 1.5.2, and IDLE 0.5 > >> > >> Try switching to Python 2.1.2 or 2.2; I'm sure that reload() has had > >> some changeds. > > > >OK, I've just tried Python 2.2 and IDLE 0.8. Same problem. > > > >This really seems quite mysterious? I'm surprised that others haven't > >run into this. I'm sure I'm not the first person to use reload, or the > >first to inherit from a class into different files. > > Not many people do use reload(), in my experience. I'm pretty > knowledgeable about Python, I think, and I've been pretty regular on > comp.lang.python for almost three years. It's not interesting enough to > me personally to invest much of my time, I'm afraid. ;-) I still > haven't seen any clear explanation from you for why you need to use > reload() in the first place. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "We should forget about small efficiencies, about 97% of the time. > Premature optimization is the root of all evil." --Knuth I'm wondering whether or not this is a bug, which I would report, or whether I'm doing something incorrectly. I can accept that others don't use reload much, but it seems that identifying bugs in the language is good for the language, or identifying known errors in my usage is good for me. For myself, I use reload all the time. Here's an example. For my current task, I'm analysing large data sets (~.01-30 GB), never doing the same analysis twice. This involves many steps, and a complete analysis takes alot of time about 20 minutes - 50+ hours. Most of this is done using old classes that I've written in different files and many of these inherit from base classes in other files. The goal is to write an analysis script and let it run, but, of course, it rarely works straight away. I run stuff from IDLE. If the analysis bombs, I can catch the exception and pickup where I left off without losing what I've already done: IDLE just waits for me to notice the exception, then using reload, I can modify the classes that caused the problem, even a base class that I wrote written 4 years ago and is ten layers deep in an inheritance tree, or using numbered DLLs I can even modify a C extension on the fly, all without losing anything. Then just rerun, picking up where I left off. This is great, and I don't want to give it up. I can't see a reanable way to restart python every time I have an error. Anyway, I know this hasn't revived your interest in reload. I expect it's use is very task specific. I've found it extremely useful. Marc From djc at object-craft.com.au Fri Mar 8 01:28:45 2002 From: djc at object-craft.com.au (Dave Cole) Date: 08 Mar 2002 17:28:45 +1100 Subject: Web scripting with Python (My 2nd post!) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> <40c3f5da.0203070720.6ca52e4@posting.google.com> <23891c90.0203071034.795308e4@posting.google.com> Message-ID: >>>>> "Paul" == Paul Boddie writes: Paul> Writing a Web application framework is one of those things that Paul> looks easy enough at first - how hard can it be to do a CGI Paul> wrapper after all? The problem is, after experiencing the low Paul> cost of entry with Python, the tasks just get harder and consume Paul> more of your effort than the application you were wanting to Paul> write. I couldn't agree more. While writing the toolkit is fun, it is not until you try to use the toolkit for a real application that you realise what needs to be done. That is when you start losing hair bigtime. Paul> How do you do user sessions properly? How do you authenticate Paul> users? Some frameworks already provide these kinds of facilities Paul> without dictating how your application is going to turn out. The approach I took here was to leave it mostly up the the user. Security is one of those things that you are never going to get right for all users in a toolkit. Paul> Starting out at a low level is exactly the kind of trap that too Paul> many projects fall into, producing a few 0.0.x releases before Paul> disappearing into the void. I suspect that is when the developers realise the scope of the task they have undertaken. I hate to think of the amount of time/money it has cost us to develop our small toolkit. Paul> And that's just desktop applications - the added amusements of Paul> Web framework development include things like security, which Paul> one might think is easy to address, but it's usually far better Paul> to use trusted security techniques than think up schemes of your Paul> own. Amen. Paul> I'll accept that some frameworks have a perspective that can Paul> seem hard to share with the developers, and others are under Paul> fairly major and continuous development, but with all the Paul> existing Web frameworks out there, I'm starting to believe that Paul> we don't really need many more, let alone ones which might never Paul> approach getting finished. I agree. The reason that we developed our toolkit was that we could not find a serious alternative to Zope. We needed something that we could hand over to a customer who would/could not grok Zope. Albatross is the third generation of that toolkit. As long as our company is operating, we will be maintaining and developing the toolkit. Paul> But don't let me stand in your way. ;-) Even if the toolkit never sees the light of day, you will learn a lot while trying to build it. - Dave -- http://www.object-craft.com.au From mwh at python.net Tue Mar 5 04:34:37 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Mar 2002 09:34:37 GMT Subject: Deitel and Deitel Book... References: Message-ID: Dennis Roark writes: > First books in C++ are mostly a dissappointing lot, There may be a reason for this. Cheers, M. -- I also feel it essential to note, [...], that Description Logics, non-Monotonic Logics, Default Logics and Circumscription Logics can all collectively go suck a cow. Thank you. -- http://advogato.org/person/Johnath/diary.html?start=4 From huaiyu at gauss.almadan.ibm.com Fri Mar 1 15:55:37 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 1 Mar 2002 20:55:37 +0000 (UTC) Subject: mult-indexed xrange? Message-ID: The generator facility in 2.2 allows me to do something cool that I always wanted: looping around multiple indices with just one for-statement, as the following code does. Is this available with some built-in functions? Should we suggest that the definition of range and xrange be thus extended? Huaiyu # code example and output def multixrange(N): t = type(N) x = [0]*len(N) while 1: yield t(x) for i in xrange(len(N)-1, -1, -1): if x[i] < N[i]-1: x[i] += 1 break else: x[i] = 0 else: raise StopIteration if __name__ == '__main__': for x in multixrange((2,3,2)): print x for x in multixrange([2,4]): print x """ Outputs: (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (0, 2, 0) (0, 2, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1) (1, 2, 0) (1, 2, 1) [0, 0] [0, 1] [0, 2] [0, 3] [1, 0] [1, 1] [1, 2] [1, 3] """ From usenet at thinkspot.net Mon Mar 11 03:30:03 2002 From: usenet at thinkspot.net (Sheila King) Date: Mon, 11 Mar 2002 00:30:03 -0800 Subject: Python Equivalent of Perl's Safe module? References: Message-ID: On Mon, 11 Mar 2002 00:06:49 -0800, John Beppu wrote in comp.lang.python in article : > > Hello, I was wondering if there was a Python equivalent of Perl's Safe > module. Here is the beginning of the man page for Perl's Safe. > > > NAME > Safe - Compile and execute code in restricted compartments > Perhaps one of these is what you're looking for? http://www.python.org/doc/current/lib/module-Bastion.html http://www.python.org/doc/current/lib/module-rexec.html -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tom at peresys.co.za Fri Mar 1 09:52:09 2002 From: tom at peresys.co.za (Tomasz Stochmal) Date: 1 Mar 2002 06:52:09 -0800 Subject: ADO GetRows() example for newbies Message-ID: #ADO GetRows() example import win32com.client import pprint def main(): ConnectionString = 'Provider=SQLOLEDB.1' \ +';Data Source=127.0.0.1' \ +';Initial Catalog=ZASecurities' \ +';User ID=sa' \ +';Password=' SQL='SELECT TOP 1 * FROM TESTCASE' DBConnection=win32com.client.Dispatch('ADODB.Connection') DBConnection.Open(ConnectionString) try: rs=win32com.client.Dispatch('ADODB.Recordset') rs.Open(SQL,DBConnection) try: # Info Row: Field Name/Type result=[] buf=[] for i in range(rs.Fields.Count): buf.append([rs.Fields.Item(i).Name,rs.Fields.Item(i).Type]) result.append(buf) # Data Rows if not rs.EOF: data=rs.GetRows() assert len(data) > 0 data=[[r[col] for r in data] for col in range(len(data[0]))] result.extend(data) finally: rs.Close() pprint.pprint(result) finally: DBConnection.Close() if __name__ == "__main__": main() # Change ConnectionString & SQL From martin at v.loewis.de Wed Mar 13 12:01:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Mar 2002 18:01:51 +0100 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> <3C8F1D74.10802@mxm.dk> Message-ID: Max M writes: > This could also just be a sign that there is interrest, but the people > using win32all might not be able to publish a build themself? > > Not everybody is as knowledgable as Mark, Even though we work on the > superior Windows platform ;-) That is part of my complaint (or analysis), though: I certainly don't expect that every user of Python or a Python port also is expert for Python's internals. I would hope that a significant user community would grow experts beyond the initial authors. This has happened for Python, and this is also what Eric Raymond reports as the basis for the "publish early, publish often" strategy. *Somebody* needs to get involved, or contribute - else the author gets (rightfully, IMO) the impression that he's left alone. Regards, Martin From ak at silmarill.org Fri Mar 29 13:35:30 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Fri, 29 Mar 2002 18:35:30 GMT Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: In article , cruciatuz wrote: > On Fri, Mar 29, 2002 at 10:20:33AM +0000, Fused wrote: > >> Can anyone think of a program that I could build that would actually >> have use to someone (you?)? I'm trained in Delphi, know some Java and >> rudimentary C, so the programs don't need to be newbie-easy ( I like a >> challenge: the greater the challenge, the faster I'll learn ;-) ). > a programming game like realtimebattle, written entirely in python, > would be very cool. > As far as games go, these would all be nice in python: nethack, fantasy general, subspace, isometric view RPG engine (like fallout's), civ, heroes of might and magic.. Okay, that'll do for now, if you make these I'll think of more :-) Another nice project would be a useful window manager. There's already PLWM in python, but it's very basic. > > have a look at: > > http://www.lysator.liu.se/realtimebattle/ > > ... if you're interested > > > 2 things: > > - other programmers (newbies like me) can learn functional programming > in python while building own bots (movement algo's etc.) > > - it doens't need to be a "war-game", it can also simulate bots in other > situations (it would be great if there would be a map with different > things on it, and the bot has to move around, climb, swim and so on - > but it has to be programmed before _how_ he should do that and which > parts (item-classes) he should use.) > > - every main part of the bot's body should be a python-object in a main > bot object - these objects will be manipulated while the bot is trying > to solve the map. > > - the bot who is the fastest in solving an arena, will be the winner. > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From martin at v.loewis.de Sun Mar 31 05:52:52 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 12:52:52 +0200 Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: <3CA62CD8.6ABD44D0@accessforall.nl> Message-ID: Paul Sidorsky writes: > to the new style. If this is going to be done anyhow, why not at least > force people it to be done right the first time? There are guidelines for language evolution (PEP 5). Those mandate that incompatible changes get a warning period, before outright breaking code. If booleans are introduced in the way the PEP suggests, but would *not* interact with numbers in the way proposed, PEP 5 would be clearly violated. Also, there are strong opinions on both sides: some people actually like booleans to interact with numbers in the way Python does it. So phasing out those interactions would be another PEP, one that cannot complete before Python 2.7 or so. Regards, Martin From jimd at vega.starshine.org Tue Mar 26 02:39:05 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 26 Mar 2002 07:39:05 GMT Subject: starting a python program from within xemacs References: <1017098019.357959@DS9.ai-lab.fh-furtwangen.de> Message-ID: In article <1017098019.357959 at DS9.ai-lab.fh-furtwangen.de>, Marco Herrn wrote: > Hi there, > sorry if this is the wrong newsgroup to ask, but I tried in > comp.emacs.xemacs and nobody could help me, probably because too few > people there code in python :-) > I develop a program that uses the curses library in xemacs. But for > testing my program I have to save it in xemacs, switch to a terminal and > call python myprog.py. Because I use curses, a C-c C-c doesn't work > because the xemacs output window isn't capable of using curses. > Is there a way to execute the content of my current xemacs buffer in a > terminal/x-terminal? > Bye > Marco > -- > Marco Herrn herrn at gmx.net More to the point, is there a way to direct the Python curses module to use an alternative terminal/device? This would be handy for other situations as well (for example when running interactively via idle or from an xterm or a Linux/FreeBSD virtual console). It would be nice to have the interactive prompt and output decoupled from the "user's" I/O --- especially when playing with the curses module. I suppose I could try reading the Python curses sources and looking for the place where it sets up its terminal context. We might be able to add a hook therein, a check for a magic environment variable like PYTHONTERMINAL or some such. It just hasn't hurt enough for me to chase down that rat hole. From grante at visi.com Fri Mar 15 12:32:59 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Mar 2002 17:32:59 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: In article , Rich Cook wrote: > At 10:57 AM -0600 3/15/02, Skip Montanaro wrote: >> Rich> I don't really need select to block. I just want it to be >> Rich> accurate. If it returns a file object in the list of things which >> Rich> are available, why should then readline() block on it? >> >>Remember that select() is lower level than readline(). As >>someone else pointed out, select() may return because there is >>data available, but it makes no promises about what that data >>is. Calling readline() may then hang waiting for other >>conditions (presence of a newline in the input, for example). > > So do I have to read the data byte by byte using read(1) and > examine each character to avoid blocking? Is there any way to > find out how much data is actually waiting for me in the file > object so I can read it in bigger increments, or must I call > select then read(1) for every byte? You don't have to read it 1 byte at a time. Just call f.read(1024) and it will give you however many bytes are available, up to the max of 1024. You can use a max different than 1024 if you want. > The reason I'm concerned is that I have two file objects (childerr > and fromchild, actually) and I want to know right away if one has > data. So I can't just call read on either one, because I may get > blocked on one waiting for data from the other. But I'd like to > avoid the char-by-char read if possible. -- Grant Edwards grante Yow! .. this must be what at it's like to be a COLLEGE visi.com GRADUATE!! From donn at drizzle.com Sat Mar 16 00:45:57 2002 From: donn at drizzle.com (Donn Cave) Date: Sat, 16 Mar 2002 05:45:57 -0000 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <1016173476.645562@yasure> <2b57f654.0203151021.7f709e4c@posting.google.com> <2b57f654.0203151908.33413282@posting.google.com> Message-ID: <1016257555.708754@yasure> Quoth wealthychef at mac.com (wealthychef): ... | Here's what I mean. If I do a select.select() and it says, "there's | data," then I do a readline() on the file object, but select() was | talking about 2 lines of data, I will lose a line of data, because my | next select() will say "nothing left." Is that right? Because the | call to readline() somehow scarfs up all the data available and saves | it for my next call to readline()? If that's so, then readline() | sucks, because I should have a way to query it to avoid blocking. | Obviously select() and readline() just don't play ball together very | well... That's right. I hesitate to say that you would "lose" input lines that way, but I suppose something you don't know you have is as good as lost. Indeed, there should be a way to query the C stdio buffer. |> The point with file descriptor is to use system I/O functions on the |> device, and avoid buffered C I/O. Basically because select is a |> system I/O function. If there were a C analogue to select, then you |> could use it with C buffered file objects, but there is no such thing. |> |> When select tells you "this thing is ready to read", it means the |> device is ready for a system level read(), as in os.read(fd, bufsize). |> So do that, and you'll get what select was telling you about. It's |> really simple. The rules are the same, if you get an empty string |> it's at "end of file" (the pipe closed.) | | I just want to be sure I understand this. You're saying that | os.read() somehow get what select.select() was talking about, but that | f.fromchild.readline() will read less than that? It might return less than that, yes. Don't say "somehow" - the reasons for this are explained above with crystalline clarity. The system functions like select() and os.read() are as simple as they could be. The C stdio functions that Python's file object uses complicate things by adding a buffer so they can do things like readline() with reasonable efficiency. |> I have lost track of what kind of devices we're actually talking about - |> I'm seeing the word "socket", but then what looks like popen2.Popen3. |> Note that in Python, sockets are are normally socket objects, with recv() |> methods etc., but these are unbuffered and recv() is like os.read(). |> Pipes (as created by Popen3) are either integer file descriptors or |> file objects, there isn't any special system level pipe object. |> As long as you're on UNIX, there's a certain purity of abstraction here |> that you can exploit if you want it just to simplify matters - you can |> get the file descriptor with s.fileno(), and you can use os.read() with |> that - or you can use sock.recv() if you prefer. | | The objects from my original post are popen2.Popen3 objects, as you | noticed. The Python lib manual says that os.read() should not be used | with file objects, even though I can get a file descriptor from them | with fileno(). Will it work? Sure. Look at Popen3 (it's implemented in Python.) It's working with file descriptors to start with, then creates file objects from them to return to the caller. You're just getting back the file descriptors. Don't use them alternately as file objects and then do system I/O on the file descriptors, that would be foolish for reasons that you can easily appreciate. I believe you don't have to worry about the file object going out of scope and getting closed while you're ignoring it. That would close your file descriptor too, but it won't happen because the popen2 module holds a reference to the Popen3 instance. If you ever have that problem, you can dup() a new file descriptor that will survive the file object. Donn Cave, donn at u.washington.edu From theller at python.net Mon Mar 25 13:33:19 2002 From: theller at python.net (Thomas Heller) Date: Mon, 25 Mar 2002 19:33:19 +0100 Subject: PEP262 - database of installed packages References: Message-ID: "Duncan Booth" wrote in message news:Xns91DCA870CFCCDduncanrcpcouk at 127.0.0.1... > "Thomas Heller" wrote in news:a7nhv1$mqa0r$1 at ID- > 59885.news.dfncis.de: > > > All true. On the other hand, Python has no possibility to display > > or change the owner and access control lists (except if you do some > > hardcore win32 programming). > > It is messy, but not hardcore: > > Python to display the owner of a file: > os.system("dir /q " + filename) > Likewise, to display or change the access control list > os.system("cacls "+arguments) > I don't know of an equivalent to change the owner of a file. I doubt we want to have code like this in the PEP 262 implementation. Here's what distutils does when copying a file (in file_util.py): def copy_file(src, dst, preserve_mode=1, preserve_times=1, ...): """ [...] If 'preserve_mode' is true (the default), the file's mode (type and permission bits, or whatever is analogous on the current platform) is copied. If 'preserve_times' is true (the default), the last-modified and last-access times are copied as well. [...] """ .... st = os.stat(src) # According to David Ascher , utime() should be done # before chmod() (at least under NT). if preserve_times: os.utime(dst, (st[ST_ATIME], st[ST_MTIME])) if preserve_mode: os.chmod(dst, S_IMODE(st[ST_MODE])) So, for PEP 262, wouldn't it be sufficient to use "" as user (since we don't care), and the value of S_IMODE(st[ST_MODE]) as permission? Thomas From ajs at ix.netcom.com Wed Mar 6 21:22:47 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Wed, 6 Mar 2002 21:22:47 -0500 Subject: PEP 284, Integer for-loops Message-ID: <001101c1c57e$fbf6ef20$0334fea9@carol> >And please avoid the ad-hominems ("too lazy to learn the >language"), it doesn't contribute to rational debate. And I would beg you to amend your PEP to remove reference to novice users. This has become the Mom and Apple Pie of PEP writers. And I have yet to see it in the context of the most straight forward meaning - to remove barriers to learning to program for people motivated to learn to program. Your evidence is derived from a specialized setting with a specialized purpose - and not in a setting of teaching Python programming tasks to novices. Your recent post makes that clear. The PEP does not, and in fact seems to imply otherwise. At least at this point I think that the most important thing that could be done on behalf of novice programmers is for the language to settle in for some period as to all it basic syntactical structures. Reference books, tutorials, and sample code are becoming too quickly obsoleted and there is too much a sense of chasing a moving target. I would submit, no change to the language I have seen proposed in a PEP does *anything* significant *for* novices - and only adds to general static. I don't know how to submit a PEP proposing *no* changes be made at this time to basic constructs - the PEP I think that would best represent novice interests. I can though ask PEP writers to be careful and thoughtful in throwing in any reference to the interests of novices, without at least explaining the basis - in some particulars - of the claim. On the other hand, novices want to invest in learning a powerful, versatile real world language - and are like the rest of the community, (reluctantly) willing to live with any changes made to the language necessary to more fully achieve that goal. So fight it out, please, on that basis alone. Please. Art From gh_pythonlist at gmx.de Sat Mar 2 22:10:21 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sun, 3 Mar 2002 04:10:21 +0100 Subject: mx odbc result strings with special characters? In-Reply-To: <24c39b2c.0203021850.7679418c@posting.google.com> References: <24c39b2c.0203021850.7679418c@posting.google.com> Message-ID: <20020303031021.GA5943@lilith.hqd-internal> Le 02/03/02 ? 18:50, Alexander Jerusalem ?crivit: > Hi, > > I'm using the mxODBC package to query a database that contains german > umlauts. The result strings conatain hex codes instead of umlauts. > I've played around with encoding and stringformat values but to no > avail. Any hints? Yes. Post an example from an interactive Python session. It's not unlikely that everything is just fine but your terminal doesn't show the umlauts. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 1.5 ?C Wind: 0.9 m/s From gerhard at bigfoot.de Wed Mar 20 05:38:15 2002 From: gerhard at bigfoot.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 20 Mar 2002 11:38:15 +0100 Subject: Recommended Books/Resources for Python References: Message-ID: <3C986697.8020500@bigfoot.de> TegSkywalker wrote: > Hey all. Sorry if this sounds like a stupid question (new and want to learn > Python) but do any of you have any suggested books or readings on how to > learn Phython? I saw an O'Reilly book over at Amazon.com > (http://www.amazon.com/exec/obidos/ASIN/1565924649) and wasn't 100% sure if > this was a good source or not. I can't recommend anything myself, but here's a great listing of Python-related books: http://www.amk.ca/bookstore/ > Here is another question. I see that Python is a multisource language > spanning different OSes like Windows, Linux, and Mactintosh like how Java > aims to be. If I were going to program something like an interactive CD and > wanted to give it to people to check out, would they have to have a Python > interpreter installed on their machine or will it run like a normal Windows > .exe file for example? One way or the other, Python applications need an interpreter. There are, however, ways to bundle the interpreter and the libraries used by a script into one self-contained executable (or an executable and a few DLLs). On Windows: Gordon McMillan's installer or py2exe everywhere: freeze (in the Tools directory) Gerhard From jkraska at san.rr.com Sun Mar 10 13:18:43 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 10 Mar 2002 18:18:43 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> Message-ID: <1a9n8us1629mrvei40hdkuuerc1j6p318m@4ax.com> >Hmm, I don't really see the difference in practice between >statically linking and installing a bunch of "private" DLLs >that are only used by my app. In one case they're all in one >file, in the other case they're in a bunch of files that have >to be linked at run-time. In both cases none of the stuff is >being shared with anybody else, so it's not like putting things >in DLLs is saving any system resources -- though it perhaps >make the packaging simpler. The case for the DLL is more obvious when what it is your distributing is a family of applications which live together. There may also be load time differences between an application that is statically linked and one that is dynamically linked. I seem to recall in my Unix days that using .so's dramatically quickened load times. C// From peter at engcorp.com Fri Mar 1 21:20:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Mar 2002 21:20:39 -0500 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7F6765.94A82394@engcorp.com> Message-ID: <3C8036F7.A0DB600E@engcorp.com> Robin Becker wrote: > > >I'm pretty sure the last time I checked the PROGRA~1 convention still > >worked on WinNT. > > > I'm sure it does and I guess that Program Files will always match as > it's often the first. On the other hand working with a path name > obtained from an execution path there's no guarantee I can always do the > correct conversion by assuming ~1, some end up as ~2 etc. > > Is there a proper way to get the 8.3 name? As Thomas showed, or more concisely with win32api.GetShortPathName(). But if this is not an application for distribution, you can definitely be 99.99% safe relying on progra~1 for that specific file name, since "program files" will be the first directory created with that pattern on almost any WinNT system. I'm just keeping Python pragmatism in mind: if I don't _really_ need to fix it, I wouldn't spend any more time on it, ugly though this solution is. -Peter From mt_horeb at yahoo.com Thu Mar 28 20:29:38 2002 From: mt_horeb at yahoo.com (Sloth) Date: 28 Mar 2002 17:29:38 -0800 Subject: Standalone CGI Server - Question for Group Message-ID: <67abb823.0203281729.3b1b4db7@posting.google.com> I've been working on finding a way of getting a CGI server, written in Python, to work on a WinME laptop. I've read through many posts describing problems with the CGIHTTPServer module, and I've experienced them as well. However, since I would love to be able to use a Python module to serve basic HTTP and CGI, I'd like to know if anyone has had luck creating such a beast and/or if there are any tips to get CGIHTTPServer to function. I've looked at Apache, Xitami, Zope, Medusa, et. al and think they are wonderful applications. On the other hand, they are overkill for what I want to be able to do - have Python start a CGI server, serve a page, get form data, get data from a database, and display dynamic content. I don't need anything industrial strength, just something that can handle a single user. Any thoughts? I sincerely appreciate everyone's help! Jeremy. From gerritvd at decillion.net Mon Mar 25 05:39:33 2002 From: gerritvd at decillion.net (Gerrit van Dyk) Date: Mon, 25 Mar 2002 12:39:33 +0200 Subject: win32Extensions,win32com Message-ID: <3C9EFE65.7000300@decillion.net> Hi all, Is there a newsgroup or mailing list for the win32com extensions from Mark Hammond or should I post related questions on this list? Regards Gerrit van Dyk From eric.brunel at pragmadev.com Wed Mar 20 11:30:33 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 20 Mar 2002 16:30:33 +0000 Subject: tkinter menuitem question References: Message-ID: Ken Guest wrote: > ok, I might be way off here but is there a way with a collection of > Tkinter menuitems that all have their callbacks set to be the one > function to determine which menuitem was clicked on? AFAIK, you cant't. But a simple workaround is to use a lambda function (example is in pure Tkinter): ---------------------------------- from Tkinter import * root = Tk() def menuHit(menuName): print menuName menubar = Menu(root) m = Menu(menubar) menubar.add_cascade(label='Menu', menu=m) m.add_command(label="m1", command=lambda: menuHit("m1")) m.add_command(label="m2", command=lambda: menuHit("m2")) root['menu'] = menubar root.mainloop() ---------------------------------- HTH - eric - From tim.one at comcast.net Wed Mar 27 02:27:54 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 27 Mar 2002 02:27:54 -0500 Subject: PyThreadState_DeleteCurrent() In-Reply-To: <20020327042600.GD10449@isis.gerrietts.net> Message-ID: [Geoff Gerrietts] > ... > But ... what's the difference? When is PyThreadState_DeleteCurrent() > the appropriate call, and when PyThreadState_Delete()? I've looked, > and the docs haven't been updated to reflect this API change. PyThreadState_Delete(PyThreadState *tstate) can only be called when the passed-in tstate is not the current thread state. It doesn't matter whether you hold the GIL when it's called. PyThreadState_DeleteCurrent() takes no argument, and deletes the current thread state. You must hold the GIL while calling it, and the thread calling it loses its tstate, and loses the GIL, and must never call anything in the Python C API ever again (unless it acquires another tstate first, but that's an intended use case). As that description hints , it was introduced to plug a Python shutdown race. A detailed explanation of "the bug" can be found in the comments here: http://www.python.org/sf/225673 From tim-dated-1016494087.c376d7 at catseye.net Mon Mar 11 18:28:06 2002 From: tim-dated-1016494087.c376d7 at catseye.net (Tim Legant) Date: 11 Mar 2002 17:28:06 -0600 Subject: PEP 284, Integer for-loops In-Reply-To: References: Message-ID: <86adteadmh.fsf@skitty.catseye.net> James_Althoff at i2.com writes: > [Tim Legant] > > So either Jason and I are significantly better than you and your > > team at expressing ourselves naturally in Python or it's > > the need to interface with Java that's forcing you to use integer > > indices all the time. I'm betting big money on the latter. > > I'm happy to believe you all are excellent programmers versed in Pythonic > ways. And I'm always happy to learn something new. So feel free to help > me on this one. Hmmm. Did you by any chance miss my ? My intent was to provide a supporting data point to your hypothesis that the real issue is interfacing with Java. With Python as it exists today, I am unaware of any good solutions. [snip description of nasty problem...] > Perhaps you could give some ideas on approaches that would be more > "Pythonic"? Well, like I was trying to convey in my original message, I think you're stuck. Tim Peters actually came up with something a little better, but I still think it's sad you have to write all kinds of wrappers just to get a reasonable looping syntax. FWIW, I completely agree that [x]range is awkward and inelegant (and necessary) in these sorts of cases. I'm also in full agreement with better language support for more complex loops. I haven't been really happy with either of the PEPs, but I sure understand the problem they're trying to address. Tim From cfelling at iae.nl Sun Mar 3 21:30:01 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 4 Mar 2002 03:30:01 +0100 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> Message-ID: Brian wrote: > Regarding: > z = [MyClass() for i in xrange(y)] > Is there a way to do this without the use of i? ofcourse, if you incist:) >>> class MyClass: pass ... >>> z = map(lambda x: C(), range(3)) -- groetjes, carel From James_Althoff at i2.com Tue Mar 5 15:17:28 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 12:17:28 -0800 Subject: PEP 276 -- What else could iter(5) mean? Message-ID: [Huaiyu] > I do not think that there is any conceptual difficulty to > explain that > for i in n ==> for i in iter(n) > iter(3) ==> xrange(3) > > which is all that is in the proposal. This is elegant and > easily explainable even to a newbie. I actually like this > quite a lot. And I, in turn, am quite fond of this part of your message . > However, I still think the potential for unintended effects > (bugs) is too big when a one-element sequence behaves substantially > different from the element itself. Imagine if Python had a character > type and that > "abc" == ['a', 'b', 'c'] == 'd' != "d" > > Even though it can be explained, what utter confusion it would > result in actual use! Sorry, I'm a little confused by this one. Example: "for x in ['spam']" is not the same as "for x in 'spam'". Isn't that a case "when a one-element sequence behaves substantially different from the element itself" in this context? > Here's another example of a similar nature. In Matlab there is a > fuction sum(x) that would return sum of elements of x, if x is a > (row or column) vector, or a row vector of columnwise sums of x, > if x is a matrix. This is very handy when used in isolation, but > a pain in programs, because the behavior on (1xm) matrix has a > different semantics. Suppose x is a (5x4) matrix. Then (using > Python syntax instead of Matlab's) > sum(a[0:n:, :]) > would give a (nx4) matrix for n in 5, 4, 3, 2, but for n==1, > it gives a scalar which is the sum of x as a row vector. Not really following that example either. Sorry. Jim From jeff at ccvcorp.com Mon Mar 4 14:24:53 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 04 Mar 2002 11:24:53 -0800 Subject: Status of PEP's? References: Message-ID: <3C83CA04.6142D79E@ccvcorp.com> James_Althoff at i2.com wrote: > I was thinking in a more general sense: I would like to create an iterator > with start, end, and step values and pass it into a function without first > actualizing it as a list (like one would have to do using for+relational in > conjunction with list comp.s). And use the same construct in for-loops, > list comp.s, etc. (For those just tuning in: I realize that I can create a > class for this -- actually, I already have. I'm refering to proposals for > new idioms in Python for iterating intervals of integers.) Um... isn't this exactly what xrange() does? Or am I missing something again? Jeff Shannon Technician/Programmer Credit International From ws at mystrobl.de Mon Mar 25 20:33:08 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Tue, 26 Mar 2002 02:33:08 +0100 Subject: PEP262 - database of installed packages References: Message-ID: Mon, 25 Mar 2002 17:06:45 +0100, "Thomas Heller" : >All true. On the other hand, Python has no possibility to display >or change the owner and access control lists (except if you do some >hardcore win32 programming). I would't call the following three-liner "hardcore win32 programming". :-) C:\>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from win32security import * >>> >>> def owner(filename): ... ownerdescriptor=GetFileSecurity(filename,OWNER_SECURITY_INFORMATION) ... owner=ownerdescriptor.GetSecurityDescriptorOwner() ... ownername=LookupAccountSid(None,owner) ... return ownername[0] ... >>> print owner("c:\\boot.ini") Administratoren >>> -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From peter at engcorp.com Sun Mar 31 01:34:20 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 01:34:20 -0500 Subject: Most important extensions? References: Message-ID: <3CA6ADEC.80859964@engcorp.com> Aahz wrote: > > I'm teaching Python for [Perl] Programmers at OSCON this July. I've > already decided to mention mxODBC, NumPy, and PIL, plus PythonPoint (aka > ReportLab) gets a mention on my title page. I'd like this group to vote > on the most important extensions for me to add to this list. Please vote > for no more than three. I take it PyXml and PyUnit no longer qualify as "extensions"? (Not that the idea of unit testing would necessarily appeal to Perl programmers anyway.) -Peter From dortmann at lsil.com Sun Mar 10 21:11:49 2002 From: dortmann at lsil.com (Daniel Ortmann) Date: 10 Mar 2002 20:11:49 -0600 Subject: python name spaces Message-ID: Hello, As a Perl user who has switched to Python for all of the standard reasons ... I must admit I am frustrated by Python's seeming lack of powerful name space support. For example, in Perl I can do something like this, our $b = "...b"; { my $a = "...a"; our $f = sub { print $a, "\n" }; our $g = sub { $a = "foo" } } $f->() $g->() # prints ...a, followed by foo. # the "$a" variable is ONLY seen by the unnamed $f and $g # subroutines. Arbitrarily creating variables and subroutines with different scopes. (The actual example seems silly, but really isn't.) 1) Can such name space manipulation be done in Python? 2) What about the creation of substantial subroutine closures? Thanks in advance for any help! -- Daniel Ortmann, LSI Logic 3425 40th Av NW, Suite 200, Rochester, MN 55901 dortmann at lsil.com / 507.529.3887 (w) / 535.3887 (int) ortmann at isl.net / 507.288.7732 (h) From op73418 at mail.telepac.pt Wed Mar 13 17:23:02 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 13 Mar 2002 22:23:02 +0000 Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: On Wed, 13 Mar 2002 13:01:13 -0800, James_Althoff at i2.com wrote: > >[ruud de rooij[ >| perhaps lists should support .keys() and .items() for those operations >| (analogous to dictionaries). > >[Clark C . Evans] >| Very nice idea. This is PEP worthy. It is nice beacuse it >| does not introduce anything new; a list can easily be viewed >| as a mapping having a positive integer domain. This is simple, >| consistent, and quite elegant. > >I would like to see: > .keys() > .items() > .iterkeys() > .iteritems() > >jim > The same idea should be extended to any sequence, actually. Gon?alo Rodrigues. From brueckd at tbye.com Tue Mar 26 12:27:24 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 26 Mar 2002 09:27:24 -0800 (PST) Subject: Python vs. C/C++/Java: quantitative data ? In-Reply-To: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> Message-ID: On Tue, 26 Mar 2002, Eduard Smirnov wrote: > I?m writing a diploma paper on the difference between scripting (e.g. in > Python or Tcl) and system programming (e.g. in C, C++ or Java), and one of As a side note, what definition of "system programming" would include Java but not Python? I know this isn't the intent of your paper, but one of the reasons Python is so flexible is that you can use it as a scripting language in the classical sense as well as a general purpose language like Java. -Dave From mwh at python.net Thu Mar 21 08:20:52 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Mar 2002 13:20:52 GMT Subject: Attachments to the list/group - OK? (Was Re: Popular style document?) References: <1016641355.370859@cswreg.cos.agilent.com> <20020320170740.GH18847@andy.tynant.ftech.net> Message-ID: Andy Gimblett writes: > I've just noticed that most people seem to embed their code directly > into their messages. Is attaching .py files (or any other > non-binaries) frowned upon around here? Some sites reject messages to non-binary groups with attachments. Cheers, M. -- I don't remember any dirty green trousers. -- Ian Jackson, ucam.chat From martin at v.loewis.de Fri Mar 1 18:54:36 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Mar 2002 00:54:36 +0100 Subject: Older Python bug entries on SourceForge References: Message-ID: David Bolen writes: > I was trying to look up an old bug entry on SourceForge (based on a > bug number from some CVS log comments) and can't seem to pull it up. > Does anyone know if SourceForge expires closed bugs after some time > duration or something? Is there any archive available to view old > bugs? Normally, they will be kept forever. However, when SF updated the software to generalize trackers (i.e. making the bug tracker an instance of a general feature), they had to renumber all existing bugs. So if you have a bug number below 300000, SF will have renumbered the bug by now. They used to have a backwards-compatible URL in place, redirecting to the new report, but they may have disabled that by now. Regards, Martin From tim.one at comcast.net Sat Mar 16 20:40:08 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 16 Mar 2002 20:40:08 -0500 Subject: Enhanced information from common exceptions In-Reply-To: Message-ID: [John Machin] > An example: > > >>> alist = [4,3,2,1] > >>> alist[42] > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list index out of range > >>> > > Suppose this was actually in a script somewhere. IMO, it would be much > more useful for Python developers of all levels were the message to be > something like: > > IndexError: list index 42 not in range(4) > > Often this extra info would lead to problem recognition & resolution > without the need for an extra step (print statement or debugger). A difficulty with this kind of thing is that producing exception info doesn't come for free. Before 2.2, raising IndexError was the only way to terminate a "for" loop via normal exhaustion, and the list indexing code has no idea *why* it's being called. If it produced more info on an out-of-range index, it would slow down every normal loop by the time it took to construct a nice exception message doomed to be thrown away unlooked-at. Note that the integers in your ideal message have to go through binary -> decimal string conversion, and lots of dynamic string fiddling to paste all the msg pieces together. The cycles add up fast. > Perhaps if people cared to nominate their "favourite" high-frequency- > low-information exception message(s), together with suggested changes, > we could put together a nanoPEP on this topic -- or simply just propose > a few patches. We're *usually* happy to apply such patches, but get more cautious over time. Last year Jim Fulton and I traced a major slowdown in Zope to a "nice msg" patch that spent lots of time formatting exception info in a context where Zope routinely provoked that exception in a try/except that ignored the exception. So these things can be trickier to get right than you may think. A good approach to IndexError would be to create an "exception object" at the C level that merely stored the offending index and max size, as C longs, and didn't produce a string until and unless it was actually needed for display. Unfortunately, that raises the amount of knowledge needed to write such a patch. From donn at u.washington.edu Fri Mar 8 15:09:26 2002 From: donn at u.washington.edu (Donn Cave) Date: 8 Mar 2002 20:09:26 GMT Subject: why is python slow? References: Message-ID: Quoth Skip Montanaro : | | Donn> ... I wonder if all of Python's performance problems are really so | Donn> deep. A few weeks ago someone posted some performance | Donn> measurements and, among other things, noted that version 2.2 took | Donn> twice as long just to start up. Did that appalling statistic | Donn> attract any investigation into the cause, ... | | I believe the bulk of the effort in the 2.x series up to this point has | focused on functionality ahead of performance. I'm sure there are things | that can be done. Why not file a bug report, investigate and solve the | problem, then grab some of that fame and fortune I alluded in my post | seeking new developers yesterday? (I'm not picking on Donn, he just happens | to be the one who raised this issue and gave me the nice segue.) I haven't even downloaded 2.2, because that's how I see it too - that Python development has lately focused on functionality, given a definition of functionality that doesn't include performance. In other words, 2.2 is a toy release for people who want to play with language features. There's another segue in here back to another of your posts from yesterday, but I'll leave that alone. | The group of people who actively beat on the code is still fairly small. I | count 38 people currently with checkin privileges. Of those, I count six | whose SF usernames I don't even recognize. There are probably another five | to ten who don't regularly contribute to either checkins or python-dev | discussions. That means the effective pool of developers is really quite | small. That, in turn, means we need more eyeballs. You don't need checkin | privileges to tackle an open bug or investigate a problem and report its | cause (a proposed solution would be helpful, but it might go a long ways | towards fixing a problem if you can narrow down the cause a bit). | | Donn> I believe I recall something similar in 2.0, due to a mistake in | Donn> site.py that was discovered during the beta releases. Not a hard | Donn> problem, just one that wouldn't be noticed until someone wondered | Donn> why performance went downhill so fast. We can wave our hands and | Donn> say performance is a tough problem, but it would be more | Donn> convincing if it looked like it was getting the most minimal | Donn> attention. | | Agreed. When can we expect that patch? ;-) Don't hold your breath. I might be up for fixing problems in 2.1.1, but it looks to me like 2.1 doesn't have this particular problem (anyway, it starts up about as fast as 2.0 for me.) Donn Cave, donn at u.washington.edu From gh_pythonlist at gmx.de Wed Mar 6 14:52:42 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 6 Mar 2002 20:52:42 +0100 Subject: fork and thread and signal... oooooops In-Reply-To: References: <87550ef1.0203050846.2166835e@posting.google.com> Message-ID: <20020306195241.GB2259@lilith.hqd-internal> Le 06/03/02 ? 23:41, Jonathan Gardner ?crivit: > [...] > Your init.d script will be written in sh, not python. It would be a > horrible idea to write an init.d script in python. I can't see why writing an init script in Python would be a bad idea. Care to explain? Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 9.2 ?C Wind: 4.6 m/s From david.abrahams at rcn.com Fri Mar 29 17:59:14 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Fri, 29 Mar 2002 17:59:14 -0500 Subject: [Python-Dev] [development doc updates] References: <20020329224851.02DAD18EAD1@grendel.zope.com> Message-ID: <0ffe01c1d775$c84ba270$0202a8c0@boostconsulting.com> I'll see what I can do. It would help to have some guidance as to: * What needs to be done * What format(s) would be appropriate (patches to TeX source, plain text...) * What approach to take (e.g. "just document what the existing Python source does", or "ask Guido what the intended functionality is and transcribe what he says") * ...etc. (I'm sure you can think of more). -Dave ----- Original Message ----- From: "Fred L. Drake" To: ; ; Sent: Friday, March 29, 2002 5:48 PM Subject: [Python-Dev] [development doc updates] > The development version of the documentation has been updated: > > http://python.sourceforge.net/devel-docs/ > > Started to update the Extending & Embedding manual with information on the > new support for types. > > There's still a long way to go -- contributions welcome! > > > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev From mnations at airmail.net Thu Mar 14 17:07:55 2002 From: mnations at airmail.net (Marc) Date: 14 Mar 2002 14:07:55 -0800 Subject: Threading/TkInter problems with Buttons. Message-ID: <4378fa6f.0203141407.9b20050@posting.google.com> I was trying to start a thread from a button to find that it would not work. The problem was that every time I started the application, the thread would automatically kick off: self.Go["command"] = self.thread1.start() I eventually put an extra step in the process and had the Go command call a function, which then called the thread. This worked: self.thread1 = Thread(target = self.cb) ... def go_thread(self): self.thread1.start() def cb(self): while self.ok: printAll( self.ipaddr.get(), self.var.get() ) ... self.Go["command"] = self.go_thread Why does it not work when you hook it up to the button, and is there a way around this problem. Thanks, Marc From joonas at olen.to Mon Mar 25 03:18:52 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Mon, 25 Mar 2002 10:18:52 +0200 Subject: hang in urllib.read()? References: Message-ID: <3C9EDD6C.D4A8A22A@olen.to> Nick Arnett wrote: > > The (presumably) infinite loop that I thought was in sgmllib, about which I > posted earlier, actually seems to be when I call read() on an urllib.urlopen > object. It's terribly non-reproducible, though -- I'm retrieving lots of > pages and sometimes it'll go for dozens and dozens, no problem. Other time > it hangs after just a few. And it won't do it on the same page twice, as > far as I can see. > > I've been unable to find anything like this searching... sound familiar to > anyone, or any suggestions for nailing it down, short of gruesome stepping > through with a debugger, hoping I can catch one...? > > This is on Win2000 with Python 2.2. Haven't tried on other platforms yet. Your problem is propably the quite long timeout of urlopen. Search Google Groups for "urllib timeout" or take a look at http://www.timo-tasi.org/python/timeoutsocket.py From maxm at mxm.dk Wed Mar 6 17:36:55 2002 From: maxm at mxm.dk (Max M) Date: Wed, 06 Mar 2002 22:36:55 +0000 Subject: Web scripting with Python (1st post here, also :-) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: <3C869A07.1030501@mxm.dk> A.M. Kuchling wrote: > Do you want to *write* a Weblog-like system, or just *use* one? If you > just want to use one, then Squishdot is the only alternative in Python > that I'm aware of, and it requires Zope. Then I would like to add that I have just installed Plone. A weblog built on top of Zope's Content Management Framework. It has some rough edges but seems rather complete, and nearing a 1.0 version "Real Soon Now TM" http://plone.org regards Max M From syver-en+usenet at online.no Wed Mar 13 20:07:30 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 14 Mar 2002 01:07:30 GMT Subject: redirecting stdin with Python scripts under win2k (solution) Message-ID: It seems that I've finally found an elegant way to do #! functionality on win2k and upwards: instead of #! ... put: @python -x "%~f0" %* & goto :EOF in the first line of your python script file. Call the file *scriptname*.bat If this file is located in your path, you should be to call it from anywhere by writing on the commandline: *scriptname* or: *scriptname*.bat Redirection of iostreams and piping between programs should work as expected, and not fail as it does when using .py files on the commandline. Notes: for emacs users put this in the bottom of your scriptfile. # Local Variables: *** # mode:python *** # End: *** Explanation of commandline: @python -x "%~f0" %* (run python) (skip first line of sourcetext) from fully qualified name of the file itself) & goto :EOF command separator jump to end of file This commanline uses the command extensions that are provided in win2000 so it won't work on win9x family of win32 operating systems. I don't think they work in NT 4 either but I am not sure. -- Vennlig hilsen Syver Enstad From James_Althoff at i2.com Tue Mar 5 15:47:26 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 12:47:26 -0800 Subject: Status of PEP's? Message-ID: [Greg Ewing] > It's been suggested that this proposal doesn't ask > us to think of integers as being sequences, only as > having sequences implicitly associated with them. Going beyond suggesting, I hereby *command* you not to think of integers as being sequences . > But I don't agree. While it's certainly possible > to give any object an __iter__ method that does > anything you want, it doesn't mean you should! Right. Unless it's useful and practical to do so (exclamation point right back at ya ). > To me, the __iter__ protocol is intended to be used > when an object can reasonably be thought of as a > sequence. That's actually *being* a sequence, not just > "associated" with a sequence in some way. I think that view of iterators is overly restrictive. An example is dict. I don't have to think that a dict object *is* a sequence to be content with it being a valid arg to iter(). For me, it's fine to write for x in mydict: print x and think "this works because there is a useful and practical sequence *associated* with mydict (namely, a sequence of the keys in mydict)". And keep on writing code . Jim From jbell at iinet.net.au Wed Mar 27 03:20:03 2002 From: jbell at iinet.net.au (John Bell) Date: Wed, 27 Mar 2002 16:20:03 +0800 Subject: Symbolic imports and manipulation of the namespace? References: Message-ID: <3CA180B3.9000909@iinet.net.au> I should have pointed out that if it is indeed a traditional config file then it might be smarter to parse it. In this case why not look at the ConfigParser module. It parses files written in Microsoft .INI format and is thus comprehensible to a reasonable subset of end users. John VanL wrote: > Hello, > > I was recently solving a problem which required that the config file > (just a python file) lie outside of the pythonpath. Is it possible to > do symbolic importation of a module? > > For example, I had: > > # cfgpath is passed in on the command line > cfgpath = os.path.basename(cfgpath) > sys.path.insert (0, cfgpath) > import sc_cfg #Hardcoded config module name! > > > How do you do this: > > # cfgpath is passed in on the command line > cfgpath, cfgfile = os.path.split(cfgpath) > sys.path.insert (0, cfgpath) > import cfgfile #Hardcoded config module name! > > So that any file name (ending with .py, of course, but that's another > matter) could be the configfile? > I tried the above, but I got an ImportError (no module named cfgfile) > > Thanks, > > Van > > From buzzard at urubu.freeserve.co.uk Fri Mar 29 08:44:46 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 29 Mar 2002 13:44:46 -0000 Subject: Boa v0.1.0-alpha + unrelated question Message-ID: I have just installed the above on a Win98 and a Win2k box (ActiveState Python 2.1, wxPython-2.3.2.1). After some very slight modification an existing Boa App is running fine. The only problem is that I cannot open up the associated modules directly from the Editor window. i.e. AttributeError: 'None' object has no attribute 'connection' Also 'type' for each module is 'unknown', and right clicking + 'Make module main module' has no apparent effect. Anyone any idea, or do I need to provide more info? On an unrelated note; is there a better (more Pythonic / more efficient) way of swapping two rows in a Numeric array than the following. def swapRows(array, index1, index2): temp = array[index2, :].astype(type(array)) array[index2, :] = array[index1, :] array[index1, :] = temp TIA Duncan From jolsen at mailme.dk Fri Mar 15 02:05:58 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 14 Mar 2002 23:05:58 -0800 Subject: XML-RPC Question References: Message-ID: "Thomas Weholt" wrote in message news:... > I'm not sure about this, but I think SimpleXMLRPCServer only provide access > to the methods of the object you "publish", in your example the methods of > MyClass, nothing else. > > system.listMethods() comes from .... .NET ?? > > I migth be wrong, and if so, please let me know. > No, not from .NET system.listMethods() is from the XML RPC introspection API - se section 11.20.1 in the python reference doc It is nice to have when connecting to servers you have not written yourself. It should be very easy to support it in the SimpleXMLRPCServer, but I guess it is not quite a standard, so they did not bother Cheers Jesper From logstx at bellatlantic.net Sat Mar 9 18:57:02 2002 From: logstx at bellatlantic.net (logistix) Date: Sat, 09 Mar 2002 23:57:02 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> Message-ID: I'm suprised this one isn't in the FAQ. You're seeing the actual object and not a printable representation of it. >>> round(56.78923, 2) 56.789999999999999 >>> print round(56.78923, 2) 56.79 >>> "%f" % round(56.78923, 2) '56.790000' -- - wrote in message news:3c8a9c23.152007063 at news... > I understand the problem of rounding errors with binary numbers. > However, the rounding functions of other languages work around it and > return a usable result. What have they got that Python hasn't got? > > BR > > ps -- your name is very familiar. i think i've read one of your books. > > On Sat, 09 Mar 2002 23:13:50 GMT, Erik de Castro Lopo > wrote: > > >brobbins333 at shaw.ca wrote: > >> > >> the round() function will sometimes return a predictable result, as > >> in: > >> > >> round(45.67891, 2) > >> >>> 45.68 > >> > >> but sometimes it will return something like: > >> > >> round(56.78923, 2) > >> >>> 56.789999999999999 > >> > >> 2.1 and 2.2 both behave this way on two different (Windows) computers. > >> What's going on here? > > > > > >What you will fins is that some numbers like 2, 0.25 etc can be > >represented exactly in floating point format while others like > >2/3 cannot. > > > >Thats just the way it is. > > > >Erik > >-- > >+-----------------------------------------------------------+ > > Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) > >+-----------------------------------------------------------+ > >BSD: A psychoactive drug, popular in the 80s, probably developed at UC > >Berkeley or thereabouts. Similar in many ways to the prescription-only > >medication called "System V", but infinitely more useful. (Or, at least, > >more fun.) The full chemical name is "Berkeley Standard Distribution". > From bokr at oz.net Thu Mar 7 19:09:45 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Mar 2002 00:09:45 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> Message-ID: On Thu, 7 Mar 2002 08:09:52 -0600, "Chris Gonnerman" wrote: >Ugly. You state that code like this: > >def somefunc(): > astring = """this is the first line >this is the second""" > >... is ugly. Fine, but IMHO so is the proposed syntax. > >Recall always that the charm of Python is it's simplicity. Even with the >new language features added in 2.1 and 2.2, a "bear of little brain" can >remember all the rules more or less at the same time. > Well, I think the charm is that one may use a very lean and clean subset of the full set of features, but that need not imply that the full set must be limited. Python already has plenty to boggle a "bear of little brain" in meta-classes etc., so I don't think a feature that can safely be ignored should be criticized on the basis of its taxing little bears' brains ;-) >I am against pasting and patching one after another new language construct, >syntax sweetener, etc. to Python because it detracts from that core >simplicity >each and every time. > I really agree. But I think the ability to __quote__ arbitrary raw text in source is a __missing capability__. It's not something you can already do, that I'm just proposing a sugar coating for. NB: I'm not saying you can't __define__ arbitrary string content by writing suitable escape sequences etc. That's not the problem. The problem is safely delimiting arbitrary __existing__ text __within__ a source file, without changing it and without having to inspect it or make iffy assumptions about its content. I think, e.g., that "for i in 5: ..." is *more* sugary, because you already have the ability to do it with "for i in xrange(5): ..." >This is why I am against incorporating the "$varname" interpolation >operator. >At least, IMHO it is not ugly. > But things like this you can often build using classes and subclassing. I would rather extend the building capability (as has been done greatly with 2.2) than add pre-built gizmos. >There seem to be a never-ending stream of new language feature proposals. >Praise Guido they don't all get incorporated! > Agreed. >(Don't take this personally. I've had my share of similar ideas; we all >think we are like Guido and can improve the language. Learning to trust his >language-design skills was hard, but rewarding.) Well, once this has boiled down to a clear proposal, I'd like to hear his pronouncement. Thus far, I don't seem to have succeeded in communicating the fact that Python can't do now what it could using some implementation of this idea. It's not a new idea. It exists in other contexts, so it's not a personal pet invention. It's a matter of whether Guido will think the base functionality is desirable. If he does, he'll likely think of better syntax for it. I would guess he invented triple quotes as an easy and convenient way to deal with quoting a mix of single quotes. This just takes the next step, recognizing that another fixed sequence (or two) of characters as delimiters will not do it. Regards, Bengt Richter From jason at jorendorff.com Tue Mar 12 13:40:38 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Tue, 12 Mar 2002 12:40:38 -0600 Subject: new to python - please help In-Reply-To: <9e629c01.0203120932.5b3eae15@posting.google.com> Message-ID: Rule #1: Post real code. I can't make heads or tails of your post because all that code is so broken. :-/ It's got syntax errors. I can sort of see a few things that I think you're doing a bit wrong, but I can't help because I simply have no clue what you're trying to accomplish. So, post real code. Also, let us know what version of Python you're using. ## Jason Orendorff http://www.jorendorff.com/ From aahz at panix.com Wed Mar 6 18:18:22 2002 From: aahz at panix.com (Aahz Maruch) Date: 6 Mar 2002 15:18:22 -0800 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> Message-ID: In article <3C850173.4050004 at bioeng.ucsd.edu>, Curtis Jensen wrote: > >Also, if your main intent for reviewing the book was for the money, I'd >suggest playing the lotto instead. Don't be so arogant that you think >that your time is so precious as to complain about a temporary, >predeterimined, pay scale. They were upfront in their monatary >compensation. If you don't like it, don't review the book. Huh??? Can anybody explain where this paragraph comes from? -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From paul at boddie.net Fri Mar 15 11:20:40 2002 From: paul at boddie.net (Paul Boddie) Date: 15 Mar 2002 08:20:40 -0800 Subject: Converting relative URLs to absolute References: <23891c90.0203130331.6f030f5b@posting.google.com> Message-ID: <23891c90.0203150820.6362868@posting.google.com> James A Roush wrote in message news:... > [Handling relative and "rooted" links in Web pages] > This precisely what I'm looking for. As someone else pointed out in another > post, urllib should have this but, sadly, does not. The module I mentioned [1] doesn't attempt to handle more sophisticated URL types, such as... http://user at somesite/somepath Indeed, a more generic URL parser really needs to be put into the standard library whilst retaining the simplicity that one tends to see in other "path" manipulation APIs (eg. os.path) - the world doesn't need another overcomplicated Java-like API to do the simplest of things. I wonder if mxURL might at least provide inspiration. Paul [1] http://www.boddie.org.uk/downloads/urlutils.py From matt at mondoinfo.com Fri Mar 29 20:34:53 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Sat, 30 Mar 2002 01:34:53 GMT Subject: Ugly little issue with Tkinter - Pmw.Counter - datatype References: Message-ID: <1D8p8.5474$vm6.876566@ruti.visi.com> On Fri, 29 Mar 2002 16:17:39 -0600, Paul Sage wrote: >The function header currently looks like this: > >def custom_counter_body(self, text, factor, increment): > >I need it to look like this: > >Def custom_counter_body(self, text, factor, increment, thePlayer) Dear Paul, I suspect that you could use an object with a __call__method. You could store the state when creating the object and have the __call__ method take the arguments that Pmw supplies. Something like this might work: class callbackObject: def __init__(self,thePlayer): self.thePlayer=thePlayer def __call__(self, text, factor, increment): # Do something involving those arguments # and self.thePlayer return 42 Regards, Matt From krissepu at vip.fi Mon Mar 11 09:47:49 2002 From: krissepu at vip.fi (pekka niiranen) Date: Mon, 11 Mar 2002 14:47:49 GMT Subject: Changing Working Directory in Windows References: <3c8cb05d.221547919@news.earthlink.net> Message-ID: <3C8CC3C4.7030607@vip.fi> You could try playing with pythonwin's commandline: import os >>> os.getcwd() 'E:\\Python22\\lib\\site-packages' >>> os.chdir('..') >>> os.getcwd() 'E:\\Python22\\lib' >>> newpath = os.path.join(os.getcwd(), 'mydirectory', 'myfile.txt') >>> print newpath E:\Python22\lib\mydirectory\myfile.txt -pekka- nrk at cmcorp.com wrote: >I'm brand new to Python. Can someone tell me how to change a working >directory in a script on a Windows system? > >What does the pathname specification look like? >Can I use an absolute path name when referring to a file? > >Thanks for any help you can give me. > >Norm Kashdan > From grante at visi.com Fri Mar 15 09:50:28 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Mar 2002 14:50:28 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> Message-ID: In article , Skip Montanaro wrote: > > >> selectables = [theProcess.childerr, theProcess.fromchild] > >> (input, output, exc) = select.select([],selectables, selectables) > ... > > >> It blocks forever waiting for theProcess.childerr.readline(bufsize) > >> to return. I expect it to block waiting for select.select(); that > >> would not be a problem. The problem is that select is claiming > >> there's stuff to be read, then when I try to read it, it's not there! > >> How can that be? > > Based upon the attribute names you are using, I suspect you instantiated > os.Popen3 to create theProcess. These are file objects, not sockets. Under Unix (and Linux) those "file objects" would be pipes, and select will work fine. Under Windows, things are probably more complicated. > I believe select only blocks on sockets. That is true under Win32 -- Just one of the problems when using an OS where the networking was pasted on (badly) as an afterthought. Under Unix, select works on all file descriptors (sockets, pipes, serial ports, etc.). That demonstrates the _right_ way to paste on networking as an afterthought. > See the comments about asynchronous file i/o near the bottom of > asyncore.py. -- Grant Edwards grante Yow! Fold, fold, at FOLD!! FOLDING many items!! visi.com From bokr at oz.net Tue Mar 26 18:15:27 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Mar 2002 23:15:27 GMT Subject: How to get a key from dictionary? References: <3C9FAFCC.20062.91741D@localhost> <009501c1d458$0a5a86c0$3425fea9@0016314730> Message-ID: On Wed, 27 Mar 2002 08:28:38 +1200, Matthew Sherborne wrote: >This is a multi-part message in MIME format. > >------=_NextPart_000_002A_01C1D569.652C29C0 >Content-Type: text/plain; > charset="iso-8859-1" >Content-Transfer-Encoding: quoted-printable > >Sorry to be a show off, but I reckon that this way may be faster. Sorry = >again. The other replies are very helpful. :) > >def findKey(val): > for key, value in dict.items(): > if value =3D=3D val: return key > return None > =20 >GBU >Matthew Sherborne > I have no problem with your showing off (since the risk is all yours ;-) but I really dislike reading literal HTML. Please try to avoid posting it ;-/ (No, I won't switch to outlook ;-) Regards, Bengt Richter From ak at silmarill.org Thu Mar 28 02:34:14 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Thu, 28 Mar 2002 07:34:14 GMT Subject: Dealing with python version References: Message-ID: In article , Harry George wrote: > Andrei Kulakov writes: > >> Hello, >> >> Correct me if I'm wrong, but it seems like if python1.6 or 2.0 are >> already installed and you install a newer version, python command still >> points to the old interpreter. >> >> I think it would be sensible to use the newest installed python to run >> a program. Is there some elegant way to do that? >> >> I would ideally prefer it to run using newest interpreter available >> unless it's older than some minimum requirement. It's not very >> user-friendly to put #!/usr/bin/env python2.1 bang line and then say in >> a README that if user gets an error, he has to somehow find out what's >> the latest version he's got and change the bang line to it. >> >> What's the proper way to deal with all of this? >> > [snip] Umm.. I guess I should have made it more explicit that I'm distributing an application - I have a tarfile on my website that people are supposed to download, unarchive and run. The problem is that even if they have a python version that could run it correctly, the program itself should intelligently detect which versions are there, whether any of them is good enough, and if not, tell the user what exactly is the problem. What I had in mind is a function that'd take two arguments: minimum python version that the program needs and the program name itself. I.e. say I have a file called vtip.py that needs at least python 2.1. I'd like a module that I can name run_vtip.py, and in it I'd have to set two vars at top: min_python_version = "2.1" run = "vtip.py" Then it'd look at what python versions are available and if there's one that's equal or higher than 2.1, use it to run vtip.py, and if not, tell user that vtip needs 2.1 and he should get that. This seems like a very useful thing to do, and if you ask users to do this manually in your README, some of them will either miss or misunderstand it, then email you, and some will have trouble determining what versions they have and how to change bang lines, etc. IOW, this should be automated. Hadn't anyone done this yet? Is there some particular reason why this is hard to implement? - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From denro at NSPAMearthlink.net Mon Mar 4 17:42:52 2002 From: denro at NSPAMearthlink.net (Dennis Roark) Date: Mon, 04 Mar 2002 22:42:52 GMT Subject: Deitel and Deitel Book... References: Message-ID: Sheila King wrote in news:a5t3f9.3vsf871.1 at kserver.org: ... > In > fact, I know some teachers who think that their book is practically > the C++ gospel or something. I never had that high an opinion of their > book. As I related, I didn't choose it for the text when I taught C++. > I considered several other books, and ended up with the one by Walter > Savitch. And while the narrative was very good in Savtich's book, > there not enough good exercises and programming assignments for my > high school students, and I was always having to search other books > for that type of stuff... > First books in C++ are mostly a dissappointing lot, surprisingly so. The Lippman and Lajoie and books by Bruce Eckel are good for students who have some familiarity with programming. I've used the Savitch and Main and Savitch books, and a host of others searching for the "perfect book". I've considered D&D, but I could never stomach its approach (not truly object oriented from the ground up) and conceptual errors or weaknesses (some mentioned in this thread). There will probably be many grumbles with this suggestion, but the best I have found for the first introduction is Lafore, Object Oriented Programming in C++. But I am really interested in weaving Python into the CS courses including the first year courses. I am taking tentative steps in that direction this year and next. -- Dennis Roark denro at earthlink.net Starting Points: www.home.earthlink.net/~denro From tejarex at yahoo.com Thu Mar 7 03:20:59 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Thu, 07 Mar 2002 08:20:59 GMT Subject: Nested scopes: design or implementation? References: <3czdq05v.fsf@vfa.com> Message-ID: "logistix" wrote in message news:Ntwh8.2920$J3.429 at nwrddc01.gnilink.net... > Okay, now I'm confused. > > I was perfectly happy with Teddy Reedy's explaination that def is an > expression and not a declaration. What I said is that it is an *executable statement* rather than a declaration. > But if I'm following you, the embedded attribute function isn't being > recompiled to bytecode each time function() is called. For efficiency, the body is compiled once. However, this is not part of the language definition (neither is the existence of byte code). > If the code object is only getting created once, > then why are the defaults getting recalculated? Defaults, I presume, are part of the function object which is created with each invocation. Terry J. Reedy From dale at riverhall.NOTHANKS.co.uk Fri Mar 22 21:04:23 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 23 Mar 2002 02:04:23 +0000 Subject: Environment variables. References: <3C9BAFAE.51D0896D@cs.unm.edu> Message-ID: You can't change the environment variables of your calling environment. There is simply no mechanism in the OS. When your program is called, it gets a copy of the calling program's environment. You can change this copy all you like but when your program ends, it is destroyed. The only way to set environment variables so they persist is by attacking the registry but then the new values don't get used until you start a new command prompt window. -- Dale Strickland-Clark Riverhall Systems Ltd From akuchlin at ute.mems-exchange.org Tue Mar 26 15:11:08 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 26 Mar 2002 20:11:08 GMT Subject: Python and the Parrot References: Message-ID: In article , Gerard Braad wrote: > more useful... i wanted to know if someone else here is using it... and? > do you think python should be ported to the parrot vm??? or are you > already programming (/porting/testing/etc) on it??? Parrot currently has no way to implement scoped variables, therefore it's basically a toy. If and when it's actually possible to use Parrot for implementing a real programming language, I'm sure work on Python to Parrot translation will be resumed. --amk (www.amk.ca) "Brilliant! I wish I'd thought of that!" "Oh, you will, Doctor, you will." -- The Doctor and Romana, in "The Horns of Nimon" From dragon at china.org Tue Mar 26 02:29:33 2002 From: dragon at china.org (Qiang.JL) Date: Tue, 26 Mar 2002 07:29:33 GMT Subject: beginner question References: Message-ID: "Bengt Richter" wrote in message news:a7p5o2$5oe$0 at 216.39.172.122... > On Tue, 26 Mar 2002 05:25:28 GMT, "Qiang.JL" wrote: > > >for this line: > > > >>>> g=(lambda x: ' '.join(x.split())) or (lambda y: 'second') > > > I doubt if this expression is doing what you want. It is the same form as > > g = a or b > > which will set g to a, unless a counts as false (e.g., None,'',[],(), or zero), > in which case g will be set to b irrespective of b's value. So your expression > is effectively equivalent to > > g=(lambda x: ' '.join(x.split())) > sorry english is not my native language, but why equivalent ? are you saying the second condition is useless? > If you really don't want to use def and you want to use your original > expressions, use another lambda to tie them together, e.g., (OTTOMH, > not very well tested ;-) > > >>> g = lambda x: (lambda x: ' '.join(x.split()))(str(x)) or (lambda y: 'second')(str(x)) > >>> g(' ') > 'second' > >>> g(g) > ' at 0x007DB060>' > >>> g(' a bc def') > 'a bc def' > > Notice that the ouside lambda has a body that both defines _and_ calls the internal lambdas > with the str()-protected arguments. The second lambda will only be called if the first one > returns ''. The outside lambda then returns the result from whichever internal one. > > But I'd say that's pretty ugly to read compared to > > >>> def g(x): > ... return ' '.join(str(x).split()) or 'second' > ... > > ;-) > > Regards, > Bengt Richter > if the original lambdas work like yours why you add another one outside ? it seems does the same thing. Weird i run into problem with this one .. >>> def g(x): return ' '.join(str(x).split()) or 'second' >>> g(0) '0' >>> g('') 'second' >>> g=(lambda x: ' '.join(str(x).split())) or (lambda x: 'second') >>> g('') '' # why it prints '' instead of 'second' ?????? >>> g(0) '0' what's wrong here ? thanks Q. From James_Althoff at i2.com Tue Mar 5 20:33:44 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 17:33:44 -0800 Subject: Status of PEP's? Message-ID: [James_Althoff] > > I don't have to think that a dict object *is* a sequence to be > content with it being a valid arg to iter(). [Greg Ewing] > Well, more generally, "collection". Good. That's step one: generalizing from sequence to collection . [Greg Ewing] > And I *do* think > of a dict as being a collection -- of key-value pairs. > It's perhaps debatable whether its iterator should > return just the keys or keys+values, but the decision > made here makes perfectly good sense to me. In real > life, it doesn't seem at all odd to ask things like > "Is 'furgleblunger' in the dictionary?" > > But if someone asked me "Is 7 in 42?" I'd think > I'd misheard them somehow. I agree that the choice of the particular keyword "in" as in "for x in y" lends itself to being interpreted as "for each object that is a member of y which *is* an aggregation of other objects". But, since Python has already generalized beyond that, I think it's fine to say that "in" means something more than that restricted interpretation (e.g., "for each object generated by the iter(y) object"). Your basic difference of opinion, I suppose. you-say-furgleblunger-i-say-spline-ly yr's, Jim From hfoffani at yahoo.com Sun Mar 31 06:44:18 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Sun, 31 Mar 2002 13:44:18 +0200 Subject: PEP 285: Adding a bool type References: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Message-ID: <20020331064422.219$KW@news.newsreader.com> "phil hunt" escribi? en el mensaje > .... > > I've gone through some of my herbivore code, looking to see where > I've used 0 or 1 as a boolean. Example 1: > > debug = 0 # debugging this module? > > Frankly, if that is unclear to anyone, they are not cut out to be a > programmer. Bear in mind that most non-programmers are aware of the > 0/1 paradigm for boolean values: it appears on much electrical > equipment. > > [an example of a "log" flag follows] Actually "debug" and "log" flags use to be confusing if the original author didn't document the use case. Those can be either boolean flags or integers level indicators. For instance, in your example the "debug = 0" may have both meanings. It's the "?" in the commentary that raises the bets towards boolean. It's a very common practice to start with a boolean meaning and "promote" it afterwards to a level parameter. I'm not judging that practice here because I don't think it is a problem, it just works. Regards, -Hernan From mertz at gnosis.cx Sat Mar 9 12:57:15 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Sat, 09 Mar 2002 12:57:15 -0500 Subject: short-circuit behavior anomaly? (fwd) Message-ID: <7zki8kKkXoNV092yn@gnosis.cx> |> http://gnosis.cx/publish/programming/charming_python_13.txt |> def pr(s): print s |> def fn(): |> (x == 1 and pr('one')) \ |> or (x == 2 and pr('two')) \ |> or (pr('other')) |By default, functions return None, which is false. For this function |to work right in context below, you must return a true value That is my tutorial. I was just about to write apologizing for the error. But looking at the file, I don't see the problem there currently. I'm not sure whether the problem was with a cached version of the article that has been fixed; or maybe it is from one of my other articles on FP in Python. In any case, Reedy is right about the example. A better function would be something like: def pr(s): print s return 1 Btw. There *is* an error in one of my articles, concerning short-circuiting. I'm not sure if I corrected it on my web site (but the IBM dW copy will remain wrong either way). It was something like: # Like C ternary 'cond ? this : that' (<> and this) or that If this is a false value, the expression doesn't do what is desired. A solution is: ((<> and [this]) or [that])[0] One has to be careful with short-circuiting. Despite my efforts to point out some functional styles, sometimes plain ole 'if' blocks are still clearer. Yours, David... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From sholden at holdenweb.com Fri Mar 29 10:12:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 10:12:09 -0500 Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> <3ca47917.18551297@news.tudelft.nl> Message-ID: "Fused" wrote in message news:3ca47917.18551297 at news.tudelft.nl... [ ... ] > "Steve Holden" wrote: > > > >I'd really like to see a Python mail/newsreader. That would teach you a lot, > >and keep you busy for a while... > > > It would teach me indeed, especially since I know next to nothing > about mail/news protocols :) But why would you specifically want a > Python mail/newsreader, when there are plenty of good mail/newsreaders > around? Because I could modify the Python code to0 make it behave in ways the "good" mail/newreaders don't. Specifically, I could have it interact with a relational database rather than a file-based message store. regards Steve From gh_pythonlist at gmx.de Wed Mar 13 12:06:08 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 13 Mar 2002 18:06:08 +0100 Subject: Python on Windows soon forbidden by Micro$oft? In-Reply-To: References: Message-ID: <20020313170608.GB2611@lilith.hqd-internal> Le 13/03/02 ? 09:10, rasmussn at lanl.gov ?crivit: > > On Tuesday, March 12, 2002, at 02:54 PM, phil hunt wrote: > > > >Lying to get money = fraud > > > >I think MicroShit's directors and laywers should be banged up for a > >few years. > > Let me throw out a different interpretation on Microsoft's actions. > > As I was reading Microsoft's license, I thought of it in relation to > the GPL. > Maybe Microsoft is just covering it's backside so that users of their > products won't use it in ways that will break the GPL. [...] I cannot imagine they'd waste a thought on wether their users break other people's/companies licenses, because there's no way Microsoft could get into trouble because of that. So that only leaves that they're spreading FUD intentionally. Btw. all EULUs contain something like: "To the maximum extent permitted by applicable law [bla bla bla]". The reason is that often, their requirements do not conform to some national laws. One example is reverse-engineering binaries, which *is* legal in some countries (using the retrieved information commercially is of course a different matter). I don't know the legal term for this, but there are certain rights which you cannot give away, even if you "agree" to in a contract. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.0 ?C Wind: 2.8 m/s From john at yahoo.com Sat Mar 23 21:18:45 2002 From: john at yahoo.com (John Warney) Date: Sun, 24 Mar 2002 02:18:45 GMT Subject: is there gonna be a Core Python Programming 2e ? Message-ID: I was wondering if there was plans on CPP 2e ? (no its not c++, core python programming, lol) If so i would ask for a better binding than what is on CPP. I would even pay more than what the current CPP is at now. Rob From jacobs at darwin.epbi.cwru.edu Fri Mar 8 07:36:51 2002 From: jacobs at darwin.epbi.cwru.edu (Kevin Jacobs) Date: 8 Mar 2002 12:36:51 GMT Subject: need something like __init__ in classes __classinit__ References: Message-ID: Jens Gelhaar wrote: > class metaclass(type): > def __new__(cls): > cls.__classinit__(...) > class primary(Persistent): > __metaclass__=metaclass > def __classinit__(cls): > << do something ...> > I get a error message, that I can not inherit from to different > metaclasses. I'm not sure my advise will help with ExtensionClasses, since I don't know enough about how it is implemented. Here is how I think it can be done without changing the Python core: class ClassInit(type): def __new__(cls, name, bases, cls_dict): # Transform __classinit__ into a static method class_init = cls_dict.get('__classinit__',None) if class_init: cls_dict['__classinit__'] = staticmethod(class_init) # Call super instead of type.__new__ to allow cooperative metaclasses return super(ClassInit,cls).__new__(cls, name, bases, cls_dict) def __init__(self, name, bases, cls_dict): # Call __classinit__ if it exists and is callable. # This cannot be done in __new__ since the class may not be completely # initialized by its metaclasses. if callable(getattr(self, '__classinit__',None)): self.__classinit__(self) class ClassInitObject(object): __metaclass__ = ClassInit class Persistent: pass class primary(ClassInitObject,Persistent): def __classinit__(cls): print "In __classinit__:",cls def __init__(self): print "In __init__:",self p=primary() The output is then: In __classinit__: In __init__: <__main__.primary object at 0x812961c> So the trick is to use multiple inheritance to allow multiple metaclasses. I have no idea if this will work with an ExtensionClass, but its much more likely than getting Guido to support __initclass__ in the Python core. (Anyway, this will certainly work with the ZODB from Zope3.) I'll add this trick to my growing list of metaclass hacks. If anyone is interested, I'll post them on my website later today. Here is the current list of magic metaclasses: o A metaclass that lazily instantiates slots so that you can write: class A(object): __metaclass__ = LazySlotBuilder __slots__ = ('a') class B(object): __metaclass__ = LazySlotBuilder __slots__ = ('b') class AB(A,B): pass Without the metaclass magic, this would will result in a layout conflict: TypeError: multiple bases have instance lay-out conflict o A metaclass that adds constraint checking to attributes and slots. This can be used to implement type checking in Python: class A(object): __metaclass__ = ConstrainedObject __slots__ = {'a':int,'b':float} class B(A): __attrs__ = {'c':str} foo=B() foo.a = foo.b = foo.c = 1 assert foo.a == 1 assert foo.b == 1.0 assert foo.c == "1" assert type(foo.a) == int assert type(foo.b) == float assert type(foo.c) == str foo.a = 'Hello' # Throws a ValueError from trying to run int('Hello') o A tuple building metaclass that allows access to tuple elements by name as well as by index. There is also a version that allows access to elements by name in a case-insensitive manner. These objects are very useful as a replacement for DB-API row tuples, which is why I call them Row objects: ABCRow=RowMetaClass(['a','b','c']) r=ABCRow( (1,2,3) ) assert r['a']==r[0]==r.a==1 assert r['b']==r[1]==r.b==2 assert r['c']==r[2]==r.c==3 ABCRow=InsensitiveRowMetaClass(['a','b','c']) r=ABCRow( (1,2,3) ) assert r['a']==r['A']==r[0]==r.A==r.a==1 assert r['b']==r['B']==r[1]==r.B==r.b==2 assert r['c']==r['C']==r[2]==r.C==r.c==3 o The above ClassInit metaclass. Regards, -Kevin -- Kevin Jacobs The OPAL Group - Enterprise Systems Architect Voice: (216) 986-0710 x 19 E-mail: jacobs at theopalgroup.com Fax: (216) 986-0714 WWW: http://www.theopalgroup.com From James_Althoff at i2.com Mon Mar 11 18:17:38 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 11 Mar 2002 15:17:38 -0800 Subject: PEP 284, Integer for-loops (fwd) Message-ID: [James_Althoff at i2.com] > ... > But if your protocol is > def getRowCount(): pass > def getColumnCount(): pass > def getValueAt(rowIndex,columnIndex): pass > def setValueAt(rowIndex,columnIndex): pass > then that option is not available. [Tim Peters] > Hmm. The inability to pass a new value to setValueAt seems to make > this a little feeble . Ah, but is it feeble or is it *omniscient*? Actually, I did it this way just to be consistent; I make the same mistake when I type it in code, too. The suggestions below are nice -- although our particular (Java-based) context leaves us still with a few spanners to deal with. > Depending on how much overhead you're willing to bear, it's > straightfoward to write wrapper classes (even using the old > for/__getitem__ protocol) such that, e.g., adding 1 to every > element in a table could be expressed via > > t = Table(original_table) > for r in t.rows(): > for e in r.elements(): > e.set(e.get() + 1) This is nice. We have noticed that there can be a hit in Jython the first time you instantiate a Python subclass of a Java class (it seems to build some internal structures based on a lot of Java reflection). We could implement a Java subclass instead. But we are trying to minimize the appearance of needing to resort back to Java for what are probably obvious reasons. But I think it might be worth having this option for times when performance isn't an issue and looping through all rows or columns is required. I would rather do it with the new iterator stuff that is available in C-Python, but ... oh well. > Short of that, you could at least reduce the clumsiness by > defining helper functions, like (assuming these are 0-based > indices; fiddle to taste): > > def ri(table): > "Return row indices for table." > return range(table.getRowCount()) > > def ci(table): > "Return column indices for table." > return range(table.getColumnCount()) > > and then > > columns = ci(table) > for i in ri(table): > for j in columns: > table.setValueAt(i, j, table.getValueAt(i, j) + 1) > > would save some typing yet be just as quick. Add > > def getter(table): > "Return bound table.GetValueAt." > return table.GetValueAt > > def setter(table): > "Return bound table.SetValueAt." > return table.SetValueAt > > and then > > get, set = getter(table), setter(table) > columns = ci(table) > for i in ri(table): > for j in columns: > set(i, j, get(i, j) + 1) > > would be about as fast as you can get in Python, short of defining a custom > "add 1 to element and then store it back" function. Some helper functions might be convenient. They would be most convenient in a helper utility module, of course, so that we could standardize them for the entire development team. A twist that we have to live with is that the 3rd party components are not always consistent with each other. JTable and DefaultTableModel both use "getRowCount()". So we could have a generic function for these. But another 3rd party component uses "getNumberOfRows ()" instead. So we would have to do the try:except:/hasattr/isinstance stuff to make the helper functions generic. Probably worth giving it a try. > If you're very concerned about speed, when you've got a choice the loop with > the largest trip count should be innermost (as true in Python as in any > other language, although this is clawing at what are usually third-order > effects). Thanks for the suggestions. Jim From michaelteo at bigfoot.com Tue Mar 19 10:20:07 2002 From: michaelteo at bigfoot.com (Michael Teo) Date: Tue, 19 Mar 2002 23:20:07 +0800 Subject: Detecting corrupted .pyc files Message-ID: Does the python interpreter has some mechanism for checking whether the .pyc files are corrupt before running it ? Thanks for replying. -- Michael Teo http://miketeo.net/ PGP 0x6C846A9C DB:7D:51:D4:4D:AB:97:79:E4:68:D9:07:94:36:D5:1A:6C:84:6A:9C 0x6937FB05 08:50:A1:4D:2E:45:58:60:DE:71:1F:30:63:54:EF:7B From logiplexsoftware at earthlink.net Fri Mar 15 13:35:49 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 15 Mar 2002 10:35:49 -0800 Subject: socket In-Reply-To: References: Message-ID: <20020315103549.4575e9bb.logiplexsoftware@earthlink.net> On Fri, 15 Mar 2002 17:46:01 GMT Billy Ng wrote: > Nothing evil here. I have 2 reasons why I would do this program. Firs, it > is my TCP/IP concept class's project. Basically, I want to try what the > book tells in to code, but I notice it does not work the way it says in so > many commercial SMTP servers. Second, I have been unemployed for about 4 > months. My friend's company needs a program to verify the users who > registered to their service. They found out many registered users were > using fake addresses. I just want to try this program to see if I will get > a job there. That's all! I really do appreciate if you would provide any > info for me to complete this project. Why not do like many others do: send a confirmation email to the address and require a reply from that address to complete registration. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From skip at pobox.com Wed Mar 27 12:55:07 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Mar 2002 11:55:07 -0600 Subject: instrumenting Python code In-Reply-To: References: <1010a26.0203262213.4a0d4b11@posting.google.com> <3CA16839.1A21E36A@engcorp.com> Message-ID: <15522.1915.63435.392960@beluga.mojam.com> >> Or, in 2.2, the new hotshot module, which is a lot more efficient at >> profiling than the profile module. aahz> Where is hotshot? I don't see it anywhere. It's not even on the aahz> Vaults of Parnassus. It's part of the standard library in 2.2. There is a hotshot.py Python module in Lib and a _hotshot.c extension module in Modules. The only docs at this point are Fred's slides from IPC10. Look here http://www.python.org/workshops/2002-02/ for Powerpoint and Postscript versions. Skip From bokr at oz.net Tue Mar 26 19:39:51 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Mar 2002 00:39:51 GMT Subject: Symbolic imports and manipulation of the namespace? References: Message-ID: On Tue, 26 Mar 2002 15:12:09 -0700, VanL wrote: >Hello, > >I was recently solving a problem which required that the config file >(just a python file) lie outside of the pythonpath. Is it possible to >do symbolic importation of a module? > >For example, I had: > ># cfgpath is passed in on the command line >cfgpath = os.path.basename(cfgpath) >sys.path.insert (0, cfgpath) >import sc_cfg #Hardcoded config module name! > > >How do you do this: > ># cfgpath is passed in on the command line >cfgpath, cfgfile = os.path.split(cfgpath) >sys.path.insert (0, cfgpath) >import cfgfile #Hardcoded config module name! > >So that any file name (ending with .py, of course, but that's another >matter) could be the configfile? >I tried the above, but I got an ImportError (no module named cfgfile) > >Thanks, > see if help(__import__) helps decide if you need to worry about default arguments. >>> cfgfile = 'xxx.py' >>> import cfgfile Traceback (most recent call last): File "", line 1, in ? ImportError: No module named cfgfile ^^^^^^^---Notice >>> __import__(cfgfile) ^^^^^^^--Notice Traceback (most recent call last): File "", line 1, in ? ImportError: No module named xxx.py ^^^^^^---Notice Looks like you may need to drop the '.py' if your cfgpath has one, or it will think package syntax. Also you have to do something with the __import__() return value, like maybe (untested) cfgmodule = __import__(cfgfile.split('.py')[0]) I haven't used this, so it's theory for you to test ;-) Regards, Bengt Richter From martin.franklin at westerngeco.com Tue Mar 19 05:56:31 2002 From: martin.franklin at westerngeco.com (Martin Franklin) Date: Tue, 19 Mar 2002 10:56:31 +0000 Subject: Scrolling line number Tkinter References: <3C8E84AA.4070306@club-internet.fr> <3C911DCC.5010605@club-internet.fr> Message-ID: Fabien Henon wrote: > Martin Franklin wrote: > >> Fabien Henon wrote: >> >> >>>I am currently writing a text editor for POV-RAY under Windows using >>>Tkinter. It should be working as well with linux and Mac. >>> >>>To display the line numbers, I use a scrolling column at the left of the >>>editor with a text box. >>> >> >> Can you please explain what a scrollng column is? Perhaps if you post >> some code we could help some more. >> >> >> >>>I also linked the main text editor with a scroll. >>> >>>My problem is that the text editor is well linked to the scroll, but the >>>line numbers do not move when I use the arrow cursors. >>> >>>Thanks for any help >>> >>>Fabien >>> >> >> It sounds like you need to link both the scrolled column and text box to >> the same scrollbar.... >> > What I mean by scrolling column is a column in which are displayed all the > line number of the text. > > I want this column of lines to scroll with the edited text. > > > cheers. By Column you mean Frame widget? It's wierd I've just finished writing a Text box with an optional line number counter down the side....... basically the code boils down to this:- f=Frame(self) # self.textaree is the main text box (also happens to be a Pmw # ScroledText so I get dynamic scrollbars for free! self.textarea=Pmw.ScrolledText(f, text_wrap='none') # self.lineCounter is a Tk.Text widget I grid inside the # Pmw.ScrolledTextBox above so I can share the Pmw dynamic # scrollbars # self.lineCounter=Text(self.textarea.interior(), width=5, bg='grey', state='disabled') self.textarea.length=int(self.textarea.index('end').split('.')[0]) # I only bind the main textarea to the scroll bars cause it caused lots # of problems when I tried to bind both Text widgets..... # this is taken care of whe I update the line counter... self.textarea.component('text').config(yscrollcommand=self.yscrollset) self.textarea._vertScrollbar['command'] = self.yscroll # Scroll functions..... def yscrollset(self, *stuff): ## print 'yscrollset called', stuff apply(self.textarea._vertScrollbar.set, stuff) self.lineCounter.yview_moveto(stuff[0]) def yscroll(self, *stuff): ## print 'yscroll called', stuff apply(self.textarea._textbox.yview, stuff) apply(self.lineCounter.yview, stuff) def setLineCounter(self, *event): # should be called check_line_count # if the length of the main textarea (self.textarea) changes # then wake up and update the line counter new_length=int(self.textarea.index('end').split('.')[0]) if new_length!=self.textarea.length: self.textarea.length=new_length self.updateLineCounter() # need to set scroll pos.... now? how do I do that__? apply(self.yscrollset, self.textarea._vertScrollbar.get()) self.after(1, self.setLineCounter) # recurse..... def updateLineCounter(self, *event): self.lineCounter.config(state='normal') self.lineCounter.delete('0.0', 'end') for line in range(1, self.textarea.length-1): self.lineCounter.insert('end', '%i\n' %line) self.lineCounter.insert('end', '%i' %(self.textarea.length-1)) line, col = map(int, self.textarea.index("insert").split(".")) self.lineCounter.mark_set("insert", "%d.0" %(line)) self.lineCounter.config(state='disabled') HTH, Martin. From sjmachin at lexicon.net Sun Mar 31 17:21:02 2002 From: sjmachin at lexicon.net (John Machin) Date: 31 Mar 2002 14:21:02 -0800 Subject: OT: Daylight savings time (was Re: Subclass sadness (was Re: [Python-Dev] PEP 285: Adding a bool type)) References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <3CA73486.72B4059F@engcorp.com> Message-ID: Peter Hansen wrote in message news:<3CA73486.72B4059F at engcorp.com>... > Richard Jones wrote: > > > > Hrm, just following this thought here, possibly for no good reason at all > > (hey, it's Sunday, and daylight savings just ended so I've got a whole _hour_ > > extra to waste today :)... > > In which country? Good thing it's not a work day, since I took your > word for it last night... or was that another advance April Fools joke? > "daylight savings just *ended*" (my emphasis) -> try thinking "other side of the equator" From dale at riverhall.NOTHANKS.co.uk Sat Mar 30 07:38:33 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 30 Mar 2002 12:38:33 +0000 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: Syver Enstad wrote: >Here's what you need: > > >REGEDIT4 > >[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] >@="{86C86720-42A0-1069-A2E8-08002B30309D}" > >[HKEY_CLASSES_ROOT\Python.NoConFile\shellex\DropHandler] >@="{86C86720-42A0-1069-A2E8-08002B30309D}" > For some reason, this only drops the DOS 8.3 version of the filename. Unfortunately, this breaks some of my routines so I'm back to using a batch file wrapper for now. -- Dale Strickland-Clark Riverhall Systems Ltd From jessw at loop.com Thu Mar 7 00:14:10 2002 From: jessw at loop.com (Jesse W) Date: Wed, 6 Mar 2002 21:14:10 -0800 Subject: Status of PEP's? Message-ID: <3C8686A2.27247.BF1E41@localhost> I feel that this whole idea of picking the _most_obvious_ or _most_natural_ or even (as has been said sometimes), _any_ _practical_ or _useful_ meaning for the iter protocol for any given type is simply a bad idea. As an example, look at the Warning about "for line in file:" thread. Apparently, the xreadlines method, which is called invisibly by the iter method (also called semi-invisibly by the use of the in operator), has a problem with not leaving gaps in the files it reads. None of this is at all obvious to the poor user using the obvious(and it is _obvious_, just not safe or meaningful) syntax of for line in file. It is probably not even documented, because the documentation for the xreadlines method(where the explanation for the bug would be listed) is not connected to the documentation(wherever it would be) for the syntax trick of iter'ing files. (Where would documentation be on that, actually?) This does not directly have to do with PEP 276's int iterator, but I believe that it shows a problem with the whole idea of hiding the mechanisms of what is going on through _practical_ meanings for the iter protocol. Jesse Weinstein From garyr at fidalgo.net Thu Mar 28 14:17:16 2002 From: garyr at fidalgo.net (Garyr) Date: Thu, 28 Mar 2002 11:17:16 -0800 Subject: Program termination problem Message-ID: I have a program that displays a Tkinter Text widget. I would like to be able to place text in the window via the clipboard. I found the following clipboard code in a Google post: import win32clipboard as clip ... clip.OpenClipboard(0) if clip.IsClipboardFormatAvailable(clip.CF_TEXT): newText = clip.GetClipboardData(clip.CF_TEXT) textwidget.insert(END, newText) clip.CloseClipboard() This works but it causes the program to hang on exit. mainloop() returns but the DOS window is frozen. The problem is associated with the clipboard functions; i.e., commenting the insert line has no effect. I'm using Python 2.1 (Pythonwin 2.1.211) on Win98. Any suggestions? Thanks in advance, Gary Richardson From stephen at xemacs.org Mon Mar 4 22:42:30 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 05 Mar 2002 12:42:30 +0900 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> <87sn7g2stu.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87it8b1xzt.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Huaiyu" == Huaiyu Zhu writes: Huaiyu> To produce a kind of tar file, perhaps? Those are tarbytes. Explicit is better than implicit. Huaiyu> To send something through socket? Verbatim low-level I/O would be permitted. I would want them to be restricted from being displayed literally by character-oriented high-level functions like print, though. If you want to use print on them, convert them to something with an appropriate (trivial) __repr__ operation defined. Huaiyu> But if it in the end restricts the kind of operations that Huaiyu> can be performed on raw strings, it's simply untenable. No. Perhaps I haven't presented this well, but I don't care what you do with blocks of raw memory, as long as they are a different type from character strings and cannot be used as though they were character strings. _It's the use of character strings that I want to restrict._ Confounding octets with characters is a horrible disease--- at XEmacs, we call it "Ebola." It crashes editors and MUAs, it corrupts text and destroys data, it may even cause your daughter to decide to become a dentist and marry a marketing VP. In the transition we have to decide what to do with the current undifferentiated notation. I suspect that people who use raw strings to access data representation are far more aware of the issues than people who think of them as "human readable text" that "just works." Thus by the principle of "least surprise" I advocate that raw string users use a new notation, while the (much larger and much more naive) group of people who expect print 'And now for something completely different' to do something useful would notice nothing new. print o'she turned me into a newt ... it got bettah' would either error (my preference) or print something like a tuple of integers. print Code86(o'spam, spam, eggs, and spam').disassemble() would do what you think, if class Code86 were defined appropriately. Yes, for people who use raw strings for access to representation extensively, this would be a one-time PITA for the conversion to the o'' notation (or whatever it turns out to be). And it's probable that the representation in source would not be one-to-one, ie the bytes would be encoded in uninterpreted UTF-8. A raw string would be turned into an array of 16-bit integers by the lexer, and the parser would then convert to an array of bytes internally based on the o'' syntax. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From peter at engcorp.com Wed Mar 20 19:48:13 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Mar 2002 19:48:13 -0500 Subject: Java and Python References: Message-ID: <3C992DCD.A4DE955A@engcorp.com> kosh at aesaeion.com wrote: > > On Wed, 20 Mar 2002, Peter Hansen wrote: > > > Way, way down the list of things I look for in a resume > > is the programming languages a candidate has. Not entirely > > unimportant, but useful only taken as a whole. [...] > > Those with only a single language, or maybe two, probably > > didn't get hired. Those with a dozen were more able to > > demonstrate their flexibility to me. > > The problem I have with someone learning lots of languages is that most of > what I have seen is that they never go beyond a surface level > understanding of the language. So you end up seeing people that can > essentially write C in any language or java etc. However in order to be > really productive you need to know a language and know it very well. Completely agreed! Understanding at least one language very well is a necessary step before one can reach the point of being able to learn new languages quickly. I took a long time to learn BASIC (which is how I learned programming), then a perhaps slightly shorter time learning C, and I accelerated rapidly in the subsequent languages. > I would rather see someone that can demonstrate higher level > mastery with one language then a surface level with many. I would not hire either. The latter is a dilettante, while the former has not generalized her experiences beyond that one language and so is unable to contribute where I really need the help. Combine the two, now that's something. > You can't get to more advanced features until you understand > all of the basic features. However once you learn those features > you are in a better position to apply them in another language. Agreed, again, completely. Even more than that, I would add that you are then in a better position to understand the fundamentals of *programming*, in a way you only understand with experience, regardless of syntax. The first language in which you encounter "late binding" for example, may teach you very little about what that really means in a broader sense. The second time you learn about it you'll start to see the forest, not just the trees. -Peter From edream at tds.net Mon Mar 4 09:37:56 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 04 Mar 2002 14:37:56 GMT Subject: The Text Widget References: <5Hzg8.72869$vP.290047@rwcrnsc51.ops.asp.att.net> <3C82E8C4.24531DE7@tds.net> <3C833DB8.6A4EB165@tds.net> Message-ID: <3C8386C3.181D1D48@tds.net> Eric Brunel wrote: > > Are you sure? > > Yep. Definitely. In fact, we were doing the same thing than you: a syntax > highlighting text editor. And we never did any after_idle in it, so you can > do it just via regular bindings. Thanks very much for this information. I must have blundered somehow in concluding that wouldn't work. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From bokr at oz.net Thu Mar 28 21:22:22 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Mar 2002 02:22:22 GMT Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: On Thu, 28 Mar 2002 14:48:28 +0000, philh at comuno.freeserve.co.uk (phil hunt) wrote: >On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen wrote: >>Jim Dennis wrote: >>> >>> The core loop is something like: >>> >>> freq = {} >>> for line in file: >>> for word in line.split(): >>> if word in freq: freq[word] += 1 >>> else: freq[word] = 1 >>> >>> (assuming Python2.2 for file interation and dictionary membership >>> support using "in." I *really* like those 2.2 features! They make >>> my psuedo-code so executable!) >> >>Something like freq[word] = freq.get(word, 0) + 1 >> >>would probably be faster, and it's a little simpler I think, >>although I could see an argument that it's less readable. >>Also doesn't depend on 2.2. > >IIRC in Awk you can just say: freq[word] ++ and it works >correctly even when there is no pre-existing index of word in freq. > >IMO it's a pity Python isn't like that. > Since successful freq[word]+=1 is the rule (in proportion to the final frequency ;-) it should be cheap to write try: freq[word] += 1 except KeyError: freq[word] = 1 Do I misremember a timbot post to that effect? Or is "try:" more expensive than all the rest ("if word in freq", "if freq.has_key(word)", and "freq.get(word,0)") ? Regards, Bengt Richter From boris.huart at mathworks.fr Tue Mar 26 13:16:10 2002 From: boris.huart at mathworks.fr (Boris Huart) Date: Tue, 26 Mar 2002 19:16:10 +0100 Subject: communication with a java applet References: <3C9F100D.BAB4F24D@hotmail.com> <57de9986.0203251218.6e42a9ab@posting.google.com> Message-ID: <3CA0BAE9.33B4C155@mathworks.fr> Hi Giles, Thanks a lot for your help, I take the liberty to save your adress in case it doesn't work out ;). Thanks again, Bye, Boris Giles Brown wrote: > Looping wrote in message news:<3C9F100D.BAB4F24D at hotmail.com>... > > Hi all, > > > > I am trying to make a real-time system communicate with a java applet > > under IE 5.5. I only have a pyd file (Python 1.5.2) to get the floats > > calculated on the platform and I wonder how to make the platform > > communicate with my java applet : TCP/IP, CORBA, shared memory, > > others... ? > > > > Thanks in advance for any advices, > > Its relatively straightforward to get Python and Java to talk over > sockets. > If you want to send data in a binary format then on the Python side of > things there is the "xdrlib" (I'm assuming this was present in Python > 1.5.2 as I don't have 1.5.2 installed anymore). On the Java side > you'd want to get hold of a DataInputStream (or DataOutputStream). > Something like: > > DataInputStream dis = new DataInputStream(mySocket.getInputStream()) ; > double nextValue = dis.readDouble() ; > > Good luck, > Giles -- Sinceres salutations, Boris HUART [mailto:boris.huart at mathworks.fr] ____________________________________________________________________ The MathWorks Consulting Tel : 01 55 64 06 63 Fax : 01 55 64 06 64 20 rue Troyon Email : mailto:consulting at mathworks.fr 92316 Sevres Cedex, France Web : http://www.mathworks.fr ____________________________________________________________________ From tim.one at comcast.net Fri Mar 29 15:04:13 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 29 Mar 2002 15:04:13 -0500 Subject: optional pass? (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26)) In-Reply-To: Message-ID: [Alexandre Fayolle] > Why don't you put a docstring ? It will help you document precisely what > you had in mind when writing the class, and you can keep it when you > actually write the code. [phil hunt] > 3 reasons. Note that this is also a docstring: '' It's two fewer characters than "pass", and right next to the colon key for ease of rapid typing . > ... > class Foo: > def method1(self): > def method2(self): > def method3(self): > def method4(self): > def method5(self): You realize there's no chance Guido will go for this, right? It looks like 5 errors of omission. From gerritvd at decillion.net Tue Mar 19 04:51:32 2002 From: gerritvd at decillion.net (gerritvd at decillion.net) Date: Tue, 19 Mar 2002 11:51:32 +0200 Subject: Excel AddIn Message-ID: <3C970A23.4DE8C406@decillion.net> Hi All, I would like to write an addin for Excel. I have a COM server running that is accessible via Excel. I would however like this server to be available in Excel as an addin. Has anybody done this successfully? Any pointers or help in this regards would be appreciated. Regards Gerrit van Dyk From michael at stroeder.com Fri Mar 29 10:12:26 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 29 Mar 2002 16:12:26 +0100 Subject: Simple threaded web-server based on BaseHTTPServer? References: <3C5976D0.A3A63A46@stroeder.com> <3CA36D8D.1080204@stroeder.com> Message-ID: <3CA4845A.8050203@stroeder.com> Aahz wrote: > In article <3CA36D8D.1080204 at stroeder.com>, =?ISO-8859-1?Q?Michael_Str=F6der?= > wrote: > >> Aahz Maruch wrote: >> >>> In article <3C5976D0.A3A63A46 at stroeder.com>, Michael >>> =?iso-8859-1?Q?Str=F6der?= wrote: >>> >>>> In my case (http://web2ldap.de) I'm using threaded BaseHTTPServer but >>>> I'm not really happy with it. Especially since I have to use a module-wide >>>> lock to serialize calls into python-ldap module because the >>>> underlying OpenLDAP libs are not thread-safe. This can block the whole >>>> thing and killing threads on e.g. Linux is not possible. Having a >>>> single-process asyncore design would probably make things easier. >>> >>> Add another thread to serialize things instead of using a >>> module-wide lock. >> >> I really wonder how this helps if the call into the underlying module >> really blocks. BTW: In opposite to my original statement an asyncore >> design would also not help since the underlying OpenLDAP lib is not >> designed that way. > > > I made my suggestion in the context of assuming that your server threads > can continue to interact with the user while waiting for the LDAP call to > complete. One possible option would be to have your server's LDAP thread > call out to another LDAP server that you write to fork off processes > (that's assuming the LDAP library is concurrent across multiple processes, > of course). I apologize for not making the situation clear enough. In fact I have a web server acting as a web gateway to the LDAP server. Each HTTP request is served by a thread. If a LDAP call in one HTTP server thread blocks forever other HTTP requests resulting in a LDAP call can't progress since I have to serialize all calls into the LDAP lib which is not thread-safe with a thread lock. IMHO a separate Queue.Queue approach does not help. I already thought about having a thread lock with a timeout since I would assume that after e.g. 60 seconds the web client causing the blocking request already gave up and I would not care about the old request being served falsely. Does anybody have a code snippet for a thread lock with timeout? I also thought about forking. But I work with persistent LDAP connections and therefore IMHO need a threaded environment. Ciao, Michael. From sumner-nntp5 at forceovermass.com Thu Mar 7 11:17:51 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Thu, 07 Mar 2002 16:17:51 GMT Subject: Reorganizing python.org (was: Why isn't pychecker...) References: Message-ID: [Some attributions were lost already...] In article , Christian Tanzer wrote: > Gerrit Muller wrote: >> > > Define "page". If you say 800x600 you'd lose. >> > >> > Good question. How would you define a page in terms of web design? >> > >> > Eliminating most if not all scrolling on reference pages seems >> > particularly important. Some reference pages seem way too long. And >> > your point is well taken. I have a large monitor, but I use relatively >> > big fonts, so I'm only using 1024x768... >> > >> > Edward >> <...snip...> >> at this moment in time 1024*768 is a reasonable choice; the poor 14" CRT >> users will need some scrolling, but all more lucky 15" LCD and 17" CRT >> and above will have a scroll free overview. > > You are assuming that everybody is wasting the full screen on the > browser's window. That might be true for the average windows user but > is not true in general. For instance, my monitor displays 1800x1024, > but the browser gets only about 850x650 of that. > > IMHO, software/web pages making such assumptions suck. Right. If you're making assumptions on a reference page I think the following is reasonable: Assume that the normal page is around 800x600 _only_ for the purposes of limiting scrolling--that "one page" shouldn't need any scrolling at 800x600. Design the pages so that they will display okay (without side-scrolling) at 640x480 and lower, though they may need vertical scrolling at that depth. Remember that low-resolution browsers are becoming more and more popular as more handhelds get connectivity (they often have resolutions around 320x200, cell phone browsers are sometimes even smaller). Ideally, the 320x200 window should display without scrolling sideways (though possibly with a lot of up-and-down), assuming the browser it uses is intelligent about image display. One site that gets this part of web design right is the stereophile.com site--I can read all their archives just fine in links (text-mode browser, nicer than lynx), in an 80-character wide column. There are left and right navigation bars/ad areas, so the main content winds up using only about 1/2 of the screen width, but it's readable only with forward scrolling. The current www.python.org does okay with this, too. (Good rule of thumb: if links displays a site in a readable way, then screen-readers for the visually impaired should work okay with the site). Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From bokr at oz.net Mon Mar 4 16:50:37 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Mar 2002 21:50:37 GMT Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: On 01 Mar 2002 22:20:47 +0100, martin at v.loewis.de (Martin v. Loewis) wrote: >Skip Montanaro writes: > >> Just to make sure I understand correctly, under Stephen's propsal would >> >> s = "\xff" >> >> be correct? I assume >> >> s = "?" >> >> (a literal 0377 character) would be an error, yes? > >Yes, on both accounts. > >> That is, when you saw "arbitrary binary data" you are referring to >> non-printable octets in the source file, right? > >Correct (except that whether something is printable is in the eye of >the beholder). On the source level, the four letters '\', 'x', 'f', >'f' are not arbitrary binary - they follow a specific syntax. > >I actually doubt anybody is putting "arbitrary binary" data into >source code. Instead, most such occurrences are likely "printable", if >viewed in the encoding of the author of that code. Those would be >outlawed, unless that encoding is UTF-8. > However, people will be wanting to put arbitrary data in strings, and I think having 'xxx' define something other than 3 octets should be separately controlled from whether the source is encoded in UTF-8 or UTF-16 or whatever. Otherwise open('filexxx','wb').write('xxx') may lose its meaning just because someone imported it into an editor and wrote it out as UTF-8 for whatever reason (e.g., not intending to change anything other than adding some comments in Japanese). It may be convenient for some programs to have 'xxx' default to internal UTF-8, but that means strings are strictly utf-8 sequences, and passing 'xxx' to .write() would probably imply passing the UTF-8 bytes. So if you wrote open('fileyyy','wb').write('\xff') you would expect to find the UTF-8 sequence, not one chr(0xff) -- oops, what is chr() going to do? Shouldn't '#'+chr(0xff)+'#' be == '#\xff#' ? I think changing the internal representation of unqualified-by-u quoted strings to UTF-8 would be a very radical step, even as a controllable option. To make it just blindly match source encoding would be more than radical. With internal UTF-8 ordinary-string default encoding, I think there would be a need for a plain old octet string as a different type (classical string?), maybe corresponding to what we get now with latin-1 encoding and rendering, for convenience. e.g., l'xxx' and maybe L'xxx' for the raw variant? Regards, Bengt Richter From eppstein at ics.uci.edu Thu Mar 7 12:26:34 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 07 Mar 2002 09:26:34 -0800 Subject: Status of PEP's? References: Message-ID: In article , "Bjorn Pettersen" wrote: > This surely doesn't have to be true. The for loop implicitly calls > iter(seq) to get an iterator, and the if statement first tries to call > contains when faced with an 'in' test. It's trivial to implement a > contains method for type int that preserves the orthogonality. > You're right though that the PEP should probably say whether it also > proposes to implement contains for type int. It doesn't have to -- x in y will fall back on __iter__ if it doesn't find a contains, won't it? Of course implementing a matching contains method would be more efficient, if we wanted to actually encourage x in integer tests. From Answer.via.news.please.prikryl at skil.nospam.cz Wed Mar 27 05:54:52 2002 From: Answer.via.news.please.prikryl at skil.nospam.cz (Petr Prikryl) Date: Wed, 27 Mar 2002 11:54:52 +0100 Subject: Newbie: What the 'PEP' means? Message-ID: Hi, Just curious -- what the acronym PEP with a number means? Thanks, Petr P.S.: RTFM expected, but anyway ;-) -- Petr Prikryl (prikrylp at skil dot cz) From maurelius01 at hotmail.com Thu Mar 21 18:08:58 2002 From: maurelius01 at hotmail.com (Marc) Date: Thu, 21 Mar 2002 18:08:58 -0500 Subject: mutlifile inheritance problem References: <9896e047.0203211303.741f695a@posting.google.com> Message-ID: <3C9A680A.F00216D2@hotmail.com> Aahz wrote: > > In article <9896e047.0203211303.741f695a at posting.google.com>, > Marc wrote: > > > >************************ > >file cbase01.py: > > > >class CBase: > > def __init__(self): > > self.cclass = None > > print "cbase" > > > >class CImStream(CBase): > > def __init(self): > > CBase.__init__(self) > > print "CImStream" > > > >************************* > >in file wrappers_A01.py: > > > >import cbase01 > >reload(cbase01) > > > >class ImStream_SavedBitmaps(cbase01.CImStream): > > def __init__(self): > > cbase.CImStream.__init__(self) > > print "SavedBitmaps" > > Try: > > def __init__(self): > cbase01.CImStream.__init__(self) > > Why are you using reload(), anyway? > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "We should forget about small efficiencies, about 97% of the time. > Premature optimization is the root of all evil." --Knuth Oops. That was a typo, but the same problem still exists when I fix it. (Originally, I had the line cbase = cbase01 in there but I took it out before posting. Then when I reran the program it still worked because cbase was still loaded from the previous run.) I have the reload in there because I'm developing this program now and I want to be able to change different files without tracking down all of the dependencies each time. Is there another way? Is there a reason not to have it in? I do think that it's part of the problem, because the program works if I remove it. But I have no idea why I must remove it, or what I'm doing wrong here that makes reload a problem. So here is my basic question: should I be able to inherit class from another file. The docs has the statement: """"There is a simple way to call the base class method directly: just call "BaseClassName.methodname(self, arguments)". This is occasionally useful to clients as well. (Note that this only works if the base class is defined or imported directly in the global scope.)""" Does this mean the inherited class must be in the same file if I'm to directly call a base class member? Or am I just hungup in some problem with "reload". From jon+usenet at unequivocal.co.uk Wed Mar 13 20:20:20 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 14 Mar 2002 01:20:20 -0000 Subject: Another socket/thread question References: <3C8FA777.8A5B07D1@accessforall.nl> <7934d084.0203131616.488b4ace@posting.google.com> Message-ID: In article <7934d084.0203131616.488b4ace at posting.google.com>, Andrae Muys wrote: >> When you close the socket from another thread or by the server, >> the pending socket.recv() should terminate with some error condition. >> It's best to test both situations, however. > > Far cleaner to open a control pipe to the thread and have the thread > wait on both the socket and the pipe. Why is that cleaner? Closing the socket from another thread and expecting that to terminate the recv() should be fine. On the other hand, I have had problems with that scenario before due to buggy operating systems. I fixed it by select()ing on that socket (and only that socket) before reading from it. From pobrien at orbtech.com Thu Mar 28 10:21:06 2002 From: pobrien at orbtech.com (Patrick K. O'Brien) Date: Thu, 28 Mar 2002 15:21:06 GMT Subject: interactive python shell References: Message-ID: PyCrust does this. It is an embeddable Python shell and namespace viewer written in Python using the wxPython gui toolkit. It now ships with wxPython, but the version in CVS is more current and includes lots of unit tests and subtle enhancements (some not so subtle as well). You can find it here: http://sourceforge.net/projects/pycrust There are a few projects that I know of using PyCrust in the way you describe (it can also be used standalone). The most prominent is PythonCard. http://pythoncard.sourceforge.net/ At the bottom of this page (http://pythoncard.sourceforge.net/layouteditor.html) you can see screenshots of the namespace viewer and the shell in action in the PythonCard environment. All PythonCard applications have access to a variety of runtime tools, including PyCrust. Now, here is the part that should interest you the most. When I created PyCrust, I wanted it to be as flexible and extensible as possible. So all the routines that depend on wxPython are in separate modules from those rountines that don't, and the dependencies have been kept to a minimum. That means you could borrow half the existing code and simply add the PyQt interface on top. Or at least mine the code for ideas. Let me know if you have any interest in this. -- Patrick K. O'Brien Orbtech "ian reinhart geiser" wrote in message news:mailman.1017254623.8656.python-list at python.org... > > Greetings > I have an python application and I would like to provide a "console" in the > application where users can have an interactive session with python that has > all of the applications enviroment. This is for debugging the system in real > time. > > Is there an easy way to do this? All it needs to do is execute commands and > return data. I am using PyQt for my GUI, so it would be cool to fit into > there, but I can get away with a input line and a display view if that is > easier. This is not for production, only to make a more useful debug tool. > > TIA > > - -ian reinhart geiser From jschmitt at ati.com Fri Mar 8 19:46:27 2002 From: jschmitt at ati.com (John Schmitt) Date: Fri, 8 Mar 2002 16:46:27 -0800 Subject: Is current integer for-loop syntax a wart? Message-ID: > -----Original Message----- > From: Cromwell, Jeremy [mailto:jcromwell at ciena.com] > Sent: Friday, March 08, 2002 10:26 AM > To: 'Python List' > Cc: 'David Eppstein'; 'James_Althoff at i2.com' > Subject: Is current integer for-loop syntax a wart? [...] > -Not a wart > This is the most pythonic way to write an integer for loop. > I would oppose > almost any change. [...] Definitely NOT a wart. > -----Original Message----- > From: Michael Chermside [mailto:mcherm at destiny.com] > Sent: Wednesday, March 06, 2002 5:39 AM > To: python-list > Subject: Re: Status of PEP's? > > > Not that my opinion means anything, but I'll go ahead and > express it anyhow. > > 1) I think that "for i in range(len(items)):" is awkward, annoying, > and detracts from Python. There should be a better way. Is it? Other people have said things to that effect too. To me it looks straightforward, unambiguous and explicit. I fail to see anything awkward or annoying about it. 'Awkward' and 'annoying' sound like aesthetic issues to me. I have yet to see any proposed syntax that is more obvious, or has more generality, or has fewer restrictions. The proposal should improve at *least one* of these in order to be adopted by the community. John -------------- next part -------------- An HTML attachment was scrubbed... URL: From db3l at fitlinxx.com Thu Mar 28 21:22:36 2002 From: db3l at fitlinxx.com (David Bolen) Date: 28 Mar 2002 21:22:36 -0500 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: philh at comuno.freeserve.co.uk (phil hunt) writes: > Correct. IMO "try to do something sensible" should be the default. No - "do something sensible" (read "do what the programmer intended where different programmers intend different things and the language is supposed to somehow guess which is right") is more along the line of what Perl attempts (and quite well in many cases). It's a valid approach, but doesn't fit with Pythons approach to things. > But 9 times out of 10, you'll want to use a default of 0. Only in cases where the dictionary entry is a counter which will be incremented, which is certainly far less than 90% of the time in my code. Remember also that this sort of rule can rear up and bite you in some complex expression sometime where it wasn't as "sensible" what the default behavior should be and not having the dictionary key in place was really an error that was then hidden from view until it causes a subtle problem at some later point in time. Others have also pointed out ways (including some built-in default approaches with Python 2.2's dictionary class) that you can provide such support yourself as needed. It doesn't belong in the base behavior. > Having to explicitly state things like this is a sign of low > levelnmess in a lang. Next you'll be arguing that explicit storage > management is a good thing.... :-) Totally different things. I think we can both agree on what the semantics are of obtaining storage for an object and releasing it when the object is done. But this has to do with locating an object - you want Python to "guess" at what I really wanted to get back when I asked for a non-existent dictionary entry. I don't want it to guess. Nothing to do with high level versus low level. > I have never had maintainability problems with the other way round. That need not extrapolate to a general rule. Personally I found that this sort of approach works well for small quick scripts where I really just want the answer and can play fast and loose with the details of the operations I am detailing, but breaks down over time and size. You may not agree, but that's why there are other languages to choose from that do take your preferred approach by default :-) -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From fredrik at pythonware.com Tue Mar 12 14:25:14 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Mar 2002 19:25:14 GMT Subject: Can we use print to print to more than sys.stdout? References: <3C8E441E.4D64C8DA@impathnetworks.com> Message-ID: Pierre Rouleau wrote: > #1) Is it possible to change print behavior to make it print to several > streams? class Tee: def __init__(self, *streams): self.streams = streams def write(self, text): for stream in self.streams: stream.write(text) sys.stdout = Tee(sys.stdout, open("some.file", "w"), ...) From mnations at airmail.net Sat Mar 30 13:41:55 2002 From: mnations at airmail.net (Marc) Date: 30 Mar 2002 10:41:55 -0800 Subject: Stopping a thread from an imported file References: <4378fa6f.0203290918.21be5409@posting.google.com> Message-ID: <4378fa6f.0203301041.3085aec9@posting.google.com> One more thing that I've found. When I take the external file and simply import it into the main file, I have the same problem. So apparently the problem is not with the external file but with the way the application is viewing the threads. I have debug statements throughout telling me when the thread isActive or not active. Right before I make the second call it shows me that the thread is not active. Yet when I try to restart the thread, the error comes back that it's already started. Here is the error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python22\lib\lib-tk\Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "threadocn.py", line 46, in validation self.go_thread() File "threadocn.py", line 49, in go_thread self.thread1.start() File "C:\Python22\lib\threading.py", line 384, in start assert not self.__started, "thread already started" AssertionError: thread already started Thanks, Marc mnations at airmail.net (Marc) wrote in message news:<4378fa6f.0203290918.21be5409 at posting.google.com>... > Hi, > > I am writing an application that has a front end Tkinter GUI and a > back end process. The back end process is being imported into the GUI, > which acts as the main thread in the program. When the 'GO' button is > clicked, the GUI starts a thread which calls a function that sends > control to the back end. > > The problem is that when this function has ended, the thread does not > die. So when the button is clicked to start the application again, it > won't start because it thinks the thread is still active. > > I have another thread within the GUI application that simply keeps > track of elapsed time. I don't have the same problem with this thread > which actually restarts every time the button is clicked. That, to me, > is even more confusing, since I know that thread is still running. And > since my experience with threads is limited, I'm simply going based on > what works and what doesn't to get this program working, and I can't > reason out what I've seen. > > Which leads me to two questions: > 1) When a function in an imported file completes, how does the thread > in the main file know to stop. > 2) If you can't restart a thread while it is active (which is the > error I receive in the first thread) then how can the second thread > simply restart when it is called again. > > Here's the relevant code: > > class GuiPart: > def __init__(self, master, endCommand, thread1, thread2): > self.endCommand = endCommand > self.thread1 = thread1 > self.thread2 = thread2 > > self.master = master > self.mainFrame = Frame(master) > > self.mainWindow = Frame(self.mainFrame) > > self.mainFrame.pack() > self.mainFrame.master.title("Running OCN cards") > self.mainWindow.pack() > self.createWidgets() > > def validation(self): > self.startTime = time.time() > flag = 0 > > flag = self.validateIP( self.ipaddr.get() ) > validOcn = self.var.get() > if validOcn == '': > showerror(title='Invalid OCN',message='Please select an OCN > Type') > flag = 0 > else: > flag = flag * 1 > > if flag: > self.go_thread() > > def go_thread(self): > self.thread1.setDaemon(1) > self.thread2.setDaemon(2) > self.thread1.start() > self.thread2.start() > > <...snip...> > class ThreadedClient: > def __init__(self, master): > > self.master = master > self.ok = 1 > self.thread1 = Thread(target = self.ocnRun) > self.thread2 = Thread(target = self.elapsedTime) > self.gui = GuiPart(master, self.endApplication, self.thread1, > self.thread2) > > self.periodicCall() > > def periodicCall(self): > if not self.ok: > #os._exit(0) > sys.exit(0) > self.master.after(100, self.periodicCall) > > def ocnRun(self): > print "In ocnRun" > counter, total = 0, 0 > for testgroup, titles, groupRow, groupCol in self.gui.testGroups: > for module, row, col, status, color in testgroup: > modFlag = getattr(self.gui.modVar, module).get() > total = modFlag * pow( 2, counter ) + total > counter = counter + 1 > > self.gui.slot = self.gui.list.curselection() > printAll( self.gui.ipaddr.get(), self.gui.var.get(), > self.gui.list.get(self.gui.slot), total, self.gui.port.get(), > self.gui.filename_field.get(), self.gui.password.get(), > self.gui.debug_field.get() , self.gui.debugVar.get(), > self.gui, self.gui.iterations.get() ) > > def elapsedTime(self): > curTime = time.time() > eTime = curTime - self.gui.startTime > > hours = str( int(eTime / 3600) ) > mins = str( int(eTime / 60) ) > secs = str( int(eTime) ) > > if atoi(hours) < 10: > hours = '0' + hours > if atoi(mins) < 10: > mins = '0' + mins > if atoi(secs) < 10: > secs = '0' + secs > > elapsedTime = hours + ':' + mins + ':' + secs > self.gui.elapsTime.insert(END, elapsedTime) > self.gui.master.after(1000, self.elapsedTime) > > def endApplication(self): > self.ok = 0 > > """ Begin Main Processing """ > root=Tk() > client = ThreadedClient(root) > root.mainloop() > > > > The first thread calls ocnRun which calls a function from an imported > file. Somehow I need to tell ocnRun that PrintAll has stopped. But I > assumed that would simply happen when PrintAll ran to completion. > > Anyway, I think that's all the relevant information. I've read as much > stuff on threads from this newsgroup and other resources as I could > find, but still can't find the answer. Any help would be appreciated. > > Thanks ahead of time, > Marc From imcmeans at home.com Sun Mar 17 04:23:39 2002 From: imcmeans at home.com (Ian McMeans) Date: Sun, 17 Mar 2002 09:23:39 GMT Subject: mixing regular expression References: <3C943641.CD0086B3@engcorp.com> Message-ID: my last message didn't get through, so I'm trying this again. Am I doing something wrong? "Peter Hansen" wrote in message news:3C943641.CD0086B3 at engcorp.com... > Ian McMeans wrote: > > > > How should go I about nesting regular expressions in python? > > > > I want one huge regular expression to be composed of a bunch of others - is > > there some way I can include a regular expression inside another? > > > > Or should I do it with strings - just save each regular expression's string, > > and then compile each combination separately? > > > > What I mean is this: > > foo = re.compile("someregexcode") > > bar = re.compile("moreregexcode") > > > > big = re.compile("foo|bar") > > > > is that possible at all? To combine regular expression objects? Or do you > > suggest that I just make strings for foo and bar, and then compile the > > combined strings into big? > > It seems to me you need to explain whether you want them concatenated > (in which case can't you just join the pattern strings?), or ORed > together (similar to the foo|bar case you give above?), or "nested" > (which to me implies some kind of hierarchy) or maybe just applied > sequentially (in which case just do that?). > > -Peter Yeah, I think I'll end up joining the pattern strings. What I wanted to do was create a new regular expression using the regular expressions that I've already made, without doing it via string concatenation -- which, in hindsight, isn't actually that hard to do. Ideally, in my example above, foo = re.compile("someregexcode") bar = re.compile("moreregexcode") big = re.compile("foo|bar") would be equivalent to big = re.compile("(someregexcode)|(moreregexcode)") I wanted to do it that way so that I could make one regex at a time, test it, and then include it in the larger expression. From mlh at vier.idi.ntnu.no Wed Mar 20 22:48:33 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 21 Mar 2002 03:48:33 +0000 (UTC) Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: In article , Michael Hudson wrote: [...] >Even in it's current state, the distutils package is an amazing piece >of work. I think people forget this sometimes. Indeed -- I agree. It is absolutely wonderful. I didn't mean to imply otherwise. >Cheers, >M. -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From grante at visi.com Tue Mar 26 12:10:10 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Mar 2002 17:10:10 GMT Subject: Deeply embedded Python still alive? Message-ID: The link I have for the Deeply Embedded Python port has been broken for several months now. Anybody know what happened to that project? -- Grant Edwards grante Yow! I wish I was a at sex-starved manicurist visi.com found dead in the Bronx!! From dgrisby at uk.research.att.com Mon Mar 18 06:23:48 2002 From: dgrisby at uk.research.att.com (Duncan Grisby) Date: 18 Mar 2002 11:23:48 GMT Subject: Python + Omni CORBA libraries link References: <3C95AF61.5D25C8CD@lfpt.rwth-aachen.de> <3C95C24A.D2B5D92F@lfpt.rwth-aachen.de> Message-ID: In article <3C95C24A.D2B5D92F at lfpt.rwth-aachen.de>, Viatcheslav Kulikov RWTH Aachen wrote: >> >ImportError: DLL load failed: Das angegebene Modul wurde nicht gefunden. >> >> Can you translate that error please? > >"The requested module was not found" (sorry, an OS is German) That probably means that the main omniORB DLL can't be found. Make sure the omniORB bin\x86_win32 directory is on your path. >Well, as I am quite new to the Python, I can't give the exact version of the >package, but the compiler shows version 1.0. That's the version of the IDL compiler, not omniORBpy. >Also, all files of the package are dated 21-06-2001 as the latest. > >The module CORBA.py from the package shows the following ID: > ># $Id: CORBA.py,v 1.27.2.3 2001/05/17 14:05:01 dpg1 Exp $ That is from omniORBpy 1.4. The simple way to tell is that the omniORBpy directory has an empty file called THIS_IS_OMNIORBPY_1_4 in it. Cheers, Duncan. -- -- Duncan Grisby \ Research Engineer -- -- AT&T Laboratories Cambridge -- -- http://www.uk.research.att.com/~dpg1 -- From edream at tds.net Mon Mar 4 19:28:50 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 05 Mar 2002 00:28:50 GMT Subject: Reorganizing python.org (was: Why isn't pychecker...) References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> <3C841006.634D0059@tds.net> Message-ID: <3C84113F.AA15F841@tds.net> Oops, I meant to say: http://python.org/doc/current/lib/lib.html instead of C:\Python22\Doc\lib\lib.htm. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From ffjhenon at club-internet.fr Thu Mar 14 17:01:48 2002 From: ffjhenon at club-internet.fr (Fabien Henon) Date: Thu, 14 Mar 2002 23:01:48 +0100 Subject: Scrolling line number Tkinter References: <3C8E84AA.4070306@club-internet.fr> Message-ID: <3C911DCC.5010605@club-internet.fr> Martin Franklin wrote: > Fabien Henon wrote: > > >>I am currently writing a text editor for POV-RAY under Windows using >>Tkinter. It should be working as well with linux and Mac. >> >>To display the line numbers, I use a scrolling column at the left of the >>editor with a text box. >> > > Can you please explain what a scrollng column is? Perhaps if you post some > code we could help some more. > > > >>I also linked the main text editor with a scroll. >> >>My problem is that the text editor is well linked to the scroll, but the >>line numbers do not move when I use the arrow cursors. >> >>Thanks for any help >> >>Fabien >> > > It sounds like you need to link both the scrolled column and text box to > the same scrollbar.... > What I mean by scrolling column is a column in which are displayed all the line number of the text. I want this column of lines to scroll with the edited text. cheers. From shalehperry at attbi.com Sat Mar 9 16:50:43 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 09 Mar 2002 13:50:43 -0800 (PST) Subject: Newbie question In-Reply-To: Message-ID: On 09-Mar-2002 Nick wrote: > How do you get the ordinal value (ASCII) of a character? For example, to > make a ROT13 program. > >>> ord('A') 65 From jp_reed at yahoo.com Wed Mar 27 17:59:58 2002 From: jp_reed at yahoo.com (Jeremy Reed) Date: 27 Mar 2002 14:59:58 -0800 Subject: DSN question Message-ID: <13a0323e.0203271459.14905cde@posting.google.com> Is there a way to programmatically create a DSN? I'm trying to create a program that connects to a MS SQL database using the mxODBC package. However, I don't necessarily want to subject the users of the program to the task of manually creating a DSN. It seems to me that there should be some way to do it programmatically, but I haven't been able to locate and documentation on it. Any information relating to this subject would be quite helpful. Thanks and best regards, Jeremy From max at alcyone.com Thu Mar 7 20:48:31 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 07 Mar 2002 17:48:31 -0800 Subject: List of Dictionaries References: <14dc40e2.0203071559.5e3d4550@posting.google.com> Message-ID: <3C88186F.6BEFA3D2@alcyone.com> Lenny Self wrote: > When I add the first dictionary element to the list all is well. When > I add the second element to the list both the first and second element > reference the second dictionary that was added. The behavior > continues whenever I add an element. So, if I add, say 50 > dictionaries, all of the listes elements reference the last dictionary > I added. > > I don't have the code with me right now, but I can assure you it is > easy as this: The problem you're having crucially depends on you doing something wrong in the details of your implementation. You're going to have to show us the _exact_ code that is causing this problem or it will be impossible to help you. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From cuiod-tec at web.de Fri Mar 8 02:31:22 2002 From: cuiod-tec at web.de (Jens Gelhaar) Date: 7 Mar 2002 23:31:22 -0800 Subject: need something like __init__ in classes __classinit__ Message-ID: Hi, I tried it very hard, but no success. What I trying to do is class test: def __classinit__(cls): << do something with the new class >> class testsub(test): pass Every time, when I inherit from class test, the function __classinit__ should be called. Several month ego, some one gave my the hint to deal with the new type (metaclass) concept from python 2.2. That was ok and helps me further. But now I get stucked again. I have to inherit from Persistent (ZODB). And this class does not work together with metaclass concept of python 2.2. class metaclass(type): def __new__(cls): cls.__classinit__(...) class primary(Persistent): __metaclass__=metaclass def __classinit__(cls): << do something ...> I get a error message, that I can not inherit from to different metaclasses. Now, I had the idea to do it in a complete different way. Lets changed it in the source and call each function "__classinit__" when a new class is created. But it worked for "classic" classes, not for inherited ones from "object" or "Persistent" of ZODB. Now my question? Where to implement such a call. I did it in "classobject.c" file, but without success. Beside, I would find it very useful as a general behaviour. There is "__init__" for a new instance, why not a "__classinit__" for a new class. Here what i tried: static PyObject * class_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *name, *bases, *dict; PyClassObject *op; PyClassObject *dummy; PyObject *classinit, *res; static char *kwlist[] = {"name", "bases", "dict", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist, &name, &bases, &dict)) return NULL; op = (PyClassObject *)PyClass_New(bases, dict, name); !!!!!!!!!!!!!!! NEW !!!!!!!!!!!!!!!!!!! if (classinitstr == NULL) classinitstr=PyString_InternFromString("__classinit__"); if (op != NULL && PyClass_Check(op)) { classinit = class_lookup(op, classinitstr, &dummy); if ((classinit != NULL)) { // && PyMethod_Check(classinit)) { res=PyEval_CallMethod((PyObject *)op, "__classinit__", "(O)", op); } } !!!!!!!!!!!!!!! END NEW !!!!!!!!!!!!!!!!!!!!!!!!1111 return (PyObject *)op; } From gcordova at hebmex.com Fri Mar 29 17:09:00 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Fri, 29 Mar 2002 16:09:00 -0600 Subject: Help with POST request. Message-ID: Hello all. I'm having some trouble using the BaseHTTPServer.BaseHTTPRequestHandler class. It says in it's internal documentation, that to process a GET or a POST request (or HEAD, or whatever), just define a do_ method in a derived class, and let'r rip. Well, I'm having some trouble accepting POST requests. GET requests work like a charm, really nice and quick, but POST requests stay hung and I have to kill them from the browser. I'm surely doing something wrong, but I really don't know how. Here's the script I'm playing with: =========================================================== import BaseHTTPServer SIMPLE_WEB_FORM = """ ... a little web page in HTML ...""" class TestHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def test_response(self): # Always so positive. self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): self.test_response() self.wfile.write(SIMPLE_WEB_FORM) def do_POST(self): self.test_response() print "-" * 60 print self.rfile.read() print "-" * 60 self.wfile.write(SIMPLE_WEB_FORM) BaseHTTPServer.test(TestHTTPRequestHandler, BaseHTTPServer.HTTPServer) =========================================================== OK, the problem is I can't ever see what's being sent via POST, it hangs when reading from the rfile object. I'd appreciate any and all comments. -- Gustavo C?rdova Avila > gcordova at sismex.com ? 8351-3861 | 8351-3862 From quinn at barf.ugcs.caltech.edu Thu Mar 14 14:57:44 2002 From: quinn at barf.ugcs.caltech.edu (Quinn Dunkan) Date: 14 Mar 2002 19:57:44 GMT Subject: Why I think range is a wart. References: <873cz44ea8.fsf@bunty.ruud.org> Message-ID: On 13 Mar 2002 11:34:55 -0500, ruud de rooij <*@spam.ruud.org> wrote: >perhaps lists should support .keys() and .items() for those operations >(analogous to dictionaries). This would also make writing polymorphic code easier. I sometimes write methods that work on both dicts and lists and find myself doing stuff like if hasatttr(o, 'keys'): ks = o.keys() else: ks = range(len(o)) From gmuller at worldonline.nl Sun Mar 31 14:28:26 2002 From: gmuller at worldonline.nl (GerritM) Date: Sun, 31 Mar 2002 21:28:26 +0200 Subject: Most important extensions? References: Message-ID: "Aahz" schreef in bericht news:a8614l$dfa$1 at panix1.panix.com... <...snip...> > Please vote for no more than three. win32all HTMLgen regards Gerrit From emile at fenx.com Fri Mar 29 09:36:14 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 29 Mar 2002 06:36:14 -0800 Subject: number of lines in a file References: Message-ID: Joseph Youssef > hello, I am nwe to Python and I'm trying to write this > script but I need it to check how many lines is in > the file and I don't know how so I'm hoping someone > could tell me. len(open('/path/and/filename').readlines()) -- Emile van Sebille emile at fenx.com --------- From claird at starbase.neosoft.com Tue Mar 19 17:02:07 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 19 Mar 2002 16:02:07 -0600 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> Message-ID: In article , phil hunt wrote: >On Tue, 19 Mar 2002 06:33:48 GMT, Ahmed Moustafa wrote: >>1. Where can I find an unbiased comparison between Java and Python? > >Python is easier to write programs in than Java, but they might run >slower. . . . Or faster. And it's more difficult to write some programs in Python than Java. But, yes, for the most part, Python's friendlier, and less concerned with performance in the way Java is, in some senses which can be made objective, but are barely worth the trouble to do so. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jeff at ccvcorp.com Mon Mar 25 19:17:38 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 25 Mar 2002 16:17:38 -0800 Subject: wxPython and wxFlexGridSizer problem References: Message-ID: <3C9FBE22.A72B4A27@ccvcorp.com> Uwe Schmitt wrote: > [ This is a repost of the following article: ] > [ From: Uwe Schmitt ] > [ Subject: wxPython and wxFlexGridSizer problem ] > [ Newsgroups: comp.soft-sys.wxwindows ] > [ Message-ID: ] > > Hi, > > when I try the following function on a linux machine I get an input > mask consisting of a label and an input field. If i run it under > Windows 2k, the label does not appear, and the inputfield is rendered > into the first field of the grid... > > Here is the procedure: > > def testtt(window): > > basicSizer = wxBoxSizer(wxVERTICAL) > > gridSizer= wxFlexGridSizer(cols=2) > > t=wxStaticText(window, -1, "Eingabe:") > gridSizer.Add(t, wxALL | wxALIGN_RIGHT) > tt=wxTextCtrl(window, -1, "", size=wxSize(100,-1)) > gridSizer.Add(tt, wxALL |wxALIGN_LEFT) > > gridSizer.SetSizeHints(window) > gridSizer.Fit(window) > window.SetSizer(gridSizer) > window.SetAutoLayout(true) > > window.ShowModal() Are you sure that you want to use ShowModal()?? How are you setting up your window? This function looks okay to me, as far as it goes, but it's hard to say what might be going on if we don't know where window is coming from. I presume that it's a wxDialog of some sort? If so, why aren't you subclassing wxDialog and putting this code in your __init__(), then calling ShowModal() from the function that creates the dialog? (You might also have better luck getting answers for this, if you ask on the wxpython-users mailing list -- see wxpython.org to subscribe.) Jeff Shannon Technician/Programmer Credit International From claird at starbase.neosoft.com Mon Mar 18 07:55:01 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 18 Mar 2002 06:55:01 -0600 Subject: why python for the academe? References: <3C947318.B0E80317@kfunigraz.ac.at> Message-ID: <0D3D6E1F7E9F9F51.ADC87E3B3D4C8072.F8EC494A26A0B22B@lp.airnews.net> In article <3C947318.B0E80317 at kfunigraz.ac.at>, Siegfried Gonzi wrote: >huck wrote: >> >> hello all, >> >> i've been lurking for a while and am amused at how >> many people in the list here use python for scientific >> computing. why not matlab (or octave or scilab or whatever)? . [lots of points I'll leave to stand on their own] . . >Python with the right combination (numerical libraries and plotting >libraries) is much more flexible than lets say Matlab or IDL. What you >buy with Matlab is a huge repository of pre-compiled code. Scientist >normally do not get paid for programming (curiosity: but they do >programming all the time) and a great many are not very well educated >how to glue together libraries. Personally, I switched to Windows (even . . . >buy my study and not expect to get it for free. Free software is not all >that good as a great many of people want to make believe us. > >S. Gonzi Commercial software is not as good as its marketers try to make people believe. Software generally is ... of limited quality. Yes, people on this list-newsgroup use Python to do scientific programming. If comp.lang.awk can discuss matrix inversion in awk ...! Mr. Gonzi's characterization is apt. While Matlab's rather wonderful stuff, it's not designed as a pro- gramming system. It offers lots of "canned stuff", but isn't satisfying as a programming language. Abstraction of Matlab applications is obscure. Python is a beautiful programming language, and sup- ports far more sophisticated design. Python also "glues" better. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From yoast at whu.edu.cn Sun Mar 24 07:27:57 2002 From: yoast at whu.edu.cn (yoast) Date: Sun, 24 Mar 2002 20:27:57 +0800 Subject: about popen and gnuplot Message-ID: <200203241222.UAA20782@email.whu.edu.cn> dear all, i have a question about popen and gnuplot. i got an example from ASPN, used to drive gnuplot with python on __win32___ platform. the code looks like below. import os f=os.popen('d:/xxx/pgnuplot.exe', 'w') print >>f, "p sin(x)" f.flush() i can see the gnuplot's interactive window, but can't see the plot window. why? what should be done to make it work? i see the code of gnuplot.py (a sourceforge project), the code in that script is absolutely same as mine :( best regards, yoast at whu.edu.cn 3.24 From deathtospam43423 at altavista.com Tue Mar 5 02:45:20 2002 From: deathtospam43423 at altavista.com (A.Newby) Date: 5 Mar 2002 07:45:20 GMT Subject: bsddb for beginners? Message-ID: I want to get into databases, but most of the tuts around seem to be over my head. For instance, looking through the standard Python documentation for bsddb module, 7.12 bsddb -- Interface to Berkeley DB library, doesn't really explain what all the syntax is for. For instance, this example ...... >>> import bsddb >>> db = bsddb.btopen('spam.db', 'c') >>> for i in range(10): db['%d'%i] = '%d'% (i*i) ....... obviously creates a database file which behaves a dictionary. If I type >>>db.keys() ... I get a complete a list of the dictionary's keys (0 - 9). But why? And how do I store values in those keys? What does the "%" symbol mean, and what's it used for? So what homework do I need to do to understand this stuff? Also, do I take it that the Berkely System comes with Python 2.2, and therefore I don't need to download anything else? Or is bsddb merely an interface for the Berkely System? -- cdewin at dingoblue.net.au From gerson.kurz at t-online.de Fri Mar 22 14:40:26 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 22 Mar 2002 19:40:26 GMT Subject: yenc encoding? Message-ID: <3c9b8743.23437968@news.t-online.de> Does someone work on a yenc-encoder/decoder for python? Both "base64" and "binascii" are there in the python standard library, after all. Just wondering: Should an implementation for a new encoding follow the base64-model (that is, have four funcs encode, encodes, decode, decodes) or the binascii-modell (a2b_yenc,b2a_yenc) or something totally different altogether? From dreed at capital.edu Tue Mar 26 19:33:33 2002 From: dreed at capital.edu (Dave Reed) Date: Tue, 26 Mar 2002 19:33:33 -0500 Subject: python on Sharp Zaurus In-Reply-To: <7xadsuan0p.fsf@ruckus.brouhaha.com> (message from Paul Rubin on 26 Mar 2002 16:10:30 -0800) References: <7xadsuan0p.fsf@ruckus.brouhaha.com> Message-ID: <200203270033.g2R0XXN20342@localhost.localdomain> > From: Paul Rubin > > Dave Reed writes: > > > Does anyone know if Python runs on the new Sharp Zaurus? > > > > http://www.idg.net/go.cgi?id=656429 > > Yes, it does. Ok, I found it - the link on the python.org web site is wrong. It's now at: http://www.riverbankcomputing.co.uk/zaurus/index.php Dave From fedor at mailandnews.com Wed Mar 27 16:41:26 2002 From: fedor at mailandnews.com (Fedor Baart) Date: Wed, 27 Mar 2002 22:41:26 +0100 Subject: Very small zlib/svg problem Message-ID: I am trying to convert a SVG file to a SVGZ file which is the "gzip"compressed version of the SVG file. (SVG is a XML based vector graphics format (see www.w3c.org)) I use the zlib library to compress the svg file. The problem is that when I try to view the SVGZ file with adobe SVG viewer 3.0 or with the Batik SVG browser that it doesn't render and is not able to read the SVGZ file as SVG. I am assuming I am not using the zlib library correctly. I use the following code: import zlib file('c:/test.svgz','w').write(zlib.compress(file('c:/test.svg').read())) #read the svg file c:\test.svg, compress it using zlib and write it to c:\test.svgz Opening the test.svgz using a svg compatible browser is supposed to display the SVG drawing. But it displays nothing. The Batik browser displays an error: Character conversion error: "Unconvertible UTF-8 character beginning with 0x9c" (line number may be too low). Any help would be greatly appreciated. Thanks, Fedor Baart For those who like svg: www2.sfk.nl/svg ---> a python svg module which I created. From python at rcn.com Mon Mar 11 15:00:12 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 11 Mar 2002 15:00:12 -0500 Subject: [ANN] PEP 279 version 1.7 Message-ID: PEP 279 -- Enhanced Generators has been updated: http://python.sourceforge.net/peps/pep-0279.html Comments are invited on the revised PEP. The changes were driven by comments from GvR, from the authors of PEP 255, and from members of the Py-Dev maillist. There changes from version 1.6 to version 1.7 were the addition of comments from Magnus Lie Hetland and the repair a typo in the code. The principal changes from version 1.5 to version 1.6 are: 1. Rationale section focused on generator usage instead of lazy evaluation. 2. The proposal for four builtins has been reduced to one. Xzip, xfilter, and xmap are retracted. Expanded the discussion of the remaining proposed builtin, indexed(). 3. All sections expanded to include comments received from GvR and the PEP 255 authors (the experts on the existing generator implementation). 4. Proposal for generator exception passing moved up one section. 5. Proposal for generator parameter passing listed as deferred -- everyone thinks this may be a viable idea but it doesn't have a chance in the near-term. 6. The restartability discussion has been deleted -- Guido thought it was evil. Raymond Hettinger From db3l at fitlinxx.com Fri Mar 1 18:31:18 2002 From: db3l at fitlinxx.com (David Bolen) Date: 01 Mar 2002 18:31:18 -0500 Subject: Older Python bug entries on SourceForge Message-ID: I was trying to look up an old bug entry on SourceForge (based on a bug number from some CVS log comments) and can't seem to pull it up. Does anyone know if SourceForge expires closed bugs after some time duration or something? Is there any archive available to view old bugs? Thanks. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From anthony at interlink.com.au Fri Mar 29 09:11:49 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Sat, 30 Mar 2002 01:11:49 +1100 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! In-Reply-To: Message from David Ascher of "Thu, 28 Mar 2002 14:40:01 -0800." <3CA39BC1.59873E78@activestate.com> Message-ID: <200203291411.g2TEBnn08738@mbuna.arbhome.com.au> >>> David Ascher wrote > Tim already spends a lot of time on installers that I for one would > rather see him spend on things that the rest of us can't do =). .. like making floating point work properly on every possible combination of OS, CPU, compiler and libc/libm. particularly-the-ones-he-doesn't-have-access-to-ly, Anthony -- Anthony Baxter It's never too late to have a happy childhood. From philh at comuno.freeserve.co.uk Fri Mar 15 14:05:45 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 15 Mar 2002 19:05:45 +0000 Subject: Connecting to a Gnutella-network References: Message-ID: On Fri, 15 Mar 2002 14:33:19 GMT, Thomas Weholt wrote: >Hi, > >I've looked at the Gnutella Protocol, v.0.4, and wondered about trying to >create an implementation in python. I'm a newbie when it comes to this sort >of thing, but have created several simple to complex server types of >applications using SocketServer and its friends like BaseHTTPServer etc. > >Has anybody tried to do this before? Does anybody have pointers for newbies >like me in such a project ( how to start, how to connect to nodes on a >gnutella network etc. ) I personally haven't, but there are several open-source Gnutella clients, just waiting there for you to inspect the code. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From sheershion at mailexpire.com Fri Mar 1 11:08:00 2002 From: sheershion at mailexpire.com (Robert Amesz) Date: Fri, 01 Mar 2002 16:08:00 -0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > .... >> >>However, if you are on a 9x platform, and quoting the command just >>as you want the command interpreter to see it on the command line >>doesn't work, you might just want to revert to using the short >>(non-space) version of the name. So in your example you would >>replace "program files" with "progra~1" (or whatever it may be in >>the unlikely event it's different than that). >> >>-- >>-- David > this is win2k. I have tried quoting with "", but I still seem to > be getting > > no such command C:\program etc On Win98 I've found I had to quote *and* escape the quote characters, and - sometimes - backslashes too. I'm not sure if this is also the case on Win2000, but it's worth a try. This would yield something like: '\\"c:\\\\program files\\\\dimbo\\\\bongo.exe\\\\" \\"c:\\\\program files\\\\dumbo\\\\my file.dat\\"' Horrible, I know. Somewhere in the gizzards of Python there's some double parsing of the commandline going on. This is doubly insidious on Win98 as it pipes its data through a little program called win9xpopen.exe, which chokes when argc isn't exactly 2. Well, chokes isn't the right word: it pops up a dialog box, but when called from Python this dialog is invisible... Fun, ain't it? I'm not going to tell you how long it took me to find out this little quirk. I hope it's fixed in 2.2. And yes, I did report this behaviour a while back. Robert Amesz From aahzpy at panix.com Sat Mar 23 10:19:40 2002 From: aahzpy at panix.com (Aahz) Date: 23 Mar 2002 10:19:40 -0500 Subject: Info needed on metaclasses / type-ing References: Message-ID: In article , Dimitris Garanatsios wrote: > >My question is about the "SingletonMetaClass" class. >I have tried in the past to create my own types using Python and just could >not find a way of doing that since built-in type objects' structure where >not documented. > >The "SingletonMetaClass though", as far as i can understand, please help me >with that, is doing exactly what i wanted: a new type definition. I browsed >Python's manuals to find more about the attributes and functions that are >used, but found nothing... You need to upgrade to Python 2.2 (or 2.2.1, which will be available within a month). If this is the first you've heard of 2.2, you're in for a *big* surprise. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From v at 4leads.com Mon Mar 18 12:08:54 2002 From: v at 4leads.com (=?ISO-8859-1?Q?4leads?=) Date: Mon, 18 Mar 2002 17:08:54 -0000 Subject: =?ISO-8859-1?Q?SORTCODE.COM?= Message-ID: Dear Sir/madam, SORTCODE.COM was not renewed and this domain had become available to register. Consequently, we have been approached to market this domain name that has been tracked and registered by a client. As a result, KIDS-PARTIES.COM is now available from us for IMMEDIATE transfer. We note that a search on the search engine Google.com returns 2,160,000 results for "SORT CODE" (THOUGH OF COURSE NOT ALL RESULTS ARE RELEVANT) but still, with so many companies that could benefit from this domain, along with what many would consider to be a "wholesale price", we expect to secure a quick transfer. This is a VALUABLE and HIGH PROFILE domain and we believe that this development could be of genuine interest and benefit to your operation. Please note that the domain name market is extremely solid at the moment and similar domains are currently selling on afternic.com, greatdomains.com (domain auction sites)and by domain name brokers, in some cases, for many thousands of US dollars. Please note that transfers take just 15 minutes and are extremely straightforward - absolutely NO technical knowledge required! For our client's peace of mind, we use an escrow service for all transactions and domains are ALWAYS secured by the buyer prior to us receiving any funds. We pay all fees connected with the escrow process. If you would like to use WWW.SORTCODE.COM for your online business, please contact us at your earliest convenience. We will be on hand should you require any further assistance or information. We thank you for your attention and sincerely apologise if this e-mail has not been of interest to you. Yours sincerely, Victoria Sales 4leads.com Please note: THIS IS A ONE-OFF APPROACH AND YOU WILL NOT BE CONTACTED AGAIN UNLESS YOU REQUEST FURTHER INFORMATION FROM US. YOU HAVE BEEN CAREFULLY SELECTED TO RECEIVE THIS MAIL AND IF THIS E-MAIL IS OF NO RELEVANCE TO YOUR OPERATION, PLEASE ACCEPT OUR APOLOGIES SINCE IT HAS BEEN SENT TO YOU IN ERROR. To be removed from our database, reply with "REMOVE" in the subject line. From grante at visi.com Sat Mar 9 13:41:01 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 09 Mar 2002 18:41:01 GMT Subject: Turn string into function call References: <1f5252d4.0203080545.3861adec@posting.google.com> Message-ID: In article , Aahz Maruch wrote: > In article , > Grant Edwards wrote: >> >>I think it would also be good to mention the eval() method, and >>the locals() method (and the problems with both). I started to >>write up a FAQ yesterday but didn't get very far... > > You can add that to the new FAQ entry at > http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.103.htp Will do. -- Grant Edwards grante Yow! HELLO KITTY gang at terrorizes town, family visi.com STICKERED to death! From mrboxer at kaosmic.net Wed Mar 6 16:43:45 2002 From: mrboxer at kaosmic.net (mrBoxer) Date: Wed, 6 Mar 2002 22:43:45 +0100 Subject: Beginner Message-ID: Have you experience of the book "How to think like a computer scientist - Learning with Python"? I would like to learn python and begin with reading that tutorial I found online at python site. I'm not a "strong old programmer" but I've some experience with shell, perl, elisp and C. Thanks a lot. -- mrBoxer at Kaosmic Cow From henrik.motakef at web.de Sat Mar 2 12:17:22 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 02 Mar 2002 18:17:22 +0100 Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: <868z9a6g9p.fsf@apo.hmotakef.int> mats at laplaza.org (Mats Wichmann) writes: > I'm looking for a piece of software to aid in reviewing a document > through the web - click on a paragraph tag, have the comment added > (highlighted in some way). I once found a project called OpenTheory (http://www.opentheory.org) that used a system that might be interesting for you (although it's written in Perl, IIRC). Basically, there is one "maintainer" of a text, and "project members" can add comments to every paragraph until the maintainer releases a new version of the document. Never used it myself, though. hth Henrik From skip at pobox.com Thu Mar 7 07:15:34 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 06:15:34 -0600 Subject: The language vs. the environment In-Reply-To: References: Message-ID: <15495.23014.196835.967433@12-248-41-177.client.attbi.com> Raymond> "Skip Montanaro" wrote ... >> There has been a huge amount of recent PEP activity related to >> further enhancements to the language. I think in general that if >> more of this energy was directed at the overall environment (library, >> support tools, installers, documentation, etc) we'd be better off in >> the long run. Raymond> I certainly agree that effort needs to be put into the library, Raymond> etc. Raymond> However, I would like to defend the PEP writers guild on a few Raymond> points: ... Raymond> 1. Writing a PEP is a disciplined activity that involves Raymond> completely thinking our design choices, rallying public Raymond> opinion, collecting all points of view for and against, and Raymond> documenting all of that information in a single, version Raymond> controlled, standard format document in a public place for Raymond> everyone to study, ridicule, or on extremely rare Raymond> occassions, adopt. Raymond> In other words, PEP writing is contributing to science and Raymond> is not a wasted effort even if the idea never gets adopted. No defense needed. We need PEPs related to the environment also, however. I think some (most? all?) the blood, sweat, and tears poured into recent PEPs related to what amount to relatively minor language design issues could have more profitably been devoted to PEPs related to environment issues. If the energy expended on just PEPs related to loop counters had been directed at cataloging/module distribution ideas, we'd probably have a pretty complete PEP with a fair amount of buy-in from the community by now, and maybe one or more implemented trial systems by now. Skip From skip at pobox.com Wed Mar 13 23:01:41 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 13 Mar 2002 22:01:41 -0600 Subject: Performance problem with filtering In-Reply-To: <20020314024259.GA24728@lilith.hqd-internal> References: <20020314024259.GA24728@lilith.hqd-internal> Message-ID: <15504.8357.750775.979255@12-248-41-177.client.attbi.com> gh> results = [] gh> for entry in b: gh> if entry not in a: gh> results.append(entry) gh> is terribly slow. Here's one idea using dicts. Depending on what your lists contain (sounds like filenames?) you might have to adjust things a bit to make them dict-worthy. adict = {} for fname in a: adict[fname] = 1 results = [] for fname in b: if fname not in adict: results.append(fname) or, pre-2.2: adict = {} for fname in a: adict[fname] = 1 results = [] for fname in b: if no adict.has_key(fname): results.append(fname) This at least gets your algorithm out of the O(n**2) realm. Should run a lot faster. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From laytonjb at bellsouth.net Fri Mar 29 15:55:34 2002 From: laytonjb at bellsouth.net (Jeff Layton) Date: Fri, 29 Mar 2002 15:55:34 -0500 Subject: Newbie: List of instances? References: <3CA4C09B.D9D15464@bellsouth.net> <3CA4CA27.F00B91BA@engcorp.com> Message-ID: <3CA4D4C6.4E38F192@bellsouth.net> Peter Hansen wrote: > Jeff Layton wrote: > > > > a = [] > > a[0] = Bob( 'localhost' ) > > IndexError: list assignment index out of range > > Please always cut and paste the actual traceback into the message > so we can see what the interpreter really says. (In this case > it's okay though.) I thought this was something simple, so I didn't post any code (it's really throw away code anyway). In the future I'll post all of the code and the tracebacks. > > > You can't assign to the first entry because the list is empty. > You need to append to the list, to let it grow as needed, > sort of like you tried here: > > > I also tried it this way, > > > > a = [] > > a.append = Bob('localhost') > > That won't work, because append is a method so you have to pass > the argument in brackets: > > a.append(Bob('localhost')) > > > and I get the error message: > > > > a[0] = Bob( 'localhost' ) > > IndexError: list assignment index out of range > > That's not the error message you would get from the a.append > attempt you did. That would have said this: > > >>> a.append = Bob('localhost') > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'list' object attribute 'append' is read-only You're correct. Somehow the paste didn't work. Sorry about that. > > > So always cut-and-paste errors into emails... > > -Peter From mwh at python.net Mon Mar 11 05:46:13 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 11 Mar 2002 10:46:13 GMT Subject: Anonymous attribute/property possible? References: Message-ID: bokr at oz.net (Bengt Richter) writes: > A class with an anonymous attribute/property would provide a place to put > get/set/del-triggered code. > > Use of an object with an anonymous property in an expression > or statement would result in calling the get/set methods defined. > > Thus you could write foo(bar) with the effect of foo(bar.__anonymous__) > and bar() with the effect of bar.__anonymous__() > > And bar = baz with the effect of bar.__anonymous__ = baz. > > But since __anonymous__ could be a property, you could define > methods at will (e.g., get_bar, and set_bar) and write > bar = baz with the effect bar.set_bar(baz) and > foo(bar) with the effect foo(bar.get_bar()) > > This might work nicely with an interpolated-string class. > E.g., > is = IS('The get_is anonymous property method will interpolate $variables') > print is # the reference would trigger interpolation with current values > # you could do this now, but you'd have to write "print is.some_property" > Ouch. > If you wanted to access the actual object that had an anonymous > property, you'd have to give it a named method returning self for > that purpose. > > I think this could open up a whole world of scary delights ;-) > (And ISTM without a backwards compatibility problem). Just in case the fact that this is a horrible idea doesn't put you off , how would you implement this without a fairly huge performance hit? LOAD_FAST is currently, well, fast. Cheers, M. -- While preceding your entrance with a grenade is a good tactic in Quake, it can lead to problems if attempted at work. -- C Hacking -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From jason at jorendorff.com Thu Mar 7 22:08:32 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Thu, 7 Mar 2002 21:08:32 -0600 Subject: Nested scopes: design or implementation? In-Reply-To: Message-ID: logistix writes: > Okay, now I'm confused. > > I was perfectly happy with Teddy Reedy's explaination that def is an > expression and not a declaration. > > But if I'm following you, the embedded attribute function isn't being > recompiled to bytecode each time function() is called. If the code object > is only getting created once, then why are the defaults getting > recalculated? (Grin.) Poke around with the various attributes of a function and you'll figure things out in no time. The code object is what's fixed; the bytecode and anything else that can be compiled at, er, compile-time. The rest of the function object is built at runtime when the "def" statement is executed. ## Jason Orendorff http://www.jorendorff.com/ From jeff at ccvcorp.com Tue Mar 12 13:33:17 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 12 Mar 2002 10:33:17 -0800 Subject: how to give an object as argument for a method References: Message-ID: <3C8E49ED.1C524CC1@ccvcorp.com> Marco Herrn wrote: > [snip] > > ... def sayNo(self): > > ... caller = sys._getframe(1).f_locals['self'] > this is the only line, that looks a bit ugly. It actually does the same > as when giving caller as parameter. So what can be a reason to implement > it this way? It looks much less readable to me. And I have to say I not > even understand it fully.... Actually, it does *not* do the same as giving the caller as a parameter, in general. What this does, is that it gets the intepreter's stack frame in which the current object was created. In this case, that happens to be the Egg.__init__() frame. It then searches this stack frame for a local name 'self'; if that name doesn't exist, this will throw an exception. This means that Spam can *only* be created from inside of another method which uses the self convention; you cannot create a Spam object globally or inside of a top level function. And, indeed, in the rare instances where a method uses some name other than self to represent its bound instance, this will fail as well. A metaphor would be that, instead of simply being told who your parents are, you're searching through a phone book for a name that you *think* belongs to them -- but you might have the name wrong, they might have an unlisted number, or they might not even *be* in that phone book. (Note also that even if it *does* work, it's inappropriate to call the object found the "owner" or "caller" of the current instance; it would be the *creator*, which is not necessarily the same thing at all, especially when you consider object factories and such.) In short, this is black magic. It might work, most of the time... but if you turn your back on it, it's liable to blow up on you. Use only with caution, and only when you're *sure* that you know what you're asking for. :) Jeff Shannon Technician/Programmer Credit International From James_Althoff at i2.com Fri Mar 1 18:37:09 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 15:37:09 -0800 Subject: PEP 276 (was Re: Status of PEP's?) Message-ID: [Carel Fellinger] > But even after that nice math lesson I still don't *understand* it, > you iterate over a sequence and I have a hard time seeing an integer > as a sequence. Same for a length. And I believe many would have the > same problem. You're right; apparently they do. Here's how I think of it. Iterators are really useful. When asked to do so they produce items one after another according to some meaningful plan. You can associate an iterator with anything that you think is practical and useful. So, is there any reason to associate an iterator with an integer? PEP 276 suggests that because there are times when you have the length of an indexed-collection and you want to iterate over the indices of that collection it would be convenient to associate an iterator with that "length" number. It just makes it easy and uncluttered to do for rowindex in table.rowcount: process(rowindex) That's it. You don't have to think of integer n as a sequence. You just need to remember that n can produce the iteration 0,1,2,...,n-1. Perhaps it might help to change one's perspective of "for x in y" from "for each object that is a member of y, an ordered aggregation of other things" to "for each object that is produced by the iterator associated with y" Works for me, but, clearly not everyone. :-) >Besides, I don't see the huge advantage of this compared to >`range(integer)' or `indici(sequenceORmapping)'. If you are happy with range and xrange, then PEP 276 won't appeal to you. > What about a function that accepts as argument such a collection > and then generates the indici? Much easier to explain, to understand, > to adopt. But admitted, it takes a little extra typing. > > Seriously I would like you to add something in your PEP that addresses > this simple alternative and explain why you favour yours. True, > `i in range(len(sequence))' doesn't look very pleasing, but > `i in indici(sequence)' does. And as an added bonus it's > very similar to `(i, item) in indexed(sequence)'. This has been suggested and is fine for one-dimensional, indexed-collections that are written in Python and obey the standard protocol for sequences -- specifically that they implement __len__. But how is such a function going to work for a two-dimensional Java table (accessed via Jython)? PEP 276 is more general. And doesn't preclude such a function being added, in any case. > But I do think that dismissing our point as a matter of > preference misses our point. The PEP says this: - Some feel that iterating over the sequence "0, 1, 2, ..., n-1" for an integer n is not intuitive. "for i in 5:" is considered (by some) to be "non-obvious", for example. How does that miss your point? What should it say? > looking forward to your views on meta programming though Thanks. Jim From cheewahwah at yahoo.com Sun Mar 24 10:03:00 2002 From: cheewahwah at yahoo.com (See Toh Chee Wah) Date: 24 Mar 2002 07:03:00 -0800 Subject: Need help with plotting References: <3c9cd61e.8124286@news> Message-ID: <34b75f98.0203240703.1ee03b95@posting.google.com> RPy is cool... pychart is another good one... http://www.hpl.hp.com/personal/Yasushi_Saito/pychart/ regards cheewah "Emile van Sebille" wrote in message news:... > brobbins333 at shaw.ca > > I'm new to Python and doing pretty well with it so far. > > One thing that has me stumped is finding an "easy" way, > > or any way, for that matter, to plot simple graphs. > > > I was really impressed by RPy > > http://www.cmat.edu.uy/~walterm/rpy > > Check out Tim Churches' example at > > http://gestalt-system.sourceforge.net/rpy_demo.html From susan at mars.provis.com Fri Mar 29 15:09:17 2002 From: susan at mars.provis.com (Susan Williams) Date: Fri, 29 Mar 2002 14:09:17 -0600 (CST) Subject: Newbie: List of instances? Message-ID: <200203292009.g2TK9H304897@mars.provis.com> >Hello, > > I'm still learning Python and I'm playing around with some >code that creates a class. I've mastered that stage already. >However, what I want to do is create multiple instances of >the class and put them into a list. > If the class is called Bob, then I want to do something like, > > >a = [] >a[0] = Bob('input1') > >and so on. Everytime I try something like this I get the following >error message: > >a[0] = Bob( 'localhost' ) >IndexError: list assignment index out of range Yeah, that is definitely a "no go". You can't refer to a[0] because it doesn't exist--a is empty. > I also tried it this way, > >a = [] >a.append = Bob('localhost') > >and I get the error message: > >a[0] = Bob( 'localhost' ) >IndexError: list assignment index out of range This is closer. a itself is an object, and the way you deal with it, at least for some functions, is thru its methods. append is a method of the list object, so what you really want is: a.append(Bob('localhost')) > >TIA, > >Jeff susan From roy at panix.com Tue Mar 12 07:39:22 2002 From: roy at panix.com (Roy Smith) Date: Tue, 12 Mar 2002 07:39:22 -0500 Subject: Is Python an object based programming langauge? References: Message-ID: Tim Hammerquist wrote: > According to Smalltalk enthusiasts, definitely not. AFAICT, if you ask a smalltalker, he'll tell you python is not OO because it's not more like smalltalk. On the other hand, if you ask a C++ hacker, he'll tell you python is not OO because it's not more like C++. Similarly for Java, etc. Everybody seems to have their own definition, usually based on whatever they learned first. I've got one guy I work with you insists python isn't OO for exactly one reason: because it doesn't implement private variables. From tejarex at yahoo.com Wed Mar 27 10:09:10 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Wed, 27 Mar 2002 15:09:10 GMT Subject: Why does this work? References: <3CA1BB93.FC00D40D@pop.ntlworld.com> Message-ID: "Phlip" wrote in message news:a7skr8$au5 at dispatch.concentric.net... ... > And we wrap all data members in get/set pairs, so the above would have been: > > x.setTiles([]) 'we'? The wisdom/folly of using get/set pairs is a matter of continuing dispute. Some of us find the extra work and inefficiency distastful. Terry J. Reedy From fperez528 at yahoo.com Wed Mar 6 10:50:48 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 06 Mar 2002 15:50:48 +0000 Subject: The language vs. the environment References: Message-ID: Skip Montanaro wrote: > > There has been a huge amount of recent PEP activity related to further > enhancements to the language. I think in general that if more of this > energy was directed at the overall environment (library, support tools, > installers, documentation, etc) we'd be better off in the long run. [snip] Let me add to your list distutils. They are nice but need a fair amount of work. Projects such as PyXML and SciPy have ended up writing a lot of wraparound utility code basically to provide functionality which it would be nice to have in the core system (useful to all). So one more for the list of 'useful things that benefit the community even though they don't sound cool' :) Cheers, f. From skurland at juggler.net Tue Mar 12 17:59:13 2002 From: skurland at juggler.net (Scott Kurland) Date: Tue, 12 Mar 2002 16:59:13 -0600 Subject: frustrated stupid newbie question Message-ID: Why isn't this $%^*#$% program working? #Searching for perfect numbers howhigh= input ("How high should I check?") for number in range (1,howhigh): factorsum = 0 halfnumber=number/2 for checking in range (1,halfnumber): if number/checking == int (number/checking): factorsum = factorsum + checking if number == factorsum: print number Flame away, I can't feel dumber than this. -- "Quemadmodum gladius neminem occidit, occidentis telum est." -- Seneca From mrchameleon at hotmail.com Sun Mar 17 03:45:05 2002 From: mrchameleon at hotmail.com (Chris Reay) Date: 17 Mar 2002 00:45:05 -0800 Subject: PIL Headaches: Advice Needed References: <4378fa6f.0203161652.7f28e23b@posting.google.com> Message-ID: <7652139e.0203170045.3c143995@posting.google.com> "Take a PIL, mate". Everyone else refrained (good on you all), but I couldn't help myself :-) From tim at vegeta.ath.cx Mon Mar 11 05:18:42 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Mon, 11 Mar 2002 10:18:42 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8C82D3.CA4220CA@earthlink.net> Message-ID: Hans Nowak graced us by uttering: [ snip ] > It sure smells like a hoax. I mean, really: > [ snip ] > > "Open and unrestricted"? It sure seems ludicrous to see these > words in the same sentence with "Microsoft". Didn't you know? Microsoft invented Open Source! ;) Tim Hammerquist -- Watch my captor grow old and die. No satisfaction. Still here. -- Morpheus, The Sandman From skip at pobox.com Thu Mar 7 14:55:35 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 13:55:35 -0600 Subject: Seek fame(*) & fortune(**) as a Python developer Message-ID: <15495.50615.234998.36271@beluga.mojam.com> As the Python user base grows, the number of bug reports and submitted patches that need to be handled grows as well. The size of the developer pool (people with checkin capability to the project) hasn't grown enough to meet the added demand, so we're looking for new developers to help. There are roughly 150 open patch submissions and about 250 open bug reports that need attention. While the work might not be glamorous, it is vital to keep the code base improving to meet new requirements. Python 2.3 is likely to be much more of a stability release than the previous versions in the 2.x series, which have each added significant new functionality to the language itself. For quality to improve, we need a major push to get existing bug reports and patches addressed. You can help in a number of different areas, so don't worry too much if you're not up on the implementation of nested scopes and their relation to new-style classes. Here are some things you might easily be able to help with: * More than 50 of the currently open bugs are in the documentation category. I suspect many of them may need fairly small additions to existing documents. * If you have access to a minority platform, you might well be able to help check that submitted bug fixes or patches work on your platform. Since most Windows users don't have MSVC++, Windows/MSVC++ may well count as a minority platform for the purposes of this work. * Most bug reports and patches are currently not assigned to anyone (probably two-thirds of the bug reports and half the patches). Performing some initial triage on them (deciding if they are duplicates, providing initial feedback, or developing initial fixes) would be a huge help. * Many bug fixes and patches simply need some feedback so the responsible people can move through their currently assigned items more easily. For much of this stuff you don't need checkin privileges to the CVS repository. For example, you could write a bit of documentation to address a doc bug, then attach a patch file to the current bug report. All you need for that is a SourceForge user id. You could also apply proposed bugfixes to your own CVS tree, see how they work, tweak them if necessary, and attach a comment to the bug report. If you're unfamiliar with the mechanisms currently in place to support Python development, I strongly urge you to read Andrew Kuchling's "Becoming a Python Developer": http://www.amk.ca/python/writing/python-dev.html I think it has just about everything you'll need to get started. Whether or not you want to be able to check files into the CVS repository, if you want to contribute, you should probably subscribe to the python-dev mailing list. You can subscribe here: http://mail.python.org/mailman/listinfo/python-dev If you'd like checkin privileges, send me (skip at pobox.com) an email with "Python developer" in the subject. Don't simply reply to this message. Your note may well get lost (I get tons of email) among followups that are just feedback about this message. Let me know where your Python interests and experience are, and maybe point to some stuff you've done. I'll do a little filtering (probably not a lot), then pass it along to another group of people who will decide about granting CVS checkin privileges. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) ----------- (*) Fame within a small group of like-minded geeks. (**) Your intangible wealth (e.g. "goodwill") will grow. Your wallet will almost certainly not get thicker. From daves_spam_dodging_account at yahoo.com Fri Mar 22 18:40:27 2002 From: daves_spam_dodging_account at yahoo.com (David Brady) Date: Fri, 22 Mar 2002 15:40:27 -0800 (PST) Subject: SECURITY ALERT!!! . gvc In-Reply-To: Message-ID: <20020322234027.13548.qmail@web21108.mail.yahoo.com> > -----Original Message----- > From: Cliff Wells > > At the same time computers have got much more > power fuller, and smaller > > But apparently users are still as illiterate as > ever. You give them too much credit, thinking they have remain at a stable level of illiteracy when, in fact, they actually have got much more clue lesser. -dB ===== David Brady daves_spam_dodging_account at yahoo.com I'm feeling very surreal today... or *AM* I? __________________________________________________ Do You Yahoo!? Yahoo! Movies - coverage of the 74th Academy Awards? http://movies.yahoo.com/ From martin at v.loewis.de Tue Mar 26 17:47:02 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 26 Mar 2002 23:47:02 +0100 Subject: Symbolic imports and manipulation of the namespace? References: Message-ID: VanL writes: > I was recently solving a problem which required that the config file > (just a python file) lie outside of the pythonpath. Is it possible to > do symbolic importation of a module? execfile will help. Regards, Martin From cdonicz at cri-inc.com Mon Mar 18 12:11:27 2002 From: cdonicz at cri-inc.com (Corey Donicz) Date: 18 Mar 2002 09:11:27 -0800 Subject: Python Embedding / Import Woes Message-ID: I'm trying to resolve how to properly handle python module imports from within an embedded python interpretor. I've been able to reduce the problem to a simple case scenario: After Py_Initialized() is called, as a test case, I run: PyRun_SimpleString("from Numeric import *"); What I get is the following traceback: File "", line 1, in ? File "C:\Program Files\Python21\Numeric\Numeric.py", line 133, in ? import multiarray ImportError: No module named multiarray I've checked that the python path points to the proper dirs, and I've also cross checked the behavior in from a python interactive shell which does _not_ result in the import error. I keep getting bizarre failures to find modules when my embedded code calls upon an external module which has an "from foo import *" type import. I feel I should also mention that the embedded application is not relying on PyRun_SimpleString at all, that's just in there for testing. I'm guessing that since my sys.path is correct, that I'm not managing namespaces correctly. Any insights into this would be greatly appreciated. Thanks in advance. -Corey From aahzpy at panix.com Fri Mar 22 14:50:31 2002 From: aahzpy at panix.com (Aahz) Date: 22 Mar 2002 14:50:31 -0500 Subject: Namespace Qualification Question References: <3C9B7C2A.20708@cpsc.ucalgary.ca__no_spam__> Message-ID: In article <3C9B7C2A.20708 at cpsc.ucalgary.ca__no_spam__>, Craig McLean wrote: > >Is there a module assosciated with the file you started the interpreter >with, and if there is what is it's name? For instance > > > python qux.py > >I would have thought that there would be a qux module, and that it's >name would be stored in the __name__ builtin. Nope. As you'll see if you look in many modules, __name__ == '__main__', so that makes it easy to test whether your script is being run directly or imported as a module. Don't know off-hand what the module is. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From peter at engcorp.com Thu Mar 21 19:36:19 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Mar 2002 19:36:19 -0500 Subject: Why do Windows sockets break after exactly 4 minutes? References: Message-ID: <3C9A7C83.F61ECDD1@engcorp.com> Geoffrey Talvola wrote: > > I've noticed that Windows sockets seem to close all by themselves if there > is no activity for 4 minutes. Does anyone know why? Is it possible to > control this behavior? Just a link to some documentation of this behavior > would be greatly appreciated. > > I don't think the same thing happens on Linux, or maybe it does but the > timeout is longer than 4 minutes there. > > I've attached a set of 2 test scripts that provoke the behavior. Start up > server.py first, then client.py, then wait 4 minutes. Haven't run your tests, but isn't this what SO_KEEPALIVE is used for? Try using: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) and this will turn on the keep-alive feature (I think... pulled that last line from pygale.py since I don't know where it is well documented). -Peter From helmut.zeisel at aon.at Tue Mar 5 04:04:40 2002 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: 5 Mar 2002 01:04:40 -0800 Subject: PyTypeObject* XXX(PyObject*) Message-ID: I want to use Python from C++. I get some Python Object using PyObject* po = PyRun_String(...); Depending on the type of the result po, I want to do different actions with po, say typedef (void)(*ActionType)(PyObject*); and I have an std::map actionMap; which I want to use in the following way: PyTypeObject* t = XXX(po); ActionType action = actionMap[t]; if(action!=0) { (*action)(); } What should be XXX, i.e., what is the name of the function to get the TypeObject of a Python Object? If there is no such function XXX, what should be the Key Type of my std::map? Helmut From mdl770 at libero.it Wed Mar 13 09:52:41 2002 From: mdl770 at libero.it (Marco De Luca) Date: Wed, 13 Mar 2002 15:52:41 +0100 Subject: calling methods of other objects Message-ID: Hi, I am quite new to Python and I have the following problem: I have a combobox and a grid inside a panel inside a frame. I added a method to a wxGrid derived class and I need to call that method from a combobox event. How can I refer to the grid method in the function handling the combobox event? Tahnks in advance, Marco.- From thomas at weholt.org Sun Mar 10 17:35:58 2002 From: thomas at weholt.org (Thomas Weholt) Date: Sun, 10 Mar 2002 22:35:58 GMT Subject: Regular expressions newbie: something for templates Message-ID: Hi, I'm not getting the hang of regular expressions. All I want to do is this. Take string #1 : "This is the test $var1$ and this is $var2$" and turn it into "This is the test %(var1)s and this is %(var2)s" Any clues? ( And yes, yet another template system in the works ;-) ) Thomas From geoff at gerrietts.net Thu Mar 7 14:50:39 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 7 Mar 2002 11:50:39 -0800 Subject: how to give an object as argument for a method In-Reply-To: <20020307101853.GA1326@lurkabove.darkstar> References: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> <20020307101853.GA1326@lurkabove.darkstar> Message-ID: <20020307195039.GE29379@isis.gerrietts.net> Quoting Marco Herrn (herrn at gmx.net): > Is there a reason why this is just a convention? It seems (because > it is such a _strong_ convention) that this should be a real feature > of the language. I mean that there could be a reserved word "self" > which is there all the time, so that one doesn't hast to do this > himself. Others have posted some very good reasons why this isn't so, but consider the advantages that explicitly passing "self" as a first argument has: >>> def myFunction(self, spam, eggs): ... print "Self:", self ... print "spam:", spam ... print "eggs:", eggs ... >>> class MyClass: ... myMethod = myFunction ... >>> my_instance = MyClass() >>> my_instance.myMethod('Yellow', 'Green') Self: <__main__.MyClass instance at 0x814f3a4> spam: Yellow eggs: Green Is that not cool? You know it is. -- Geoff Gerrietts "I have read your book and much like it." --Moses Hadas From martin at v.loewis.de Mon Mar 25 08:43:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 25 Mar 2002 14:43:51 +0100 Subject: unicode and locale of machine ? References: <3C9ED480.8000403@vip.fi> Message-ID: pekka niiranen writes: > Is it possible to read the current keyboard layout or > language settings in windows/unix and use that > automatically to convert text from unicode to printable > in another machine ? Some machines might not provide you with that information, so you might have a hard time figuring out what encoding to use. Here are some strategies: - On Unix, try locale.nl_langinfo(locale.CODESET). If that is available, it should be a string identifying the user's encoding. Pitfalls: - you might need to call setlocale before nl_langinfo returns something useful; make sure to set atleast the LC_CTYPE category. - the operating system may not support nl_langinfo, or CODESET. - the user may not have configured her locale properly - the encoding returned by the operating system may not be known to Python - On Windows, when passing strings to GUI code, you can use the "mbcs" encoding, which is Python's name for the CP_ACP codepage, which is Microsoft's abbreviation for "ANSI code page", which is Microsoft's name for the user's locale's encoding. Pitfalls: - Windows has *two* locale's encodings: the ANSI code page, and the OEM code page. The cmd.exe/command.com window, by default, uses the OEM code page, for which Python has no easy wrapper. - In any specific console window, the console code page may have been changed. If you find the encoding "enc" that the user users, you can print the Unicode strings uni just by doing print uni.encode("enc") HTH, Martin From gdiribarne at udcast.com Mon Mar 25 08:16:49 2002 From: gdiribarne at udcast.com (Gilles Diribarne) Date: Mon, 25 Mar 2002 14:16:49 +0100 Subject: Indentation problem Message-ID: <3C9F2341.1000802@udcast.com> Hi, I like Python language and use it every day. But... I read some articles from October, 1998 where there was a fight with space and tabs and indent problems. Today, we can found code with spaces and tabs in the code. I've some problem with identing code. I'm allright with the example. But, I think it's important to have an "end" building block like "!:" What do you think about that? Why I would like to put this in the code? 1/ Because it's almost impossible to paste python code with ident = n spaces to another code with indent = m spaces This kind of examples occurs more and more and you can indent the code by hand when it's 10 lines of codes, but not 1000 code lines. It prevents the re-use of code pieces. 2/ Programmers wants independence: some wants to manage building blocks with spaces, other with tabs, some wants length = 4 with tabs. I would like to use my own programming style! But, my code risks to be not supported by others. 2/ Emacs and a great number of editors cannot indent region, since the building blocks are only in programmer's mind. 3/ A large number of programming language use this. C, PERL, Ruby, ... Why not Python? 4/ Solve the problem of space and tabs length. But, we should keep the indenting mode which produces beautifull syntax. pythona.py: def func(): a = 1 if a == 1: a ==2 print "beatifull! Isn't it?" 5/ This kind of separator should be optional ??? So, don't change the current library. It will be very easy to adapt old code with this kind of separator. A parser could be provided to re-adapt the old code !!! EXAMPLE: pythona.py: def func(): a = 1 if a == 1: a ==2 pythonb.py def func2(): a = 2 if a == 2: print "Yeah!" You cannot merge correctly or tell me how to do this ? This is simply because the language doesn't have a "end" instruction block. It has ":" as beginning instruation block. I would like to propose an end instruction block like "!:" or "end" pythona.py: def func(): a = 1 if a == 1: a ==2 !: !: pythonb.py def func2(): a = 2 if a == 2: print "Yeah!" !: !: Now, with your favorite emacs, you can indent two portions of code very easily. def func(): a = 1 if a == 1: a ==2 !: !: def func2(): a = 2 if a == 2: print "Yeah!" !: !: Gilles, Python programmer From l0819m0v0smfm001 at sneakemail.com Fri Mar 8 23:28:24 2002 From: l0819m0v0smfm001 at sneakemail.com (Joshua Macy) Date: Sat, 09 Mar 2002 04:28:24 GMT Subject: PEP Parade References: Message-ID: <3C895594.60601@sneakemail.com> Roy Smith wrote > Not touching the core language is a Good Thing. It's really tough to > convince people that python is a viable tool when it's a moving target. > > It's been somewhat of an uphill battle to get my development group to > accept the fact that I write tools for the whole group's use in python. > Having the core language change from version to version just makes it > worse, as we discover imcompatabilities between whatever version I'm using > to develop on and whateve they're running on their boxes. Telling people, > "Oh, you need to upgrade to version X" gets old pretty fast. As the saying > goes, "if you're explaining, you've already lost." > Just out of curiosity, what does the rest of your group develop in then? FORTRAN? COBOL? ("and none of this ANSI85 crap, either...it gets old trying to hit a moving target!") Joshua From nospam at mega-nerd.com Sat Mar 9 20:29:18 2002 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sun, 10 Mar 2002 01:29:18 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> <3C8AA5E4.982FC689@mega-nerd.com> <3c8aae24.156616153@news> Message-ID: <3C8AB6ED.D7869109@mega-nerd.com> brobbins333 at shaw.ca wrote: > > I knew your name was familiar! I'm reading your book right now. > It's excellent. Thanks :-). > VB for one, returns a proper rounded result on these > recalcitrant numbers. VB probably stores rounded floating point numbers as strings instead of the normal binary representation. VB like most scripting style languages (ie non-stringly typed languages) often hides the representation of the its variables. > I'd be willing to bet that C can do it as well, > but you should know better than I. Python as it is written in C, gets its behaviour directly from C. What you are seeing is actually the behaviour of C. > The problem is that I am trying to use the return value of round() as > the return value of another function, so using Print to tidy it uup > really doesn't do me any good. Any suggestions? My suggestion is that instead of rounding the number you convert it to a string of the required precision: erikd at coltrane > python Python 2.1.2 (#1, Jan 18 2002, 18:05:45) [GCC 2.95.4 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> x = 56.78923 >>> x_as_string = "%.2f" % x >>> print x_as_string 56.79 Just what you want. Remember however that if you want to operate on the number using standard arithmetic you need to work on x rather than x_as_string. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ "The whole principle is wrong; it's like demanding that grown men live on skim milk because the baby can't eat steak." - author Robert A. Heinlein on censorship. From justin at iago.org Fri Mar 8 19:20:15 2002 From: justin at iago.org (Justin Sheehy) Date: Fri, 08 Mar 2002 19:20:15 -0500 Subject: ' in ' works, why doesnt ' in '? In-Reply-To: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> (morton@dennisinter.com's message of "8 Mar 2002 15:38:51 -0800") References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> Message-ID: morton at dennisinter.com (damien morton) writes: >>>> 'c' in 'the quick brown fox' > 1 >>>> 'fox' in 'the quick brown fox' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'in ' requires character as left operand > > is this by design? > > is there any reason why ' in ' shouldnt work? The "in" operator tests to see if the first operand is an element of the sequence which is the second element. A string is a sequence of characters (which are 1-element strings). Thus, the only thing which can be an element of a string is a single character. -Justin From bokr at oz.net Fri Mar 8 22:30:51 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 03:30:51 GMT Subject: broken pipes, import errors (LONG, INVOLVED) References: Message-ID: On Fri, 8 Mar 2002 16:13:54 -0800, Geoff Gerrietts wrote: > >At work, I'm seeing an "interesting" problem in my production >environment, or maybe two problems. It's one of those problems that [...] > > "This" is extremely curious. In one of our Zope products, we have a > sequence of logic that looks something like this: > > > statement = "import module.submodule.SubSubModule" > > object_nm = "module.submodule.SubSubModule.Object" > > > > exec statement > > object = eval(object_nm) > > Obviously, the names have been changed to protect the innocent and reduce > the complications. > > When Zope starts back up, the app will execute this block of statements > one or more times for several different values of "statement" and > "object_nm". I don't have a clue about your situation, but it strikes me that exec and eval both use name spaces (local and global dictionaries) that you could specify, but don't. I'm wondering if the default (current scope) is ok in your context. If you are repeatedly reusing the same current scope (e.g., doing those exec and eval lines inside a loop) for unrelated things, maybe there are name collisions? Maybe logging the output of dir() before and after those lines would reveal something? Or try specifying local and global dicts and .clear() them after use (maybe the default environment is keeping something alive that should get garbage-collected and have its destructor executed? Or maybe one finally does fire off after a same-name rebinding of a reference, and the old destructor is doing inappropriate cleanup for the new environment? How does memory usage look?) If you specify dictionaries for exec and eval, be wary of just passing anonymous {}. Give them separate names and assign them separately, unless you want to use the same one. I.e., dloc={}; dglob={} and they won't clear by themselves, so dloc.clear(); dglob.clear() when you want them to be fresh for the next loop (if that's what you have). If you pass {} to exec and eval, you won't be able to clear it, and you won't have changed much. These are just ideas trying to jog your thoughts, hopefully helpfully ;-) No specific recommendations -- you'll have to figure what's appropriate for your situation. Regards, Bengt Richter From jmdeschamps at cvm.qc.ca Thu Mar 14 09:49:25 2002 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 14 Mar 2002 06:49:25 -0800 Subject: PyProlog 0.2.0 - compiling under Windows Message-ID: <3d06fae9.0203140649.635d4b49@posting.google.com> I'M trying to use the Prolog wrapper from Nathan Denny, pyprolog0.2.0.tar http://agave.ahsc.arizona.edu/~schcats/projects/ ********* Excerp from the readme file... ... The prolog.py file provides a Python interface to SWI-Prolog. SWI-Prolog is a free prolog, ... Once you have installed SWI-Prolog, you will also need libpython2.0a...which should be in your Python-2.0 build directory. ... ********* The example tells how its compiled for Unix/Linux - I'm trying to adapt this to Windows using VC++6.0 Linking breaks with: ********* --------------------Configuration: pyswipl - Win32 Debug-------------------- Linking... LINK : fatal error LNK1104: cannot open file "python21_d.lib" Error executing link.exe. pyswipl.dll - 1 error(s), 0 warning(s) ********* Naturally, I don't have that file on my machine, nor the "libpython2.0a" refered to in the readme. I'm using Python 2.1 from ActiveState, under Windows 2000 Pro Any hints, recipy or other comments appreciated, Jean-Marc From mwh at python.net Mon Mar 4 11:15:52 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 4 Mar 2002 16:15:52 GMT Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> Message-ID: Christian Tismer writes: > Makes pretty much sense to me. > Stackless can provide light-weight threads to all platforms. > There is no need to use OS threads unless you need it > for I/O. The idea I think Frederic was getting at was to automatically use OS threads for IO. I don't know if that would be possible, but it might be cool. Cheers, M. -- The Oxford Bottled Beer Database heartily disapproves of the excessive consumption of alcohol. No, really. -- http://www.bottledbeer.co.uk/beergames.html (now sadly gone to the big 404 in the sky) From gerhard at bigfoot.de Thu Mar 7 23:08:38 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 8 Mar 2002 04:08:38 GMT Subject: [GERMAN] "ziegenproblem" References: <7x3czc87qq.fsf@ruckus.brouhaha.com> <3C882CBC.4553D21C@engcorp.com> Message-ID: Peter Hansen wrote in comp.lang.python: > Paul Rubin wrote: >> >> stefan antoni writes: >> > sorry that i won't be able to explain this in english, i don't know the >> > name of this problem in english, and the website which is about this >> > problem is also in german. >> >> Usually we call it the "Monty Hall problem". Monty Hall was the host >> of a TV game show where he actually played that game (put a prize behind >> one of three doors, etc). > > See also http://c2.com/cgi/wiki?MontyHallProblem for full discussion. Most of the explanations are too complicated IMHO. This is how I finally understood the problem: Your original choice has a chance of 1/3 to win the prize. This doesn't change no matter what the moderator will do. Consequenetly, the chance that the prize is hidden behind one of the two remaining doors is 2/3. So, now, the moderator opens one of the goat doors, but not yours. Your original choice still has a chance of 1/3 to be correct, but the two thirds for the other two doors now only apply to one door. That's why switching doors is smart. A little ASCII art :) After your original choice: +------+ +------+ +------+ | ? | | ? | | ? | +------+ +------+ +------+ your choice \-------+--------/ chance to win: | 1/3 chance to win: 2/3 +------+ +------+ +------+ | goat | | ? | | ? | +------+ +------+ +------+ chance to chance to win: 2/3 win: 1/3 Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From sholden at holdenweb.com Fri Mar 29 08:24:28 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 08:24:28 -0500 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: "phil hunt" wrote in message news:slrnaa7eem.eau.philh at comuno.freeserve.co.uk... > On 28 Mar 2002 15:19:27 -0500, David Bolen wrote: > >philh at comuno.freeserve.co.uk (phil hunt) writes: > > > >> IIRC in Awk you can just say: freq[word] ++ and it works > >> correctly even when there is no pre-existing index of word in freq. > >> > >> IMO it's a pity Python isn't like that. > > > >I'm not so sure. Doing it that way presumes that in fact you aren't > >making an error while trying to access an index (word) that doesn't > >exist. > > Correct. IMO "try to do something sensible" should be the default. > So you'd like Python to operate in DWIM (do what I mean) mode? Perhaps you'd also like the development of psychic wireless networking, which knows what you are going to say so you never need to say it, and all programs simply become a sinlge statement: solve this problem > If the programmer *wants* to do it the other way round, that is easy > enough to code: > > if word not in fred: > raise SomeException > fred[word] ++ > > But 9 times out of 10, you'll want to use a default of 0. > 9 times out of 10 a language system that makes guesses about what I want will be wrong. If I want a system that "makes guesses" then Perl is available. > >Python requires marginally more effort to cover this case (e.g., you > >have to explicitly use a method like .get to include a default value > >if you know the key might not yet be present), but that also means > >that the code explicitly highlights that the scenario is anticipated > >and being handled. > > Having to explicitly state things like this is a sign of low > levelnmess in a lang. Next you'll be arguing that explicit storage > management is a good thing.... :-) > Explicit storage management is a good thing if you happen to need close control over storage. But having to be explicit about the semantic of your problem (rather than the details of using a computer to solve a problem by manipulating information models) is a sign a maturity, not of "low-levelness". I guess solve this problem would be high-level in your book? In mine it simply moves the onus of providing semantic detail on to the description of what "this problem" is. The problems that take most fixing are the ones where the language system acts on some unstated assumption which contradicts the assumptions of the programmer. > >Sure, in a simple example like an increment operation it seems a bit > >much, but as a general case, I think it's the smarter and more > >maintainable default behavior. > > I have never had maintainability problems with the other way round. > You're lucky. regards Steve From skip at pobox.com Fri Mar 1 15:53:06 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 1 Mar 2002 14:53:06 -0600 Subject: PEP 263 comments In-Reply-To: References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <15487.59954.782142.191843@12-248-41-177.client.attbi.com> Martin> A byte string should certainly be able to store arbitrary Martin> bytes. Under Stephen's proposal, it would indeed not be possible Martin> anymore to put arbitrary binary data into source code. It's clear from discussions on python-dev that, like Barry Warsaw, I wear American sunglasses when exposed to the Unicode sun. Just to make sure I understand correctly, under Stephen's propsal would s = "\xff" be correct? I assume s = "?" (a literal 0377 character) would be an error, yes? That is, when you saw "arbitrary binary data" you are referring to non-printable octets in the source file, right? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From emile at fenx.com Wed Mar 20 08:54:54 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 20 Mar 2002 05:54:54 -0800 Subject: classes for fun and newbies References: Message-ID: Bruce Dykes > class call_record: > def __init__(self, record=''): > self.record_id=record[0:5] > self.date=record[6:11] > > etc... > > Now what I expect to be able to do is say: > > log = readlines(today.log) > > and then summon discrete bits of info like so: > > print call_record.record_id(log[1]) > If all you want is the record_id you could do: print call_record(log[1]).record_id But if you want to get to the other attributes, you'll probably want to save a reference to the object: this_rec = call_record(log[1]) and then access the attributes: this_rec.record_id this_rec.date etc. HTH, -- Emile van Sebille emile at fenx.com --------- From aahz at pythoncraft.com Thu Mar 14 13:46:56 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2002 13:46:56 -0500 Subject: Conditional Import References: Message-ID: In article , Gustavo Cordova wrote: > > from exceptions import ImportError > try: > from codeop import CommandCompiler > except ImportError: > from MockCommandCompiler import CommandCompiler Exceptions are automatically imported; no need for the first line. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. --Aahz From Chris.Barker at noaa.gov Wed Mar 6 14:59:36 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Wed, 06 Mar 2002 11:59:36 -0800 Subject: Black Adder and PyQt References: <3C80B1E3.575761B7@river-bank.demon.co.uk> Message-ID: <3C867528.F55D9A90@noaa.gov> Wayne Pierce wrote: >I've tried wxDesigner, but > couldn't figure out that spacer stuff for the life of me. I think you mean "Sizer", and you might want to give it another shot. They take a little effort to wrap your brain around, but once you get it, wxSizers are an excelent way to develop GUIs, particularly cross-platform ones, where the widgets are different shapes and sizes on different platforms. Or multi-language ones, where the text is different in different languages. wxDesigner makes using wxSizers a whole lot easier that writing th code by hand, anyway! -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From khirmint at hotmail.com Fri Mar 15 13:28:10 2002 From: khirmint at hotmail.com (Ken) Date: Fri, 15 Mar 2002 10:28:10 -0800 Subject: Implementation Advice Message-ID: Hey everyone.. I'm trying to create a system where users log in, and based on how they log in or who they log in as, they get a different set of functionality. A really simple example would be a multi-room chat, where each room has some common functionality (ie.send/receive messages) and some extras like different color text. I'd like to keep the functionality for each room in a separate file. My question is, should each file have a class declaration (using inheritance where appropriate) containing the necessary additional functions, initialization, etc.. Or, should each file contain a series of functions? One common to all files to initialize a room and then modify it and add functions to it as necessary? Thanks in advance for any thoughts and my apologies if it makes no sense :) Ken P.S. Just wanted to add that I'm rather new to Python and I've got to say that I'm really impressed with both the language and the community :) From rjones at ekit-inc.com Tue Mar 19 01:38:57 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Tue, 19 Mar 2002 17:38:57 +1100 Subject: Java and Python In-Reply-To: <3C96DBB4.6040109@pobox.com> References: <3C96DBB4.6040109@pobox.com> Message-ID: <200203190639.GAA17904@crown.off.ekorp.com> On Tue, 19 Mar 2002 17:33, Ahmed Moustafa wrote: > 1. Where can I find an unbiased comparison between Java and Python? > 2. Will Python dominate? > 3. Who does support Python? Please go look at http://www.python.org/, there's plenty of resources there to answer your questions. Richard From bergeston at yahoo.fr Wed Mar 6 06:07:53 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: 6 Mar 2002 03:07:53 -0800 Subject: how to give an object as argument for a method References: Message-ID: If I understand your question correctly, you can do it like in java: >>> class Spam: ... def sayYesBut(self, caller): ... print "Yes %s, but I'm %s !" % (caller, self) ... >>> class Egg: ... def __init__(self): ... self.spam = Spam() ... def saySomething(self): ... self.spam.sayYesBut(self) ... >>> egg = Egg() >>> egg.saySomething() Yes <__main__.Egg instance at 0x01227338>, but I'm <__main__.Spam instance at 0x0125CC88> ! >>> But: - 'self' is used in Python in place of 'this' in java - 'self' is mandatory (no implicit reference to the instance) - 'self' is not a reserved word but a **STRONG** naming convention for the first argument of every method that always refer to the instance PS. Here is a way to do it magically. It comes from the excellent post 'Get reference to "owner"' from ... yesterday ! This is powerfull and funny but IMHO it hurts good principles of design. >>> class Egg: ... def __init__(self): ... self.spam = Spam() ... def saySomething(self): ... self.spam.sayYesBut(self) ... def saySomethingElse(self): ... self.spam.sayNo() ... >>> class Spam: ... def sayYesBut(self, caller): ... print "Yes %s, but I'm %s !" % (caller, self) ... def sayNo(self): ... caller = sys._getframe(1).f_locals['self'] ... print "No %s, but I'm %s !" % (caller, self) ... >>> egg = Egg() >>> egg.saySomething() Yes <__main__.Egg instance at 0x0126E098>, but I'm <__main__.Spam instance at 0x010F7DA8> ! >>> egg.saySomethingElse() No <__main__.Egg instance at 0x0126E098>, but I'm <__main__.Spam instance at 0x010F7DA8> ! >>> B. Marco Herrn wrote in message news:... > Hello, > > I am new to python and have a question how to achieve $subject. > > I want something like the 'this' statement in java that gives you the > current object. So when I call a method like f(this) I give the object > that calls the method as argument. > But how can I do this in python? > I am using python 2.1. > > Bye > Marco > -- > This life is a test. It is only a test. Had this been an actual life, you > would have received further instructions as to what to do and where to go. From sjmachin at lexicon.net Fri Mar 1 13:28:50 2002 From: sjmachin at lexicon.net (John Machin) Date: 1 Mar 2002 10:28:50 -0800 Subject: Apology to Bill Gates (was Re: ASV module, CVS modules) References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: Michael Hudson wrote in message news:... > Skip Montanaro writes: > > > John> Python, starting from a Unix background, where there is evidently > > John> no such thing as an invalid character in a file name, ... > > > > I believe "/" is not allowed in Unix filenames. Not sure if this is > > escapable or not. > > Don't think so. NULLs are out, too. It is not a case of "not allowed". You simply can't supply a file name containing a "/" or a NUL (not a *NULL*) because "/" is interpreted as a path separator and NUL as a string terminator. My point was that Unix doesn't proactively check to see if you are trying to create a file whose name you may never see again. From gcordova at hebmex.com Thu Mar 14 12:13:03 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 14 Mar 2002 11:13:03 -0600 Subject: Conditional Import Message-ID: <19650FF08A99D511B19E00B0D0F0632301D68956@SRM201002> > > Right now, I've this hack in the middle of my code > > try: > from codeop import CommandCompiler > except: > from MockCommandCompiler import CommandCompiler > > But if I have to put up with a work around like this, I'd > prefer that it be fairly elegant. Or at least standard... > Well, it's *almost* standard. Just a little modification: from exceptions import ImportError try: from codeop import CommandCompiler except ImportError: from MockCommandCompiler import CommandCompiler and that's it. :-) It's fairly used, look into some of the standard modules, mainly in conjunction with StringIO/cStringIO. Salutations! -gustavo From philh at comuno.freeserve.co.uk Wed Mar 27 19:17:11 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 28 Mar 2002 00:17:11 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <8gv3au47846mgol398j4oc5t0ufoi274b4@4ax.com> Message-ID: On Wed, 27 Mar 2002 17:05:58 GMT, Courageous wrote: > >>And then, when you begin to flesh out your code, you would have to >>get rid of the extraneous passes you didn't want to add (assuming >>you are like me) in the first place. So the with-pass version >>requires more effort, and is more verbose, for no good reason. > >The reasons are related to the implementation and not the design >of Python, I believe. Oh? Can it really be hard to modify python so that pass is optional? The relvant file is grammar, line 68 of which reads: suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT I wonder if I could change this to something like: suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT | NEWLINE (It's current;ly compiling; i will get back on this) -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From it.santiago at memo.volvo.se Fri Mar 15 13:12:27 2002 From: it.santiago at memo.volvo.se (Santiago) Date: Fri, 15 Mar 2002 15:12:27 -0300 Subject: Wrong transfer of data (ODBC) Message-ID: I was trying to use the 'Python ODBC Notes (Windows Only)' wrote by John Dell'Aguila 2/11/98.(at the bottom you will see the program) I used the ODBC using Python Database API. from the AS/400 database to the PC Windows. But when I get the data from the AS/400 I get the string fields okay, but the fields with decimals , like price, it appears with wrong decimals. The price field in the AS/400 has eleven digits (9 integers and 2 decimals). For example, the data in the AS/400 is 15860.94 but what I get is 15860.94000000001. Column descriptions: ('mater', 'STRING', 20, 20, 0, 0, 0) ('descr', 'STRING', 18, 18, 0, 0, 0) ('price', 'NUMBER', 13, 11, 11, 2, 0) ('stock', 'NUMBER', 7, 5, 5, 0, 0) Data (' 9534', 'GEARBOX ', 15860.940000000001, 0L) (' 9632', 'GEARBOX ', 15962.969999999999, 1L) (' 9642', 'GEARBOX ', 15090.389999999999, 0L) (' 9643', 'GEARBOX O ', 15090.389999999999, 1L) (' 9686', 'GEARBOX 8686 ', 15090.389999999999, 1L) (' 9827', 'GEARBOX 8827 ', 18053.43, 0L) (' 9862', 'GEARBOX 8862 ', 15962.969999999999, 0L) (' 9892', 'GEARBOX 8892 ', 17155.32, 0L) (' 9908', 'GEARBOX 18 ', 18535.619999999999, 0L) (' 9911', 'GEARBOX 8911 ', 18053.43, 0L) Where is the problem? David PD: program that I used as a base: import dbi, odbc # ODBC modules import time # standard time module dbc = odbc.odbc( # open a database connection 'sample/monty/spam' # 'datasource/user/password' ) crsr = dbc.cursor() # create a cursor crsr.execute( # execute some SQL """ SELECT country_id, name, insert_change_date FROM country ORDER BY name """ ) print 'Column descriptions:' # show column descriptions for col in crsr.description: print ' ', col result = crsr.fetchall() # fetch the results all at once print '\nFirst result row:\n ', result[0] # show first result row print '\nDate conversions:' # play with dbiDate object date = result[0][-1] fmt = ' %-25s%-20s' print fmt % ('standard string:', str(date)) print fmt % ('seconds since epoch:', float(date)) timeTuple = time.localtime(date) print fmt % ('time tuple:', timeTuple) print fmt % ('user defined:', time.strftime('%d %B %Y', timeTuple)) -------------------------------output-------------------------------- Column descriptions: ('country_id', 'NUMBER', 12, 10, 10, 0, 0) ('name', 'STRING', 45, 45, 0, 0, 0) ('insert_change_date', 'DATE', 19, 19, 0, 0, 1) First result row: (24L, 'ARGENTINA', ) Date conversions: standard string: Fri Dec 19 01:51:53 1997 seconds since epoch: 882517913.0 time tuple: (1997, 12, 19, 1, 51, 53, 4, 353, 0) user defined: 19 December 1997 From tejarex at yahoo.com Sat Mar 9 15:55:40 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 09 Mar 2002 20:55:40 GMT Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> Message-ID: "Gerson Kurz" wrote in message news:3c8a4042.46048234 at news.t-online.de... > Bored, I spent the past few hours writing a small, 100% useless > language. It doesn't have a name, so I call it UNBABTIZED (as in: has > not been given a name yet), which is, right there, a > self-contradiction. What a good start! You apparently meant UNBAPTIZED, but since you baptized it as you did, its too late 8-) From kragen at pobox.com Tue Mar 19 13:59:30 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 19 Mar 2002 13:59:30 -0500 Subject: Optimising list comparison References: Message-ID: <83it7sidt9.fsf@panacea.canonical.org> Graham Ashton writes: > A friend of mine is using Python in a research project where he needs to > compare each element of two vectors, such that comparing [a, b, c] and > [d, e, f] would involve comparing a with d, b with e and c with f. Numeric.alltrue(Numeric.logical_or(a == b, Numeric.logical_or(a == -1, b == -1))) It might not be faster than psyco, but it will be faster than looping in interpreted Python over all the elements of each vector if the vectors are relatively large. From thoa0025 at mail.usyd.edu.au Fri Mar 29 21:49:17 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sat, 30 Mar 2002 02:49:17 GMT Subject: thanks all! it's great References: Message-ID: "Bengt Richter" wrote in message news:a80oq0$av7$0 at 216.39.172.122... > On 29 Mar 2002 02:00:03 GMT, bokr at oz.net (Bengt Richter) wrote: > [...] > >Here is something to deal with the key order problem (i.e., if one > >key is a substring of another. You have to sort by length to get > >maximal or minimal matching. This is for maximal: > > > > >>> def dirinterp(s,d): > > ... import re > > ... klist = [(-len(k),k) for k in d.keys()] > > ... klist.sort() > > ... resp = re.compile('('+'|'.join([k for l,k in klist])+')') > > ... return ''.join([kv.get(w,w) for w in resp.split(s)]) > ^^--oops, that worked because of a leftover global ;-/ > > ... > > >>> subdir = {"sub":"","substring":""} > > >>> dirinterp("Will sub or substring be replaced?",subdir) > > 'Will or be replaced?' > > >>> dirinterp("Will substring or sub be replaced?",subdir) > > 'Will or be replaced?' > > > >This is hardly tested at all, but I guess it could be handy. > Must run in fresh interpreter before posting ;-/ > > >>> from miscutil import subbydict > >>> d={'x':'A', 'xx':'B','xxx':'C'} > >>> s='xxxxxx xxxx xxx xx x' > >>> subbydict(s,d) > 'CC CA C B A' > >>> s='xxxxxx xxxxx xxxx xxx xx x' > >>> subbydict(s,d) > 'CC CB CA C B A' > > where name changed and kv->d > > def subbydict(s,d): > import re > klist = [(-len(k),k) for k in d.keys()] > klist.sort() > resp = re.compile('('+'|'.join([k for l,k in klist])+')') > return ''.join([d.get(w,w) for w in resp.split(s)]) > > Regards, > Bengt Richter From duncan at NOSPAMrcp.co.uk Wed Mar 13 04:50:25 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 13 Mar 2002 09:50:25 +0000 (UTC) Subject: Is there a good reason why we cannot (as of 2.1.1) deepcopy complex objects? References: Message-ID: Tim Peters wrote in news:mailman.1015995502.4050.python-list at python.org: > [Carl Banks] >> Subject: Is there a good reason why we cannot (as of 2.1.1) deepcopy >> complex objects? > > I doubt it. Works fine in 2.2: Although you could perhaps have mentioned that deepcopy of a complex number does not in fact copy it (it returns the original number). This is of course correct behaviour for immutable objects. -- 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 bergeston at yahoo.fr Tue Mar 5 10:06:01 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: 5 Mar 2002 07:06:01 -0800 Subject: Generators and iterators Message-ID: Hello, I just quickly red the page about new features in Python 2.2 and tried - for fun - to test it. It must be obvious but I really don't see why, in the console transcript below, z.next() send back None and not 1,2 and 3 whereas it does it correctly 3 times, no more no less. TIA. B. Sorry for the methods and class names. Here is it: PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> from __future__ import generators >>> def t(): ... yield 1 ... yield 2 ... yield 3 ... >>> tt = t() >>> tt >>> tt.next() 1 >>> tt.next() 2 >>> tt.next() 3 >>> tt.next() Traceback (most recent call last): File "", line 1, in ? StopIteration >>> class Z: ... def __init__(self): ... self.ttt=t() ... def __iter__(self): ... return self ... def next(self): ... self.ttt.next() ... >>> z=Z() >>> for i in z: ... print i ... None None None >>> z=Z() >>> z.next() >>> z.next() >>> z.next() >>> z.next() Traceback (most recent call last): File "", line 1, in ? File "", line 7, in next StopIteration From attila-kenez at vnet.hu Tue Mar 26 08:15:25 2002 From: attila-kenez at vnet.hu (=?iso-8859-1?Q?Ken=E9z_Attila?=) Date: Tue, 26 Mar 2002 14:15:25 +0100 Subject: beginner Message-ID: Hi! I am a beginner using Python and I have two problems. I would like two write an installer program in Python, that works on any computer with Wondow OS, so that is not nesseccary to have Python interpreter on it. Is there a simple (or a difficult) way to do it? The other question is about pyd files. I did not found any mention about it in the documentation. I want to access a database under SAP DB from Python, and for that I need to use the sapdb.pyd file. I tried to move it to a directory in PATH and PYTHONPATH but the interpreter dropped an error at the import statement. How I have to use these kind of files? Thanks: Attila Kenez From martin at v.loewis.de Thu Mar 21 01:20:35 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Mar 2002 07:20:35 +0100 Subject: How Can I Determine the Operating System with Python? References: Message-ID: obsidian_genius at yahoo.com (Jill Obsidian) writes: > I have need to write some Python scripts that run on Windows as well > as Linux/Unix. > > In some instances I will be making os.system() calls to execute > applications installed locally on the machine. > > How can I put a check in my script which will allow me to determine > whether I'm running on Windows or Linux at execution time? If you want to run an executable, don't check for the system - check whether the executable exists: os.path.exists("/bin/ps"). HTH, Martin From peter at engcorp.com Thu Mar 21 18:59:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Mar 2002 18:59:24 -0500 Subject: #define equivalents and config files References: <3C9963BD.1040304@verizon.net> <3C9964FF.46805590@engcorp.com> <3C9A466F.7D6D6AE9@ccvcorp.com> Message-ID: <3C9A73DC.A354F58@engcorp.com> Jeff Shannon wrote: > > Dave Swegen wrote: > > > > Rich Salz wrote: > > > > > > > > > Is there a pythonic way of doing something similiar to Cs #define? > > > > >... are globals the only way to go? > > > > > > > > You can at least make them class attributes > > > > class constants: > > > > pi = 3.14159 > > > > e = 2.71828 > > > > adding your own setattr can serve to make them read-only. > You can use some interesting hacks to make the constants module read-only, > if necessary (see the ASPN Python Cookbook), but since I'm typically the > only person using my code I've decided to simply trust myself. ;) And thank you for that, since if, after all, you decide to distribute your code, the rest of us can improve it without changing your source, which wouldn't be possible if you'd gone all whips and chains on us and made it read-only: import constants # get Jeff's constants constants.pi = 3.141592653589793 # tighten up pi a little... :-) -Peter From jimd at vega.starshine.org Tue Mar 19 08:46:13 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 19 Mar 2002 13:46:13 GMT Subject: Book Draft Available: Text Processing in Python References: Message-ID: In article , David Mertz, Ph.D. wrote: > Pythonistas: > As some folks know, I am working on a book called _Text Processing in > Python_. With the gracious permission of my publisher, Addison Wesley, > I am hereby making in-progress drafts of the book available to the > Python community. It's about half done right now, but that will > increase over time. > Take a look at the book URL: http://gnosis.cx/TPiP/ > I welcome any comments or feedback the Python community has about my > book. > Yours, David... I was glancing through it and stopped when I read your word counter (with no support for the command line options). I just had to do one to emulate the GNU wc utility as closely as I can in one quick session. Below is a somewhat more faithful rendering of the GNU wc command. Although it's about 120 lines long, almost forty of those are blank lines, docstrings, or comments. In most cases it gives output that is identical to GNU wc (including the character spacing). The only discrepancies I've seen are in the -L (--max-line-length) calculation (particularly on binary files). It's pedagogical value is more in the use of the getopts module and possibly in file iteration (for line in file: ...). The text processing being done here is trivial. There's also a little bit of exception handling, and a minimal amount of error avoidance --- since Python will allow me to open a directory but will complain if I try to read lines therefrom). It is mildly interesting that this Python implementation of wc is only about a third the length of the GNU version from the text utils package (wc.c is 371 lines). Actually counting words and characters the Python version is only about half the length. (Glancing at the sources I see that I missed support for the POSIXLY_CORRECT environment variable -- which modifies, or uglifies if you prefer, the output format; I could add that in a few lines). David, you're welcome to use this script as an example. Perhaps you could list this as an example of how 14 lines of simple, focused code grows to 140 lines by the time we add option handling, help and error messages, exception handling and error avoidance, and all that other stuff. (If you really want to scare people you could include the wc.c from the GNU textutils package by way of comparison). #!/usr/bin/env python2.2 import sys, os """ wc: Emulate GNU wc (word count) """ help = '''Usage: wc [OPTION]... [FILE]... Print line, word, and byte counts for each FILE, and a total line if more than one FILE is specified. With no FILE, or when FILE is -, read standard input. -c, --bytes, --chars print the byte counts -l, --lines print the newline counts -L, --max-line-length print the length of the longest line -w, --words print the word counts --help display this help and exit --version output version information and exit Report bugs to ''' version = """Python word count: wc(1) emulation by James T. Dennis version 0.1""" def options(): """Process command line options""" import getopt short = "clLw" long = ('bytes', 'chars', 'lines', 'max-line-length', 'words', 'help', 'version') try: opts, args = getopt.getopt(sys.argv[1:], short, long) except getopt.GetoptError,err: msg = "wc: invalid option \nTry `wc --help' for more information." print >> sys.stderr, sys.argv[0], err print >> sys.stderr, msg sys.exit(1) return opts, args def count(f=None): """Count and return words, chars, lines, and maxlength""" # We count them all, since that's and much easier than alot of # conditional logic to decide what to count. # We return it all, and main() can decide what to return. lines = words = chars = maxline = 0 if f == None: file = sys.stdin else: if os.path.isdir(f): print >> sys.stderr, "wc: %s: Is a directory" % f return lines, words, chars, maxline try: file = open(f,'r') except IOError: print >> sys.stderr, "Error opening:", f return lines, words, chars, maxline # If we get this far, we can count stuff for line in file: length = len(line) lines += 1 chars += length words += len(line.split()) if length - 1 > maxline: maxline = length - 1 # GNU wc doesn't count line terminator in maxlength? # +++ binary files anve much different line length semantics! return lines, words, chars, maxline def printcount(flags, totals, filename=None): """Print counts for each file and for the grand totals takes two 4-tuples, the flags for which items to print, and the total lines, words, characters, and max-line-length and an optional filename""" if filename == None: filename = "" dolines, dochars, dowords, domaxln = flags l, w, c, m = totals print "", # GNU wc prints one leading space? if dolines: print "%6d" % l, if dowords: print "%7d" % w, if dochars: print "%7d" % c, if domaxln: print "%7d" % m, print filename if __name__ == "__main__": opts, args = options() dolines = dochars = dowords = domaxln = 0 for opt,arg in opts: if opt == '--help': print help sys.exit() elif opt == '--version': print version sys.exit() elif opt in ('-l', '--lines'): dolines = 1 elif opt in ('-c', '--chars', '--bytes'): dochars = 1 elif opt in ('-w', '--words'): dowords = 1 elif opt in ('-L', '--max-line-length'): domaxln = 1 if dolines + dochars + dowords + domaxln == 0: # None specified so default is to do lines, chars, and words dolines = dochars = dowords = 1 # Else we do only the ones that are specified # GNU wc always prints the stats in the same order, regardless # of the order of the options/switches. printflags = (dolines, dochars, dowords, domaxln) if not args: # No files named: so just do stdin # No grand totals. and no filename l, w, c, m = count() printcount (printflags, (l,w,c,m)) else: # Else we do each file and keep track of grand totals all_lines = all_words = all_chars = longest_line = 0 files_processed = 0 for i in args: if i == '-': l, w, c, m = count() else: l, w, c, m = count(i) all_lines += l all_words += w all_chars += c if m > longest_line: longest_line = m printcount (printflags, (l,w,c,m), i) files_processed += 1 if files_processed > 1: # Print totals totals = (all_lines, all_words, all_chars, longest_line) printcount (printflags, totals, "total") From jimd at vega.starshine.org Wed Mar 27 14:07:49 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 27 Mar 2002 19:07:49 GMT Subject: os.fchown, avoiding a race condition References: Message-ID: In article , John Leach wrote: >Hi, > I haven't managed to find any reference in python (any version) to the > unix system call fchown (SVr4, SVID, POSIX, X/OPEN). There is chown, but > not fchown. > I'd like to create a file as a different user but would like to avoid a > race condition by chowning via the file descriptor, but it seems I cannot. > Does anyone know why this seems to be missing? Any plans for it to > appear? Any other way I can do this? > Thanks in advance. >-John. If would be cool if os.chown was overloaded to take *either* a patch *or* a file descriptor (from file_instance.fileno()) as its first argument. Should that be submitted as a PEP and/or patch? From oliver.pust at web.de Tue Mar 26 09:14:10 2002 From: oliver.pust at web.de (Oliver Pust) Date: Tue, 26 Mar 2002 15:14:10 +0100 Subject: module for assessing gray levels of gray level bitmap? References: <3C987942.9060309@web.de> Message-ID: <3CA08232.5040602@web.de> Fredrik Lundh wrote: > Oliver Pust wrote: > > >>is there a module for assessing the gray levels of gray level bitmap? I >>am thinking of a module that allows to open a bmp-file and stores the >>gray levels of each pixel in form of a matrix e.g. gray_level[x,y]. >> > > http://www.pythonware.com/products/pil/index.htm > > from PIL import Image > > im = Image.open("myimage.bmp") > print im.getpixel((x, y)) Thank you, that is what I looked for. Oliver From warlock at eskimo.com Wed Mar 20 03:23:52 2002 From: warlock at eskimo.com (Jim Richardson) Date: Wed, 20 Mar 2002 00:23:52 -0800 Subject: For loops with explicit indices -- again References: <3c9789ed$0$29676$ba620e4c@news.skynet.be> Message-ID: On Tue, 19 Mar 2002 18:57:29 +0100, Armin Rigo wrote: > Hello everybody, > > Here is yet another proposal (or did I miss something similar?) about the > for-with-explicit-indices syntax problems, as discussed in PEP 281 > (http://python.sourceforge.net/peps/pep-0281.html). > > Now that Python has iterators, they could be more explicitely used by user > code. Remember that 'for x in sequence' is equivalent to 'for x in > iter(sequence)', where iter() is used to get a sequence iterator. As it > seems we often loop over sequence elements and occasionnally need an > explicit index, I suggest adding a 'count' attribute to sequence iterators > that returns the number of items returned so far. This just requires putting > the iterator in a local variable. For example, to decrement all positive > integers in a list, modifying it in-place: > > it = iter(lst) > for x in it: > if x>0: > lst[it.count-1] -= 1 I am missing something. How is this different from for x in len(lst): ? -- Jim Richardson Anarchist, pagan and proud of it www.eskimo.com/~warlock Linux, for when you need to get work done, Or you could just play UT... From heinlr at gmx.de Sat Mar 2 12:34:33 2002 From: heinlr at gmx.de (heinl raimund) Date: Sat, 2 Mar 2002 18:34:33 +0100 Subject: Error on pysnmp and/or BER Module in Python2.2 Message-ID: <3c810d55$0$139$9b622d9e@news.freenet.de> i am using : Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 i use the pysnmp modul. for coding and encoding of snmp packets pysnmp uses the BER Modul. on function call to MyPySnmp_session.decode_value i got the following error: session instance has no attribute 'decode_an_unsigned'-exceptions.AttributeError is it a known bug - maybe a fixed BER/pysnmp Modul already exists ? best regards ### CODE SNIPPLET session = pysnmp.session(agent, community) # create a SNMP session #the session is always not NONE - its not possible at this point to validate a password for objid in lobjid: # encode objids #DBG(DBG_SNMPLO, "snmpget: %s + %s ", objid, poid) encoded_oids.append(session.encode_oid(session.str2nums(objid+poid))) # build a packet packet = session.encode_request ('GETREQUEST', encoded_oids, encoded_vals) # send SNMP request and receive a response packet = session.send_and_receive (packet) if packet == None: # if None stop condition occured return (-2, None) # parse a response packet (encoded_oids, encoded_vals) = session.decode_response (packet) index = 0 while index < len(encoded_oids): # decode objs & vals objid = session.decode_value(encoded_oids[index]) # in Python2.2 an !!!!!!!!!!! ERROR !!!!!!!!!!!!! # session instance has no attribute 'decode_an_unsigned'-exceptions.AttributeError value = session.decode_value(encoded_vals[index]) lval.append(value) if lprivoid != None: pos = string.find(objid, lobjid[index]) #DBG(DBG_SNMPLO, "snmpget:oidfind %s,%s:%d", objid, lobjid[index], pos) if pos != 0: # OID not at begin or not found privoid = objid # return complete ??? else: # ok strip requested OID pos = len(lobjid[index]) privoid = objid[pos:] # return private part lprivoid.append(privoid) index = index + 1 # go to the next objid if CallBackRead != None: CallBackRead(0) return (index, None) -- =========================================================== Heinl Raimund SSH - Software Systeme Heinl gepr.Wirtschaftsinformatiker IHK Am Galling 3 91217 Hersbruck Email: heinlr at gmx.de =========================================================== From andreas at zope.com Fri Mar 1 13:24:35 2002 From: andreas at zope.com (Andreas Jung) Date: Fri, 1 Mar 2002 13:24:35 -0500 Subject: Does python have a function like similar_text in PHP References: Message-ID: <04ef01c1c14e$acf37210$02010a0a@suxlap> I wrote a Python extension that implements the Levenshtein algorithm that PHP uses too. The same extension als contains implementations for soundex and metaphone. Available from the CVS: http://sourceforge.net/projects/pyproximity Andreas ----- Original Message ----- From: "Tim Peters" To: Sent: Friday, March 01, 2002 13:18 Subject: RE: Does python have a function like similar_text in PHP > [ron nixon] > > Does anyone know if Python has a function like similar_text in PHP. It > > compares two strings and returns a percentage for the match. > > The .ratio() method of SequenceMatcher objects looks like a similar gimmick, > returning a "similarity score" as a float in [0, 1]: > > http://www.python.org/doc/current/lib/sequence-matcher.html > > > -- > http://mail.python.org/mailman/listinfo/python-list > From h.jehadalwan at student.kun.nl Sat Mar 2 09:44:05 2002 From: h.jehadalwan at student.kun.nl (husam) Date: Sat, 02 Mar 2002 15:44:05 +0100 Subject: a simple 'else' decrease speed by 1000 times. References: <3C80BBAC.2060600@student.kun.nl> Message-ID: <3C80E535.7000407@student.kun.nl> Chris Liechti wrote: > husam wrote in news:3C80BBAC.2060600 > @student.kun.nl: > >>One else statement decrease speed by 1000 times. Why is that? >> > ... > >> if prv == n[i][-1]: >> n[i].append(new) >> print count, '\t', i , '\t',n[i] >> count = count +1 >> break >> else: >> n[i].append(0) >> > > 'cause your not "break"-ing here? but you do in the "if-then" part... It should not break here. Because imagin that the matching 'prv' is somewhere in a line in the middle of the file, the code will break immediately at the first non-matching line. From akuchlin at ute.mems-exchange.org Wed Mar 27 23:39:09 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 28 Mar 2002 04:39:09 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: In article , David Bolen wrote: > Mark's pages are at http://starship.python.net/crew/mhammond/ where > you can download the extensions for any Python release (1.5.2, 2.0, > 2.1 and 2.2). I have vague memories of adding PythonWin to the Python CVS tree being suggested on python-dev long ago. Wonder if that idea should be revived for 2.3? --amk (www.amk.ca) Oh, don't worry; I always leave things till the last moment. -- The Doctor, in "Ghost Light" From tim.one at comcast.net Sat Mar 30 17:29:29 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 17:29:29 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Message-ID: [Guido] >> There's also the issue (which I've seen puzzling even experienced >> Pythonistas who had been away from the language for a while) that if >> you see: >> >> >>> cmp(a, b) >> 1 >> >>> cmp(a, a) >> 0 >> >>> >> >> you might be tempted to believe that cmp() also returned a truth >> value. If ints are not (normally) used for Booleans results, this >> would stand out much more clearly as something completely >> different. [Paul Rubin] > If cmp returns a boolean, it can no longer distinguish the 3 cases > a < b, a == b, or a > b. That is seriously broken. He didn't suggest changing cmp. He's saying that if functions that return bools printed True/False instead of 1/0, people would be much less likely to fall into the trap of believing cmp() returns a bool (cmp() would continue to display not True/False, but little integers). From van at lindbergs.org Tue Mar 26 19:06:32 2002 From: van at lindbergs.org (VanL) Date: Tue, 26 Mar 2002 17:06:32 -0700 Subject: One tiny embedding problem, please Message-ID: <3CA10D08.8000409@lindbergs.org> Hello, Do to various constraints, I am having to use C for a certain project, even after I did the (working!) prototype in Python. I am trying to embed python so as to not lose my work. I have it working and compiling, but I am not getting values out correctly. I think this is just a tiny problem, but I haven't been able to fix it. Code is below, can anyone spot the error? Thanks, VanL Here is the C function: +++++++++++++++++++++++++++++++++++ void getWP(WP *WP_ptr) { int status; PyObject *results; status = PP_Run_Function( "code", "getWP", "O", &results, "(i)", 1); if (status == -1) { printf("\n\nScript Error: Get WP Failed.\n"); PyErr_Print(); } PyArg_ParseTuple(results, "(fff)", &WP_ptr->id, &WP_ptr->x, &WP_ptr->y); Py_DECREF(results); } +++++++++++++++++++++++++++++++++++++ Here is the python being called: +++++++++++++++++++++++++++++++++++++ def getWP(): num = get_sequence() * 1.0 print "I'm returning," (num, 1.0, 2.0) return (num, 1.0, 2.0) +++++++++++++++++++++++++++++++++++++ Here is the test function in C: +++++++++++++++++++++++++++++++++++++ for (i=0; i<2; i++) { x +=2; y +=4; v +=8; printf("\nInput: %d, %d, %d\n", x, y, v); update(x, y, v); printf("Updated."); getWP(WP_ptr); printf("Got WP"); printf("\nOutput: %f, %f, %f\n\n\n", WP_ptr->id, WP_ptr->x, WP_ptr->y); } +++++++++++++++++++++++++++++++++++++++ And here is the output: +++++++++++++++++++++++++++++++++++++++ Input: 2, 4, 8 1 Updated.I'm returning (2.0, 1.0, 2.0) Got WP Output: 0.000000, -1.997108, 0.000000 Input: 4, 8, 16 3 Updated.I'm returning (4.0, 1.0, 2.0) Got WP Output: 0.000000, -1.997108, 0.000000 From duncan at NOSPAMrcp.co.uk Mon Mar 25 09:49:08 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 25 Mar 2002 14:49:08 +0000 (UTC) Subject: Indentation problem References: Message-ID: Gilles Diribarne wrote in news:mailman.1017062259.25098.python-list at python.org: > EXAMPLE: > > pythona.py: > def func(): > a = 1 > if a == 1: > a ==2 > > > > pythonb.py > def func2(): > a = 2 > if a == 2: > print "Yeah!" > > > You cannot merge correctly or tell me how to do this ? > Sadly, neither pythona.py nor pythonb.py is syntactically valid. To make them acceptable to Python, you must remove all the indentation before the 'def' keywords. Once you do this, so that each function begins with a line that is not indented your problem goes away. Just copy and paste the code, and even though the function bodies are indented differently everything will work. In practice copying Python code is less usual than in many other languages because Python makes it so much easier to reuse code in-place without copying. Just remember to put the body of any script in a block with "if __name__=='__main__':" guarding it, and you can then safely import the script and pick out any functions you need at runtime. Code reuse beats copying. BTW, Python does have a block end marker. It is spelled '# end'. Look in your Python installation for the file Tools/Scripts/pindent.py. Running this program with the -c option will 'correct' your code to use the block end marker everywhere. The -d option will make your code readable to everyone else again. If you mess up the indentation then the -r option will use the #end markers to put indentation back in again. See also reindent.py in the same directory for making source files use consistent indentation. -- 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 scarblac at pino.selwerd.nl Mon Mar 25 02:23:47 2002 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 25 Mar 2002 07:23:47 GMT Subject: 2.2 open References: Message-ID: Bengt Richter wrote in comp.lang.python: > ... sort of interesting, FWIW. Has someone done a proper showinfo(x) utility to > do this kind of thing for various objects? Hard to believe not. Try e.g. from pydoc import help help(ValueError) Or even do 'pydoc -p 5000' from a command line, and point your browser at http://127.0.0.1:5000/ Pydoc is neat. -- Remco Gerlich From cjw at sympatico.ca Sun Mar 10 11:07:18 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 10 Mar 2002 11:07:18 -0500 Subject: range Failure? Message-ID: <3C8B84B6.DB3F8E9A@sympatico.ca> Thanks to Oleg and Sean. It was a silly error. Sean, What you say is, on reflection, obvious. Perhaps the doc could better bring this out? The help now has: range([start,] stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the largest start + i * step greater than stop. step must not be zero (or else ValueError is raised). It might say: range([start= 0,] stop[, step= 1]) This function creates a list containing an arithmetic progression. The arguments must be integers. If only one argument is passed it is the 'stop' value, if two values are passed then the first is the 'start' value and the second the 'stop' value. The function returns a list of integers [start, start + step, start + 2 * step, ...]. The 'step' must not be zero; if 'step' is positive, the last element is the largest; if 'step' is negative, the last element is the smallest. Colin W. Sean 'Shaleh' Perry wrote: On 09-Mar-2002 Colin J. Williams wrote: > > > It would seem that the first execution below should deliver the same >
    result as the second. >
    >>> range(5, 2) >
    [] >
    >>> range(0, 5, 2) >
    [0, 2, 4] GAH! kill the html please. range(5,2) says "start at 5 and go to 2" which makes no sense and thus returns an empty list. from the python source: if (PyTuple_Size(args) <= 1) { if (!PyArg_ParseTuple(args, "l;range() requires 1-3 int arguments", &ihigh)) return NULL; } else { if (!PyArg_ParseTuple(args, "ll|l;range() requires 1-3 int arguments", &ilow, &ihigh, &istep)) return NULL; } Look at the last arguments to each funtion. If one argument is passed it because the high value (endpoint). Otherwise the values are assigned in order to low, high and then step (which defaults to 1). From theller at python.net Wed Mar 20 04:10:32 2002 From: theller at python.net (Thomas Heller) Date: Wed, 20 Mar 2002 10:10:32 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: "Martin v. Loewis" wrote in message news:m3pu1z91y6.fsf at mira.informatik.hu-berlin.de... > mlh at vier.idi.ntnu.no (Magnus Lie Hetland) writes: > > > I know there are several solutions available for building standalone > > binary executables from Python programs (Freeze, py2exe, McMillan > > Installer, etc.) -- I just wondered if it would be possible to add > > functionality like this to distutils? > > That is certainly possible; freeze would be the obvious choice for > such a mechanism (IMO). Alas, distutils is unmaintained, so don't wait > for anybody else to implement it for you. > I have never *seriously* tried freeze, maybe I gave up too early. Also I have the impression that some people are actually using freeze, but I never heard definitive words about it's status. Problems with freeze, IMO, are that it requires a C-compiler, which most people on windows do not have, also the resulting files are much larger than those created by py2exe or installer, because the byte codes are not compressed. Thomas From gcordova at hebmex.com Thu Mar 7 10:19:45 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 7 Mar 2002 09:19:45 -0600 Subject: CP4E was Re: Deitel and Deitel Book... Message-ID: <19650FF08A99D511B19E00B0D0F06323060B49@SRM201002> > > By contrast, the child can't converse effectively with his peers for > three to four years, and can't hold his own in a conversation with an > adult for even longer than that. > This is a little something which has always piqued my curiosity. It's true that children sometimes don't make much sense to us ("TO US") until they have breached a certain threshold in knowledge / social rules / vocabulary. But, what about identical twins, who speak their own language well before they start speaking their parents? Aren't they communicating with their peer(s)? I'm not criticising your comment, actually I'm probably proving it by providing the exception :-) Sometimes I wonder if I'd have twice the fun if I was two, er, had a twin. :-) Or maybe I'd be twice as silly and make half as much sense. Have a nice thursday :-) -gustavo From bokr at oz.net Sat Mar 30 00:52:46 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Mar 2002 05:52:46 GMT Subject: string copying References: Message-ID: On Fri, 29 Mar 2002 19:22:45 -0500, Tim Peters wrote: >[Peter Hansen] >> The only one I've been able to think of is the surprisingly >> common situation of trying to consume vast quantities of memory >> quickly by something like: >> >> a = [0] * 1000000 >> for i in xrange(1000000): >> a[i] = 'bigstringsuckinguplotsofmemory' > >Hmm. A much easier way to consume vast quantities of memory quickly is to >skip the for-loop and just increase the multiplier on the first line. If >you're on a 32-bit machine, and want to consume N bytes, use N/4 as the >multiplier. > s = 'x'*2**30 would be a quick gig too. But it made me think maybe one could write a sort of memory test (to exercise the available python space, anyway). Does python run out of memory gracefully? I'm afraid to try it (have NT4, 320MB, and too many things running a lot). Anyway, one could generate binary patterns and chr() the 8-bit pieces and join them into say megabyte chunks, and then compare sequentially with a the regenerated sequence. And do it for different patterns. Not like doing it from a bootable floppy, but still some exercise. You could use long random sequences. ... hm, I wonder if dual CPUs running in a dedicated test would have a better chance of jangling motherboard signals with patterns beating against each other than a single CPU... Regards, Bengt Richter From mstenner at phy.duke.edu Fri Mar 15 08:27:05 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 15 Mar 2002 08:27:05 -0500 Subject: further infos In-Reply-To: ; from s.ernst@web.de on Fri, Mar 15, 2002 at 02:11:43PM +0100 References: Message-ID: <20020315082705.A17341@phy.duke.edu> On Fri, Mar 15, 2002 at 02:11:43PM +0100, Sascha Ernst wrote: > 1. "command not found" is the error message. how can I get more detailed > infos? > 2. the dev tools are ok, I compiled Ruby some days ago successfully whaaa? 1) this is a python list... not a ruby list... 2) I'll try and employ my ESP anyway: "command not found" is a common shell error. Are you running (python or ruby, whatever) under unix? If so, do you have the proper shebang? For example, your files should probably start with #!/usr/bin/env python If this isn't there, the file will usually be interpreted as a shell script and almost certainly throw errors. This can be unpleasant if the first non-comment is an import :) 3) you get more detailed infos when you give us more detailed infos :) -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From aahz at pythoncraft.com Tue Mar 12 08:37:32 2002 From: aahz at pythoncraft.com (Aahz) Date: 12 Mar 2002 08:37:32 -0500 Subject: PEP 284, Integer for-loops (fwd) References: Message-ID: In article , Tim Peters wrote: > >there's-more-than-one-to-do-indirection-in-python-ly y'rs - tim TMTOWTDI?!?!?!?! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From amoustafa at pobox.com Thu Mar 21 02:55:05 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Thu, 21 Mar 2002 07:55:05 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> Message-ID: <3C9991C0.4080102@pobox.com> Peter Hansen wrote: > > Here's my best answer to you: I happen to hire programmers > to work on my team in a wireless telecom company. Although > we happen to have chosen to use Python in addition to C and > a few minor languages like Javascript and Assembly, where > necessary, the language we use is hardly the most important > thing. > > Communication skills are, first and foremost, the thing I > look for in hiring. This includes the softer social skills > like how to work in a team and put aside one's programming > ego. Next are adaptability, as in how easily someone can > pick up new skills and apply them effectively. Design > skills are useful. Debugging skills are very valuable, > though rather unfortunately rare. Probably some others > that don't come to mind in today's economy (we're not > hiring now :-). Peter, what do you think about qualifying problem sets like what arsDigita had? -- Ahmed Moustafa From mwh at python.net Wed Mar 13 13:18:08 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 13 Mar 2002 18:18:08 GMT Subject: Newbie: Undefined reference when initializing Python References: Message-ID: "henrikb666" writes: [...] > I already include at the top of the TServer.cc file, so > that's not it. Could it have something to do with my Makefile? You need to link to Python; there should be a "-lpython" in there somewhere (and probably a "-L/some/path/or/other/" too). Cheers, M. -- There's an aura of unholy black magic about CLISP. It works, but I have no idea how it does it. I suspect there's a goat involved somewhere. -- Johann Hibschman, comp.lang.scheme From logstx at bellatlantic.net Wed Mar 20 18:08:33 2002 From: logstx at bellatlantic.net (logistix) Date: Wed, 20 Mar 2002 23:08:33 GMT Subject: Develop-test-debug cycle References: Message-ID: Like Tim said, the module is getting reloaded but instances aren't getting re-instantiated. If it's not too time-intensive, use the if __name__=="__main__" trick in your script. if __name__ == "__main__": reload(wibbleModule) wibs = wibble(args) wibs.test1() wibs.test2() and just run it again from the interpreter. If that's too slow and you want to use some really bad voodoo, you can also modify the classes in-place: PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> class foo: ... def meth(self): ... print "xxx" ... >>> bar = foo() >>> bar.meth() xxx >>> def newMeth(self): ... print "yyy" ... >>> foo.meth = newMeth >>> bar.meth() yyy -- - "Dale Strickland-Clark" wrote in message news:un2h9ukh13kddcd3ooc9osejapiaf5v6t3 at 4ax.com... > I can't believe I'm doing this this best way. > > I am debugging a large system written in Python with modules spread > over 4 directories. I'm using PythonWin under Win2K to set-up the > environment and run the code. > > Setting up the environment typically involves the following commands: > > import sys > sys.path.append("x:\\whereever") > from wibbleModule import wibble > wibs = wibble(args) > > wibs.methods(args) > > > > At this point, I fix the error. > > Now, I haven't figured out a way of continueing past this point > without quiting and starting from scratch because there appears to be > no way to get Python to reload a module. The reload() function doesn't > do it. > > I've tried stuff like this: > > del wibs > reload(sys.modules['wibbleModule'] > > but I still seem to have the old version loaded. > > I've also tried using PyCrust for this but it suffers from the same > problems. I assume IDLE does too. > > How do others go about interactively debugging large Python OO-based > systems? > > Thanks for any pointers. > -- > Dale Strickland-Clark > Riverhall Systems Ltd From evebill8 at hotmail.com Fri Mar 15 03:00:33 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Fri, 15 Mar 2002 08:00:33 GMT Subject: socket Message-ID: I am trying to write a python program to verify the email address. Here is what I am going to do: Establish the connection to the t:25 If I get code 220 send command HELO: If I get code 250 send command MAIL FROM: If I get code 250 send command RCPT TO: If I get code 550 the recipient address does not exist else the recipient address exists In fact, I could send VRFY: to shorten the code, but I notice so many SMTP server does not allow VRF command. I also notice the many SMTP server denies the RCPT TO command too. If you have down something like this, please tell how did you do it. Thanks in advance! Billy Ng From plugin at airtel.net Mon Mar 4 10:23:28 2002 From: plugin at airtel.net (VUG) Date: Mon, 4 Mar 2002 16:23:28 +0100 Subject: C++, Python & Threads References: <1015181073.276455@seux119> Message-ID: <1015255451.705549@seux119> "Martin v. Loewis" escribi? en el mensaje news:m3elj1weyv.fsf at mira.informatik.hu-berlin.de... > "VUG" writes: > > > When I launch python console and I create a thread I get a NUMBER but...... > > This number doesn't the same as the one I get by the function > > thread.get_ident(). What's wrong in the code? > > PyThread_get_thread_ident, having no parameters, always returns the > thread id of the calling thread. If you want the thread id of the new > thread, you need to invoke PyThread_get_thread_ident inside of the new > thread. > > BTW, in Python 2.2, start_new_thread does return the thread id of the > new thread. > > HTH, > Martin > Ok. Thanks. I've taking a look at Python 2.2 and it works in the way I need. But I still having problems. I've embedded Python in my application so I need to modify Python source. I can't find this source in the Python's Home page. Isnt't the source code for Python 2.2 available? If not, How can I modify python 1.6.1 source in order to work the way I need? Thank a lot --VUG From herrn at gmx.net Tue Mar 19 08:26:36 2002 From: herrn at gmx.net (Marco Herrn) Date: Tue, 19 Mar 2002 14:26:36 +0100 Subject: inheriting from curses window-objects Message-ID: <20020319132636.GA10465@lurkabove.darkstar> Hi, i would like to create window-objects that are derived from the standard curses windows (like window or pad). But I don't see any way to achieve this. Is this possible? Or would I have to write a "new curses library" to get real objects for window, one can inherit from? Bye Marco -- If you cannot convince them, confuse them. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From tim.one at comcast.net Mon Mar 4 03:03:19 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 04 Mar 2002 03:03:19 -0500 Subject: PEP 276 -- What else could iter(5) mean? In-Reply-To: Message-ID: [David Eppstein] > Here's another way of looking at the same question. > An iterable object has a next() function, that's what it means to be > iterable. An iterable object A is one that iter(A) doesn't barf on . For example, lists are iterable objects but don't have a .next() method. It's an iterat*or* that needs a next() method; an iter*able* object is one that iter() knows how to get an iterator for. >>> [].next Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute 'next' >>> iter([]).next >>> > If numbers are iterable, we can call number.next(), right? It's such a pretty point I hate to spoil it, but no. If numbers are iterable, then we can call iter(number).next(). > So what should 5.next() be? SyntaxError as given, AttributeError if "(5).next()" instead, and by the time we get to the "iter(5).next()" that should actually do something besides blow up, the presence of iter() spoils the point. > Surely anyone familiar with the Peano axioms would say 6, not 0! If ints did have a .next() method, then I expect most people would expect 6 even if Peano had said succ(i) == -42 . From emile at fenx.com Thu Mar 28 18:14:50 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 28 Mar 2002 15:14:50 -0800 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: John Machin > Python *could* be made like that with the explict dict() constructor > ... something like: > > freq = dict(default=0) > ... > freq[word] += 1 Or you could subclass with something like: >>> class ddict(dict): ... def __getitem__(self, ky): ... return self.setdefault(ky, self.default) ... def __init__(self, default=None): ... self.default = default ... >>> d = ddict(0) >>> d['a']+=1 >>> d['a'] 1 -- Emile van Sebille emile at fenx.com --------- From sdm7g at Virginia.EDU Tue Mar 19 11:30:19 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Tue, 19 Mar 2002 11:30:19 -0500 (EST) Subject: RELEASED: Python 2.2.1c1 In-Reply-To: <15510.53493.198841.313608@12-248-41-177.client.attbi.com> Message-ID: On Mon, 18 Mar 2002, Skip Montanaro wrote: ... > sinh > sqrt > tan > tanh > exceptions > Traceback (most recent call last): > File "Lib/test/test_math.py", line 195, in ? > test_exceptions() > File "Lib/test/test_math.py", line 192, in test_exceptions > raise TestFailed("sqrt(-1) didn't raise ValueError") > test_support.TestFailed: sqrt(-1) didn't raise ValueError > I got the same on my osx build. Specifically: math.sqrt( -1 ) returns NaN. When I do: import fpectl fpectl.turnon_sigfpe() I get: 'Operation not implemented' Are those two connected? -- Steve Majewski From ron at ire.org Fri Mar 1 11:50:42 2002 From: ron at ire.org (ron nixon) Date: 1 Mar 2002 08:50:42 -0800 Subject: Does python have a function like similar_text in PHP Message-ID: <61ff32e3.0203010850.3aedc22f@posting.google.com> List: Does anyone know if Python has a function like similar_text in PHP. It compares two strings and returns a percentage for the match. Anyone know of anything like this in Python and would be willing to send along an example? Ron From dale at riverhall.NOTHANKS.co.uk Wed Mar 13 19:46:39 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 14 Mar 2002 00:46:39 +0000 Subject: win32 extension: rare PythonService problem References: Message-ID: bokr at oz.net (Bengt Richter) wrote: >On 10 Mar 2002 21:55:37 GMT, bokr at oz.net (Bengt Richter) wrote: >[...] >>But I'd check the event logs (run "%SystemRoot%"\system32\eventvwr.exe) first > >Oops, misplaced quote, that won't work verbatim. Try > > "%SystemRoot%\system32\eventvwr.exe" > Actually, either quoting approach works fine with NT/W2K. -- Dale Strickland-Clark Riverhall Systems Ltd From bhat at cs.mu.oz.au Mon Mar 18 17:22:46 2002 From: bhat at cs.mu.oz.au (Tim Bell) Date: 18 Mar 2002 14:22:46 -0800 Subject: Text Search Engine that works with Python References: <88bc63c6.0203071841.1867a977@posting.google.com> Message-ID: <22732848.0203181422.186670b@posting.google.com> Fernando Rodr?uez wrote in message news:... > On 7 Mar 2002 18:41:45 -0800, writeson at earthlink.net (Doug Farrell) wrote: > > >is because of all the other media that goes on the CD. Our current > >search engine is a piece of junk, but works in the C++ environment of > >our current application, which is only for Windows. I am considering > Whatever you use, you will probably have to write the Python interface. > If I was in your situation I would write a Python interface to the mg system > that someone already recommended to you... MG has already been adapted for use on multimedia CD ROMS as the Greenstone Digital Library software . Most of the work was done at the University of Waikato in Hamilton, NZ, and I'm sure it would be worth your while investigating their approach. (They don't use Python anywhere, to my knowledge.) While the Greenstone system is cross-platform (including even Windows 3.1), there is considerable effort required in getting it to work on each platform. Clearly a language such as Python (coupled with a suitable GUI toolkit) would be very useful here. Also, if you start getting into implementing a new text indexing and compression system, or even just building a Python API for MG, I strongly recommend you read Managing Gigabytes, 2nd Edition, by Witten, Moffat and Bell; Morgan Kaufmann, 1999. (My name is similar to the third author's, but we're different people.) There's more info about the book here: . Much of the work they describe has been implemented in the MG system. Tim. -- Tim Bell - bhat at cs.mu.oz.au - Dept of Comp Sci & SE - Uni of Melbourne, Aust. From mwh at python.net Wed Mar 13 05:20:57 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 13 Mar 2002 10:20:57 GMT Subject: structseq and keywords? References: Message-ID: quinn at vomit.ugcs.caltech.edu (Quinn Dunkan) writes: > Is structseq supposed to take keyword args? From the source I assume it was > meant to, but they're unused. Well, in 2.2 it takes one keyword argument -- "sequence". In 2.2.1 and 2.3 it will take another one -- "dict". This is the result of some hacking I did a week or so ago related to pickling the buggers. > I suppose they'd interact poorly with sequence args, but I'd expect > them to be mutually exclusive: > > ss(attr=bar) #-> attr set to bar, rest set to None > ss(a, b, c) #-> initialize with (a, b, c) You'd have to write that last ss((a,b,c)) ... > It also seems odd that structseq expects a single sequence rather than a > variable number of args. ... but it seems you already know this. In the current implementation, you're not really expected to create structseq objects. Why would you? > I've been meaning to give python access to structseqs, since I think > it would be useful for python as well as C code. Hmm. I think they're a bit specialized for that. You could probably whip up something nearly equivalent... class StructSeq(object): def __init__(self, *args, **kw): slots = self.__class__.__slots__[:] for name, arg in zip(slots, args): setattr(self, name, arg) slots.remove(name) for key in kw: if key not in slots: raise ValueError setattr(self, key, kw[key]) slots.remove(key) for name in slots: setattr(self, name, None) def __getitem__(self, i): return getattr(self, self.__class__.__slots__[i]) class stat_result(StructSeq): __slots__ = ['st_size', 'st_dev', 'st_atime'] >>> sr = stat_result(2, st_atime=3) >>> sr.st_size 2 >>> sr[1] >>> sr = stat_result(2, st_size=3) Traceback (most recent call last): File "", line 1, in ? File "", line 9, in __init__ ValueError >>> tuple(sr) (2, None, 3) >>> Doesn't do everything structseqs do, but that's mostly a matter of typing. Cheers, M. -- Windows installation day one. Getting rid of the old windows was easy - they fell apart quite happily, and certainly wont be re-installable anywhere else. -- http://www.linux.org.uk/diary/ (not *that* sort of windows...) From timo at alum.mit.edu Sat Mar 16 00:35:12 2002 From: timo at alum.mit.edu (Timothy O'Malley) Date: Sat, 16 Mar 2002 00:35:12 -0500 Subject: timeoutsocket.py -- Version 1.23 Message-ID: hola. I've updated the timeoutsocket module with the following two fixes: 1. The recv() method did not work with recv(0) when the socket was closed. This was causing problems with httplib in 2.2. There was a condition test that used > when it should have used >= instead. 2. The readlines() method should no longer potentially lose data when a Timeout exception is thrown. As usual: http://www.timo-tasi.org/python/timeoutsocket.py Happy python-ing! TimO From just at xs4all.nl Tue Mar 26 10:22:03 2002 From: just at xs4all.nl (Just van Rossum) Date: Tue, 26 Mar 2002 16:22:03 +0100 Subject: Optimizations (was Re: reduce vs. for loop) References: Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > >Just out curiosity, > >why is fact2 a bit faster than fact1? > > > >def fact1(n): > > return reduce (operator.mul, range(1L,n + 1)) > > > >def fact2(n): > > result = n * 1L > > for i in range(1 , n): > > result *= i > > return result > > Try this: > > def fact3(n): > mul = operator.mul > return reduce(mul, range(1L, n+1) ) operator.mul will be evaluated only once in even in fact1, so this shouldn't make any difference. Just From usenet at thinkspot.net Sun Mar 17 15:44:46 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 12:44:46 -0800 Subject: Still same bug even with email ver. 1.2 Message-ID: [reference link, for those just now joining this discussion: http://mail.python.org/pipermail/python-list/2002-March/093191.html ] OK, I got the latest email module from the CVS. I installed it. I ran the tests for the module. Everything tested out fine. I now eagerly get out my code from last night, that was causing the 'int' has no attribute .lower error, and run it, hoping for different results. No good. Same results. :( File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Message.py", line 285, in get name = name.lower() AttributeError: 'int' object has no attribute 'lower' Here is all the data and code necessary for you to run this test, also: ### main program file ### parsertest.py from cStringIO import StringIO from SmartParser import SmartParser import sys, traceback try: f = open('problem_multipart_virus.txt', 'r') fp = StringIO(f.read()) parserobj = SmartParser() msg = parserobj.parse(fp) count = 0 print "msg.get_params() = ", msg.get_params() if msg.preamble: print "preamble = ", preamble if msg.epilogue: print "epilogue = ", epilogue print "payload = ", msg.get_payload() print "now walking parts:" count = 0 for part in msg.walk(): print "part ", count, " = ", part count += 1 except: exc, val, tb = sys.exc_info() f = open('err.txt', 'w') traceback.print_exception(exc, val, tb, file=sys.stdout) ### class file ### SmartParser.py from email.Parser import Parser import email print "starting init of SmartParser" print "email.__version__ = ", email.__version__ class SmartParser(Parser): def _parsebody(self, container, fp): print "\n*** beginning SmartParser._parsebody() ***" boundary = container.get_boundary() print "type = ", container.get_type() isdigest = (container.get_type() == 'multipart/digest') if container.is_multipart(): print "multipart" if boundary: preamble = epilogue = None separator = '--' + boundary payload = fp.read() start = payload.find(separator) if start < 0: container.add_payload(fp.getvalue()) if start > 0: preamble = payload[0:start] start += len(separator) + 1 + isdigest terminator = payload.find('\n' + separator + '--', start) if terminator < 0: terminator = len(payload) if terminator + len(separator) + 3 < len(payload): epilogue = payload[terminator + len(separator) + 3:] if isdigest: separator += '\n\n' else: separator += '\n' parts = payload[start:terminator].split('\n' + separator) print "parts = ", str(parts) for part in parts: msgobj = self.parsestr(part) container.preamble = preamble container.epilogue = epilogue container.add_payload(msgobj) print "*** end SmartParser._parsebody ***\n" ### data file ### problem_multipart_virus.txt Received: from aol.com (adsl-63393.turboline.skynet.be [217.136.119.161]) by excalibur.skynet.be (8.11.6/8.11.6/Skynet-OUT-2.16) with SMTP id fBJ8Iu829963 for ; Wed, 19 Dec 2001 09:18:56 +0100 (MET) (envelope-from ) Date: Wed, 19 Dec 2001 09:18:56 +0100 (MET) Message-Id: <200112190818.fBJ8Iu829963 at excalibur.skynet.be> From: "John Doe" <_removed at infonie.be> To: webmaster at leonbergerdatabase.com Subject: Re: MIME-Version: 1.0 Content-Type: multipart/related; type="multipart/alternative"; boundary="====_ABC1234567890DEF_====" X-Priority: 3 X-MSMail-Priority: Normal X-Unsent: 1 --====_ABC1234567890DEF_==== Content-Type: multipart/alternative; boundary="====_ABC0987654321DEF_====" --====_ABC0987654321DEF_==== Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable --====_ABC0987654321DEF_====-- --====_ABC1234567890DEF_==== Content-Type: audio/x-wav; name="stuff.MP3.pif" Content-Transfer-Encoding: base64 Content-ID: TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAA8AAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1v ZGUuDQ0KJAAAAAAAAAAoxs1SbKejAWynowFsp6MBF7uvAWinowHvu60BbqejAYS4qQF2p6MBhLin WHAA/kVwAPw2cAD+KXAA+BxwAPz2cAD+GQAAAAAAAP4BAAAAAAAAAAAAAAAAAAD8QgAAAAAAAAAA /l/9D/3yCg== --====_ABC1234567890DEF_==== ### results file ### output.txt starting init of SmartParser email.__version__ = 1.2 *** beginning SmartParser._parsebody() *** type = multipart/related parts = ['Content-Type: multipart/alternative;\n\t boundary="====_ABC0987654321DEF_===="\n\n--====_ABC0987654321DEF_====\nContent-Type: text/html;\n \t charset="iso-8859-1"\nContent-Transfer-Encoding: quoted-printable\n\n\n\n\n--====_ABC0987654321DEF_====--\n', 'Content-Type: audio/x-wav;\n\t name="stuff.MP3.pif"\nContent-Transfer-Encoding: base64\nContent-ID: \n\nTVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAA8AAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1v\nZGUuDQ0KJAAAAAAAAAAoxs1SbKejAWynowFsp6MBF7uvAWinowHvu60BbqejAYS4qQF2p6MBhLin\nWHAA/kVwAPw2cAD+KXAA+BxwAPz2cAD+GQAAAAAAAP4BAAAAAAAAAAAAAAAAAAD8QgAAAAAAAAAA\n/l/9D/3yCg==\n', '\n'] *** beginning SmartParser._parsebody() *** type = multipart/alternative parts = ['Content-Type: text/html;\n \t charset="iso-8859-1"\nContent-Transfer-Encoding: quoted-printable\n\n\n\n'] *** beginning SmartParser._parsebody() *** type = text/html *** end SmartParser._parsebody *** *** beginning SmartParser._parsebody() *** type = audio/x-wav *** beginning SmartParser._parsebody() *** type = None *** end SmartParser._parsebody *** msg.get_params() = [('multipart/related', ''), ('type', 'multipart/alternative'), ('boundary', '====_ABC1234567890DEF_====')] payload = [, , ] now walking parts: part 0 = Traceback (most recent call last): File "parsertest.py", line 20, in ? print "part ", count, " = ", part File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Message.py", line 73, in __str__ return self.as_string(unixfrom=1) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Message.py", line 83, in as_string g(self, unixfrom=unixfrom) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 79, in __call__ self._write(msg) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 100, in _write self._dispatch(msg) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 130, in _dispatch meth(msg) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 246, in _handle_multipart g(part, unixfrom=0) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 79, in __call__ self._write(msg) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 100, in _write self._dispatch(msg) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 130, in _dispatch meth(msg) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Generator.py", line 243, in _handle_multipart for part in msg.get_payload(): File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Message.py", line 222, in __getitem__ return self.get(name) File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Message.py", line 285, in get name = name.lower() AttributeError: 'int' object has no attribute 'lower' Notice that if I change the following lines in the parsetest.py file count = 0 for part in msg.walk(): print "part ", count, " = ", part count += 1 to count = 0 for part in msg.walk(): print "count = ", count count += 1 That the code then runs fine without generating an error. So, I am able to parse the message into parts, I am able to walk the parts. I am only getting an error when I try to print a string representation of the part. :( What should I try next ???? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From junkster at rochester.rr.com Sun Mar 17 19:16:00 2002 From: junkster at rochester.rr.com (Benjamin Schollnick) Date: Sun, 17 Mar 2002 19:16:00 -0500 Subject: Eliminate Spam Now... >g< Python w/DNS/&POP3 In-Reply-To: <20020317144859.B18963@glacier.arctrix.com> Message-ID: on 3/17/02 5:48 PM, Neil Schemenauer at nas at python.ca wrote: > You don't need DNSlib. socket.gethostbyname() works fine. Check out my > spamhunter script? for example code. > > Neil > > ? http://arctrix.com/nas/python/spamhunter.py Neil, Your script is quite helpful, but I don't follow your suggestion about not needing DNSlib. gethostbyname would resolve to the IP address of the spammer, but it doesn't do any checking against the blacklists....The only exception that I can think of would be if you were using the blacklist organizations DNS servers as your primary DNS server??? - Benjamin From john at yahoo.com Mon Mar 25 17:10:07 2002 From: john at yahoo.com (John Warney) Date: Mon, 25 Mar 2002 22:10:07 GMT Subject: question on slices Message-ID: I am sorta new to programming, i have had an intro to programming using C++ and thats it. Other than that i have kinda read a few things but now i am into Python.....blah blah blah..... The issue that i have a problem with is slices. for instance let me show you a snippet: >>> numlist=[0, 1, 2, 3] >>> numlist[1] 1 >>> numlist[2] 2 >>> numlist[1:2] [1] This last one doesnt make since to me since i am asking for a range from 1-2. Why in the world does it give me 1 when i am asking for 1-2 which would logically be: >>> numlist[1:2] [1, 2] but it's not. it doesnt make since. Just seems strange when i just was in a C++ class and it would do the logical thing. Rob From martin at v.loewis.de Wed Mar 27 14:35:27 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Mar 2002 20:35:27 +0100 Subject: os.fchown, avoiding a race condition References: Message-ID: jimd at vega.starshine.org (Jim Dennis) writes: > If would be cool if os.chown was overloaded to take > *either* a patch *or* a file descriptor (from ^^^^^file? > file_instance.fileno()) as its first argument. There are already a number of f* functions exposed in posixmodule.c (fstat, ftruncate, fsync, fdatasync, fstatvfs, fpathconf); a patch adding fchown would certainly be accepted. If you want polymorphism, you need to come up with a way of doing it uniformly; that would require a PEP, documentation changes, and testsuite additions (fchown would also require documentation changes). Regards, Martin From gimbo at ftech.net Wed Mar 20 12:07:40 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 20 Mar 2002 17:07:40 +0000 Subject: Popular style document? In-Reply-To: <1016641355.370859@cswreg.cos.agilent.com> References: <1016641355.370859@cswreg.cos.agilent.com> Message-ID: <20020320170740.GH18847@andy.tynant.ftech.net> On Wed, Mar 20, 2002 at 01:52:35PM +0000, Greg Weeks wrote: > Is there a popular style document for Python? I realize that there isn't a > whole lot of scope for such a thing, but I wondered because of certain > particular issues that came to mind. http://python.sourceforge.net/peps/pep-0008.html http://python.sourceforge.net/peps/pep-0257.html > 1. I use "me" instead of "self" in method definitions. I mention this not > to ask what people think -- I have an unpleasant suspicion -- but because > I'll be using "me" below. Bad boy. :-) > 2. How should methods call other methods? Suppose that show_and_tell() > simply calls show() and then tell(). Let the class be, say, "Demo". Then > there are two choices: > > def show_and_tell(me): > me.show() > me.tell() Correct and moral. :-) > def show_and_tell(me): > Demo.show(me) > Demo.tell(me) Pointless except when Demo is a subclass, AFAIK. If anyone knows better, I'd love to hear about it and increase my knowledge. :-) > These have different semantics for subclasses, but I would hate to choose > based on that. I simply use the first alternative. But only the second > alternative was given in "Python Essential Reference" (by David Beazley). > So I wonder. Gosh. That really surprises me. Are you sure the book wasn't talking about subclasses at that point? > 3. Personally, I think that code is more readable (at least sometimes) > when global variables are "declared". But how? If within a comment, what > form does the comment take? Unable to answer that question, I found myself > using a "global" statement, which is semantically a no-op and only > acceptable if the reader knows what the heck it is doing there. The "global" statement certainly isn't a no-op, and it's definitely not just for readability - it can totally change your program's logic! Check out the attached global.py for a quick demo of how I tend to use it. This isn't the full story but should hopefully convince you it's not a no-op. For completeness, here's the output I get when I run global.py: [gimbo at andy python]$ ./global.py Foo: 0 Foo: 1 Foo: 1 vikings inside beans(): 3 vikings outside beans(): 3 vikings outside beans(): 6 vikings inside beans(): 3 Traceback (most recent call last): File "./global.py", line 55, in ? print dinsdale NameError: global name 'dinsdale' is not defined Hope this helps, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. -------------- next part -------------- #!/usr/bin/env python # I always declare globals at the top, out of force of habit. But see # the beans() function, below. foo = 0 def spam(): # We use a global declaration to tell spam() that when we say foo, # we mean the one defined above. global foo foo = 1 def eggs(): # Here, foo is local to eggs(), and the foo defined above is # untouched. So calling eggs() makes no change. foo = 2 def beans(): # Globals can be declared anywhere in a module global vikings vikings = 3 print "vikings inside beans(): %d" % (vikings,) def gumby(): # If this doesn't get called, referencing dinsdale anywhere else # will result in a NameError global dinsdale dinsdale = 4 print "Dinsdale in vikings: %d" % (dinsdale,) # See how foo changes over these calls... print "Foo: %d" % (foo,) spam() print "Foo: %d" % (foo,) eggs() print "Foo: %d" % (foo,) # Now we demonstrate that a global can be defined anywhere. beans() print "vikings outside beans(): %d" % (vikings,) # However, if we modify it here without first declaring global in # thise scope, we're creating a completely different variable which # just happens to have the same name, so when we call beans() again, # it won't have changed since last time. vikings = 6 print "vikings outside beans(): %d" % (vikings,) beans() # Finally, we try to access dinsdale, which fails because gumby() # hasn't been called yet. print dinsdale From tim.one at comcast.net Sun Mar 24 18:53:41 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 24 Mar 2002 18:53:41 -0500 Subject: 2.2 open In-Reply-To: Message-ID: [Martin v. Loewis] > Correction: open is file. Just try it > > >>> open is file > 1 > > So open is the type of file objects. Na, file is the type of file objects: >>> type(sys.stdout) >>> type(sys.stdout).__name__ 'file' "open" was made identical to "file" just so open(filename) would continue to work as before. Once you get used to it, it's more natural to say file(filename) in 2.2 (for much the same reason it's long been more natural to say int("42") than string.atoi("42")). From joonas at olen.to Sun Mar 10 17:34:39 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Mon, 11 Mar 2002 00:34:39 +0200 Subject: import gadfly causes 500 Server Error -- anyone know how to fix? References: <3C8AFB43.275714BB@erols.com> Message-ID: <3C8BDF7F.5F386023@olen.to> Jerry Gitomer wrote: > > Hi, > > I have an application I am porting from Python with Tkinter to > Python on the Web. > I built my first set of scripts by copying something that worked > and then modifying > one idea at a time. Everything was fine until I tried to add a > query into a gadfly database. > > I discovered that adding the "import gadfly" statement results > in: > > 500 Server Error > > The server encountered an internal error and could not complete > your request. > > Anyone have any ideas on why and how to fix? Insert these lines just above the line where you import gadfly. It causes the traceback to be printed to browser. Or if you are using Python 2.2, you should use cgitb module. import sys sys.stderr = sys.stdout print "Content-type: text/plain" print From tejarex at yahoo.com Fri Mar 29 18:00:02 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 29 Mar 2002 23:00:02 GMT Subject: List problem References: <3CA4E7C6.EDE85B98@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3CA4E7C6.EDE85B98 at engcorp.com... > Jon Cosby wrote: > > lword = len(firstword) You missed that lword *is* the length of firstword, not firstword itself, making > That finds the line matching lword and appends it to words, I think, > which is another way of saying that every instance of lword in the > dict.txt file will be appended to the words list. Strange... and > For every character in lword, append an empty list to the rows > and columns? If that's what you want, you need range(len(lword)) and > Same problem as above... use len() with range(). invalid. I am still looking for what is wrong. Terry J. Reedy From andreas at mtg.co.at Tue Mar 12 13:41:45 2002 From: andreas at mtg.co.at (Andreas Kostyrka) Date: Tue, 12 Mar 2002 19:41:45 +0100 Subject: File Attributes conversion In-Reply-To: <2030665d.0203080406.5b1b008b@posting.google.com> References: <2030665d.0203040431.1279d1ab@posting.google.com> <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> <2030665d.0203070126.55addc33@posting.google.com> <3C87A28B.549D9B1C@noaa.gov> <2030665d.0203080406.5b1b008b@posting.google.com> Message-ID: <20020312194145.0c968c64.andreas@mtg.co.at> On 8 Mar 2002 04:06:42 -0800 sam_collett at lycos.co.uk (Sam Collett) wrote: > How would you remove trailing 0's? > e.g. > Instead of 12.20kb it would be 12.2kb > 23kb instead of 23.00 etc >>> "%f" % 2.0 '2.000000' >>> "%.0f" % 2.0 '2' Andreas From ark at research.att.com Sun Mar 31 00:46:12 2002 From: ark at research.att.com (Andrew Koenig) Date: Sun, 31 Mar 2002 05:46:12 GMT Subject: Subclass sadness (was Re: [Python-Dev] PEP 285: Adding a bool type) References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: Aahz> Instead of circle/ellipse, it's slightly easier to talk about Aahz> square/rectangle. In terms of standard geometry, a square is a Aahz> subset of rectangles, such that height and width are identical. Aahz> But in OO terms, it's a bit more complicated to inherit square Aahz> from rectangle, because square has only side-length attribute Aahz> where rectangle has two (height and width). So to create a Aahz> class square that inherits from rectangle, you either have to Aahz> write special code that ties height and width together or you Aahz> have to delete at least one of the attributes (in which case any Aahz> code expecting to work with rectangle fails). Right you are. The other way around -- inheriting rectangle from square -- would seem to make more sense because a rectangle has all the information that a square does, and then some. But that doesn't really work either, because then you can no longer assume that every kind of square is really a square. After all, it might be a rectangle. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From brueckd at tbye.com Tue Mar 12 12:39:02 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 12 Mar 2002 09:39:02 -0800 (PST) Subject: programming h----ng In-Reply-To: <3AAC52DF.420FB510@netscapeonline.co.uk> Message-ID: > canyou help please > please please please please please Ah yes, the age-old topic of programming humming. A lot of times I'll listen to the same collection of music for a given project, and so I end up humming those same tunes all day long. What is really weird is how quickly my mind gets back into that particular project when I start humming (or just hear) that same bit of music again. As far as helping you, I'd really recommend that you vary quite frequently your tune selection (there's some good Internet radio stations if your mp3 collection isn't large enought). There's nothing worse than ruining a great CD because hearing it reminds you of some awful project you worked on. U2's Achtung Baby will forever remind me of a really buggy HTTP client. :( HTH, Dave P.S. I suddenly realized that your subject line may have been referring to programming honking. If so, there are some great sound libraries out there - do a quick Google search. From db3l at fitlinxx.com Tue Mar 19 18:12:08 2002 From: db3l at fitlinxx.com (David Bolen) Date: 19 Mar 2002 18:12:08 -0500 Subject: os.popen4 and exit codes References: <3C966B18.BB1E81BD@bgb.cc> Message-ID: "Donn Cave" writes: > On UNIX, popen3 is implemented in Python, out of fork and pipe functions, > and unlike popen it returns 100% stock, common file objects. > > To get exit status, you have to use the Popen3 class explicitly, so you > can call its wait() function. Right - the Windows behavior is sort of a kludge (albeit a convenient one) because of the lack of an equivalent capability in terms of how the child process is controlled. Earlier implementations (the os.popen# functions originated as a contribution to the win32all package) lost the exit code under Windows entirely :-) Unfortunately, it makes handling this platform-dependent, but at least you can get the exit codes in general. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From gh_pythonlist at gmx.de Fri Mar 8 10:31:12 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 8 Mar 2002 16:31:12 +0100 Subject: returning a picture In-Reply-To: References: Message-ID: <20020308153112.GB2591@lilith.hqd-internal> Le 08/03/02 ? 14:32, Peter Posselt Vestergaard ?crivit: > Hi > I would like to be able to enter an URL to a python script in the src field > of an img tag in html. The script is then supposed to return a picture which > will be shown in the html-page. > I am loading and editing the picture the Python Image Library (PIL) but how > should I return/print it to do what I want? In the CGI script that will return the image, just set the appropriate content type and then write the image data, something like (for a jpeg image): print "Content-type: image/jpeg\n\n" sys.stdout.write(imagedata) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 10.6 ?C Wind: 2.6 m/s From grumble at lycos.com Mon Mar 11 08:04:51 2002 From: grumble at lycos.com (jcm) Date: 11 Mar 2002 13:04:51 GMT Subject: Modulo operator : differences between C and Python References: <3C8BE537.74E55963@mega-nerd.com> <29e28c51.0203102042.76ac31b7@posting.google.com> Message-ID: A better name might be rem, as this produces the remainder of x/y. Python returns what most would call the modulus. Cimarron Taylor wrote: >> Anybody have any idea why this is? >> Erik > I encountered this as well in an application which needed to > verify the results of a C program. Python seems to be counting > "down" from y if x<0. I simply compensated for this with > the following function: > def mod(x,y): > m = x%y > if m==0 or x>0: return m > return m-y > Another thing to watch out for when comparing results from Python and > C include is overflow/underflow behavior of the math operations. > Cim From gerhard at bigfoot.de Sat Mar 30 23:00:53 2002 From: gerhard at bigfoot.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 30 Mar 2002 20:00:53 -0800 Subject: [ANN] PYNOSPAM 0.1 (and some Embedded-Python-Questions) References: <3ca4b9e8.10558859@news.t-online.de> Message-ID: <3CA689F5.5010609@bigfoot.de> phil hunt wrote: > at some point I want herbivore to run on Windows > email clients). I still didn't check out herbivore, but what about writing an smtp proxy for that? smtpd in the standard Python library should be a good starting point. Gerhard From shredwheat at attbi.com Wed Mar 20 12:11:04 2002 From: shredwheat at attbi.com (Pete Shinners) Date: Wed, 20 Mar 2002 17:11:04 GMT Subject: Develop-test-debug cycle References: Message-ID: <3C985420.6020401@attbi.com> Dale Strickland-Clark wrote: > I am debugging a large system written in Python with modules spread > over 4 directories. I'm using PythonWin under Win2K to set-up the > environment and run the code. i'd also recommend running "pychecker" on your code. instead of interactively looking for errors, it always shows me the list of errors right up front. (of course this won't really notice all your logic errors) :] http://pychecker.sourceforge.net/ From jamarijr at my-deja.com Fri Mar 29 10:44:46 2002 From: jamarijr at my-deja.com (Arinté) Date: Fri, 29 Mar 2002 10:44:46 -0500 Subject: Released product Message-ID: <3ca48b83_2@news3.prserv.net> Don't know how late I am, but Freedom Force a game that was released this week uses python... Hooray From phd at phd.pp.ru Thu Mar 28 07:34:15 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 28 Mar 2002 15:34:15 +0300 Subject: Very small zlib/svg problem In-Reply-To: <15522.19213.655102.927935@12-248-41-177.client.attbi.com>; from skip@pobox.com on Wed, Mar 27, 2002 at 04:43:25PM -0600 References: <15522.19213.655102.927935@12-248-41-177.client.attbi.com> Message-ID: <20020328153415.D11101@phd.pp.ru> On Wed, Mar 27, 2002 at 04:43:25PM -0600, Skip Montanaro wrote: > f = gzip.open("c:/test.svgz", "w") ^^ this suggests to use binary modes for binary files: f = gzip.open("c:/test.svgz", "wb") ! Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From opengeometry at NOSPAM.yahoo.ca Tue Mar 12 11:58:24 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 12 Mar 2002 16:58:24 GMT Subject: Question about scientific calculations in Python References: Message-ID: Martin Kaufmann wrote: > Hello Newsgroup > > I'm trying to write a program to calculate diffraction patterns for > electron diffraction on clusters (100-10'000 atoms). So far I used > Python only for CGI programming and system tools (on a rather low > level...). Therefore I don't know whether it's reasonable to program > such a project in Python (I really like the language). Presently my > man concern is speed as the main function of the program is a nested > loop, the inner over several 1000 bins of a histogram and the outer > over several 1000 values of scattering factors. In the end I should be > able to simulate diffraction patterns and compare them to the > experimental data (i.e. run this function several times). > > Now my questions: Would it be best to > > (a) write the whole program in C/C++ (I know only the basics of C but > it would be a good "excuse" to learn it...)? > (b) write the main program in Python but the heavy calculations in C > (I played today with scipy.weave -- the speed is much better but I > didn't really understand what I was doing...)? > (c) program it in Python and don't care about speed (or buy a new > workstation...)? First, get the math right. Then, get the algorithm right; here, Python helps. If you have to solve your own integral, then all bets are off. :-) If you can use FFT approximation or higher math functions (ie. Fresnel) approximation, then Python is good choice. But, this depends on the math being right, so we're back in circle. -- William Park, Open Geometry Consulting, 8 CPU cluster, NAS, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Tin From vku at lfpt.rwth-aachen.de Wed Mar 20 14:05:18 2002 From: vku at lfpt.rwth-aachen.de (Viatcheslav Kulikov RWTH Aachen) Date: Wed, 20 Mar 2002 20:05:18 +0100 Subject: Python/CORBA Message-ID: <3C98DD6E.EB227047@lfpt.rwth-aachen.de> Hello! Can anyone probably answer a question why Python 2.1 sends me an exception message "INITIALIZE: Minor: 0, Completed: COMPLETED_NO." while I am trying to initialize omniORB CORBA interface with: from omniORB import CORBA orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) The registry key (ORBInitRef) is set (properly) to: "NameService=corbaname::sallust.lfpt.rwth-aachen.de:5100" Independently from that, when I use a set ORBInitialHost/ORBInitialPort, the message is still the same. Version of omniORB - 3.0.4. Meanwhile at the other computer where Python 2.0 and omniORB 3.0.2. are installed, everything works. But is it possible that the higher version does not support something the lower version does? I doubt. Please give hints where to search the reason for such an error. Will be grateful. From boud at valdyas.org Thu Mar 7 10:24:38 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Thu, 07 Mar 2002 14:24:38 -0100 Subject: Detect Version of PyQT Bindings? References: <3C86A5F1.49E69E0E@gmx.de> Message-ID: <3c876afa$0$24833$e4fe514c@dreader3.news.xs4all.nl> Ingo Linkweiler wrote: > Hi, > > does anybody know how I can detect the version of the python QT > bindings? (Not the version of QT itself) > I want to use qt canvas. Version 3.0 requires an extra: > from qtcanvas import * > but with older versions this was included with "from qt import *" > > OK, I can do it this way: > > try > from qtcanvas import * > except: > pass > > any better ideas? > I think that's it, basically -- because the qt.py doesn't include a version number itself. Of course, even if Phil were to add one, it wouldn't help all that much, since previous versions wouldn't have it, so you'd have to check anyway for the existence of something. -- Boudewijn Rempt | http://www.valdyas.org From phd at phd.pp.ru Wed Mar 20 05:12:51 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 20 Mar 2002 13:12:51 +0300 Subject: Can't print national characters in IDLE with Python 2.2.1c1 In-Reply-To: <3C97E9DF.3070300@thinkware.se>; from magnus@thinkware.se on Wed, Mar 20, 2002 at 02:46:07AM +0100 References: <3C97E9DF.3070300@thinkware.se> Message-ID: <20020320131251.J14060@phd.pp.ru> On Wed, Mar 20, 2002 at 02:46:07AM +0100, Magnus Lyck? wrote: > UnicodeError: ASCII encoding error: ordinal not in range(128) http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.102.htp Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mwh at python.net Tue Mar 19 13:58:25 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Mar 2002 18:58:25 GMT Subject: Python-2.2.1c1 Build Problems on Linux and AIX. References: Message-ID: ralph at inputplus.demon.co.uk (Ralph Corderoy) writes: > With Python-2.2.1c1, I find `make test' fails on my old version of > Linux/x86 and it fails to build on an also old version of AIX. How old? > Should I go straight to SourceForge and fill in bug forms or do > people tend to discuss the problems here first? Please do. Assign the bugs to me. Give OS/architecture/etc info, please. > I can see the problem with the AIX build. Linux SIGSEGVs in > test_calendar on a call to strftime. More detail needed. Cheers, M. -- The rapid establishment of social ties, even of a fleeting nature, advance not only that goal but its standing in the uberconscious mesh of communal psychic, subjective, and algorithmic interbeing. But I fear I'm restating the obvious. -- Will Ware, comp.lang.python From tatebll at aol.com Wed Mar 20 11:33:29 2002 From: tatebll at aol.com (Bill Tate) Date: 20 Mar 2002 08:33:29 -0800 Subject: [pygresql] Please suggest References: <20020319181506.8E7E757C6@smaug.vex.net> <20020319231043.58646.qmail@web10508.mail.yahoo.com> Message-ID: Gerhard H?ring wrote in message news:... > Le 19/03/02 ? 15:10, Suraj Peri ?crivit: > > Dear Group, > > Please excuse me if my question is not appropriate > > for this group. We are planning to make a public > > object oriented database for genes and proteins ( > > biological databases are generally huge and has lots > > of inter-relationships). > > While planning this, my friend is very much particular > > about using Zope. > > Our plan is using PostgreSQL-PHP tiers. > > there will be many relationships between our objects. > > Now the question is is Zope more sophisticated in > > dealing with objects than PostgreSQL? if so is this > > sophistication is in dealing with the complexity of > > relationships between objects or something else? > > > > Please suggest is ZOPE a good and better choice that > > PostgreSQL-PHP or PostgreSQL-JDBC-Java client > > interface. > > Well, PHP, ZOPE and Java servlets are only technologies for the > frontend. It doesn't matter much which one you choose - either one will > work. But in IMO Python and Java better languages than PHP. And, > compared to Java, Python is far easier to develop with. Btw. I've also > seen some open-source computational biology libraries for Python > mentioned on the comp.lang.python newsgroup. > > The much more important decision to make is which backend technology > (database) to choose. AFAIK PostgreSQL is not really an Object Database, > though it may have some features that go in this direction. > > I basically see two options > 1) a relational database, like PostgreSQL > 2) an object database, like ZODB (for Python, part of Zope). There are > also several open-source object databases for Java > > But to say which one is more appropriate, we'd have to know more of the > requirements. > > One more hint: if you want to reuse Java libraries from an easy-to-use > language like Python, you can use Jython (http://www.jython.org/). It's > a Python interpreter than runs in the JVM. > > As for a more perhaps more appropriate place to ask, I don't know a > newsgroup that has this exact topic, but I think you might get value > advice in the comp.lang.python newsgroup, or the Python mailing list, > which is basically the same thing, just via email. > > Come to think of it, I'l just cc the Python mailing list. Have an eye > there (or in the newsgroup, whichever you prefer). > > Gerhard I would suspect this would be case where an OODBMS would very likely choke if you try to do anything that involves some really advanced querying capability. Normally you take a pretty big performance hit when you start querying down deep in an object graph and/or across object instances - I wish it were otherwise. Note also that zodb currently doesn't support querying in the traditional sense of say a product like Object Design's objectstore - you get pretty much everything under the database root. Where ODBMS tends to excel is in applications where you have document-like data. There are other's as well, but your questions don't strike me as that being the situation here. PG has a number of very nice features including the ability to work with datatypes other than alpha-numeric or binary, e.g., geometric datatypes. The ability to inherit from a table's schema design is interesting and might be useful in this circumstance. Since most RDBMS now allow you to drop columns in a table (historically this wasn't a fun thing to do) so schema evolution is not as big a deal as it used to be. I suspect you'll find PG offers most of what you need here. From eshorkey at rightbracket.com Wed Mar 20 16:22:32 2002 From: eshorkey at rightbracket.com (Eric Shorkey) Date: 20 Mar 2002 13:22:32 -0800 Subject: Embedded Python Requirements Message-ID: I'm having a little trouble making a self reliant embedded build of python. I've looked at Demos/embed/demo.c, and I understand it just fine, but the python interpretter is generating errors on startup. Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] 'import site' failed; use -v for traceback This occurs seemingly regardless of how I build libpython2.2.a. >From searching previous posts, I'm able to remove the first three lines by simply setting PYTHONHOME in the environment. It doesn't matter whether the path is valid or not. Alternatively I could redefine my own Py_GetPath() Py_GetPrefix() Py_GetExecPrefix() and Py_GetProgramFullPath(). I probably will do just that. So these are not really the problem. It's the last error that really has me baffled. I understand that the site module is always imported when the interpreter starts, but I really need to build my app completely self sufficient. So the site module will either have to be statically included, or it's necessity will have to be removed. Is it possible to statically link in the site module? And what exactly does the site module provide that is so important that it is included by default? I'd like to know, because I may be able to simply do away with it. Thanks! From sandskyfly at hotmail.com Sun Mar 17 08:29:18 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 17 Mar 2002 05:29:18 -0800 Subject: a text processing problem: are regexpressions necessary? Message-ID: Hi, I thought I'd share this problem which has just confronted me. The problem An automatic way to tranform urls to articles on various news sites to their printerfriendly counterparts is complicated by the fact that different sites have different schemes for doing this. (see examples below) Now given two examples for each site: a regular link to an article and its printer-friendly counterpart, is there a way to automatically generate transformation code that is specific to each site, but which generalizes across all article urls within that site? Here are a few examples from several online publications: http://news.bbc.co.uk/hi/english/world/africa/newsid_1871000/1871611.stm http://news.bbc.co.uk/low/english/world/africa/newsid_1871000/1871611.stm http://www.economist.com/agenda/displayStory.cfm?Story_ID=1043688 http://www.economist.com/agenda/PrinterFriendly.cfm?Story_ID=1043688 http://www.nationalreview.com/ponnuru/ponnuru031502.shtml http://www.nationalreview.com/ponnuru/ponnuruprint031502.html http://www.thenation.com/doc.mhtml?i=20020204&s=said http://www.thenation.com/docPrint.mhtml?i=20020204&s=said I'm kinda heading in the direction of attempting to generate regular expressions for each site... But I'm a bit apprehensive about doing this. Is there a more pythonic way to approach this problem? Any advice would be appreciated. regards, Sandy From bokr at oz.net Fri Mar 1 05:49:00 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Mar 2002 10:49:00 GMT Subject: Telnet connection References: <8z9f2rks.fsf@fido.trinitycapital.com> Message-ID: On 28 Feb 2002 23:46:47 GMT, bokr at oz.net (Bengt Richter) wrote: >On Thu, 28 Feb 2002 19:51:06 +0100, "Riss Nicolas" wrote: > >>Has somebody a python program where it is an telnet connection ? > >You appear to be running windows. What happens if you get into your browser >and put > > telnet://192.168.0.9:32 > >in the location (i.e., what you are trying to connect to with your code)? >Do you get a telnet client screen with a login prompt? > >Did you try \r\n in place of plain \n in your code? > Whoa, I just realized your program seems to be missing a couple of lines for waiting for a user prompt and sending the user name. After that, wait for the password prompt. At least that is typical. Or do you have some special telnet server setup that bypasses that? Maybe it still needs a \r\n to trigger it past the missing user entry? It's hard to say with so little info. Or copy from the screen of a manual login and successful connect with a couple commands. (Do you connect to an ordinary shell or some special program)? BTW, if you somehow have wrapped your telnet program execution in a try: do_it() except: pass, you could be missing a bug-caused exception discussed in another thread. You might want to try changing line 424 of telnetlib.py. In the other thread I wrote: I suspect line 424 self.msg('IAC %d not recognized' % ord(opt)) should be self.msg('IAC %d not recognized' % ord(c)) Regards, Bengt Richter PS., explain in French if that helps. Someone will translate if needed. Maybe even if not needed ;-) From mertz at gnosis.cx Tue Mar 5 15:33:51 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Tue, 05 Mar 2002 15:33:51 -0500 Subject: Text Search Engine that works with Python Message-ID: |Here is a related question -- Is there a search program for |structured text files, in particular something that searches XML |files. You might like my xml_indexer program. There is a writeup on the design at: http://gnosis.cx/publish/programming/xml_matters_10.txt As with indexer, from which xml_indexer is derived, the module has been aggregated into a package found at: http://gnosis.cx/download/Gnosis_XML_Utils-0.9.tar.gz Yours, David... -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From timr at probo.com Wed Mar 6 01:27:26 2002 From: timr at probo.com (Tim Roberts) Date: Tue, 05 Mar 2002 22:27:26 -0800 Subject: Minor, minor style question References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> <7le58u86cc6u7ibsdobuj7jk8gqobuluq5@4ax.com> <3c8382f3.291759938@news.laplaza.org> Message-ID: mats at laplaza.org (Mats Wichmann) wrote: > >I'm far from being a Javascript expert, but I thought it was missing >there, too. My one bit of Javascript coding a few years back I ended >up having to do something like this to make mutiline text messages. >Of course, Python can do the multiline messages natively... No, Javascript has a continuation character (backslash), but it's not often required in Javascript because, unlike Python and VB, Javascript is free-format: str = "This is a long long string, " + "which I can encode just by " + "concatenating a bunch of strings " + "on separate lines."; -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Chris.Barker at noaa.gov Thu Mar 7 12:25:31 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 07 Mar 2002 09:25:31 -0800 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> <2030665d.0203070126.55addc33@posting.google.com> Message-ID: <3C87A28B.549D9B1C@noaa.gov> Sam Collett wrote: > > > Actually, I usually use a few more cases so that I always get two > > significant digits: 1.2k, 23k, 840k, 2.4M, etc. > How would you do that then (maybe even to 2 decimal places, e.g. 24.52kb)? You make sure the result of your division is a Float (Ah, how I long for the "new division" to be standard!) and you use %f instead of %d #!/usr/bin/env python def ShowSize(raw): if raw < 3000: return "%db" % raw elif raw < 2000000: return "%.2fkb" % (raw / 1000.) elif raw < 2000000000L: return "%.2fMb" % (raw / 1000000.) else: return "%.2fGb" % (raw / 1000000000.) print ShowSize(2567L) print ShowSize(2567000L) print ShowSize(256700000L) print ShowSize(2567000000L) print ShowSize(256700000000L) And here are the results: >>> execfile("junk.py") 2567b 2.57M 256.70M 2.57G 256.70G -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From donn at drizzle.com Fri Mar 15 01:11:38 2002 From: donn at drizzle.com (Donn Cave) Date: Fri, 15 Mar 2002 06:11:38 -0000 Subject: Setting UNIX environment with a Python script References: <3C8D143A.17963385@all.com> Message-ID: <1016172689.74477@yasure> Quoth "James T. Dennis" : | Cameron Hutchison wrote: |> On Tue, 12 Mar 2002 13:25:57 +1100, Grant Edwards wrote: ... |>> Another common method is to have your Python program write the shell |>> commands to stdout, then execute them with something like | |>> eval `myPythonProgram` | |> While that would work fine, I dont think it's a terribly good idea. I |> think it would be cleaner to keep the shell syntax in a shell script and |> avoid having the python program assume the scripting environment it is |> returning to. | | Having "myPythonProgram" implemented in ANY language (including | in ANY shell) makes exactly the same assumptions: to wit: | FOO=BAR assigns shell variables and either export (Bourne & family) | or setenv (csh/tcsh) exports them into the environment. | | *ANY* program or script that is intended to be invoked under | eval `....` will have to make those assumptions. Yes, and that's why it's not really an ideal design! I think that's his point - don't write your tools to be invoked in an eval statement, if you don't have to. Or "source", or any solution that requires the tool to know the natural syntax of its invoker. How would we write it instead, to avoid this problem? If there's CPU time to spare, one alternative might be to invoke python separately for each variable, and in that case python can print out just the value for that variable. sh: EX1="`exsetup EX1`" export EX1 rc: EX1 = `{exsetup EX1} ... etc. Donn Cave, donn at drizzle.com From chris.gonnerman at newcenturycomputers.net Fri Mar 1 08:22:06 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 1 Mar 2002 07:22:06 -0600 Subject: Can somebody kill getpathp for me? References: Message-ID: <005601c1c124$4bcb90a0$0101010a@local> ----- Original Message ----- From: "Tim Peters" > [Chris Gonnerman] > > In the PC subdir of the Python-2.1.2 build directory is a module > > called getpathp.c, which sets up the initial sys.path value. It > > is well known by Python programmers on Windows that the sys.path > > initialization includes directories plucked from special registry > > keys... unless you are using the PythonWare version. > > Or the PythonLabs distribution: while the core installer does set up a > registry entry containing "the usual" Python path, it *normally* never uses > it. Read the long comment block at the start of getpathp.c, and this time > believe that it means what it says . >From several places in that comment block: Other "application paths" in the registry are always read. I *don't* want this! > Note that the core installer > never sets up what the comment block calls "'application paths' - that is, > sub-keys under the main PythonPath registry key". If there aren't any > application paths, then, as the rest of the comment block says, the main > PythonPath key is ignored, unless a "Python Home" isn't given by a > PYTHONHOME envar and can't be guessed from the python.exe path. No, but win32all does (for instance). The point is, I never want my CD-based runtime to ever see the end user's install, if he/she has one. The programs I want to run from CD may get psycho if the local version has conflicting libraries, and in fact I have already encountered this problem (so it's not just theoretical). > > I thought, great, I can use this (the PythonWare version) to create > > Python runnables on CD-ROM; but now I discover a fly in the ointment. > > If the computer already has an installed Python interpreter, the > > paths set in the registry are added, and BEFORE the paths from the > > PythonWare PYROOT variable are added. > > AFAIK PythonWare doesn't ship with a custom getpathp.c, and neither does > ActiveState, so AFAIK the comment block applies to all Python installations. Ah. Didn't know that. > The "PythonWare PYROOT variable" is news to me, google hasn't heard of it > either, and I find no mention of PYROOT in my PythonWare PY21 installation. > Setting a PYROOT envar has no visible effect on sys.path when I run under > PY21 either. That's a long-winded way of saying I think you must be > confused . Read the "setup.bat" file. I assumed it actually did something... my mistake. > Have you tried setting PYTHONHOME? If, e.g., I set PYTHONHOME to \Python22, > then execute python while *in* my \Python21 directory (these both referring > to PythonLabs distros), then Python 2.1.2 comes up with sys.path pointing > entirely at Python 2.2 directories. This is insane, but shows that > PYTHONHOME works the way getpathp.c says it works. Here's my result (formatting corrected, content same): K:\Python>set pythonhome=k:\python K:\Python>set path=k:\python K:\Python>python Python 2.1.1 (#20, Aug 23 2001, 11:27:17) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. Alternative ReadLine 1.5 -- Copyright 2001, Chris Gonnerman >>> import sys >>> sys.path ['', 'C:\\Python\\win32', 'C:\\Python\\win32\\lib', 'C:\\Python', 'C:\\Python\\Pythonwin', 'k:\\python\\DLLs', 'k:\\python\\lib', 'k:\\python\\lib\\plat-win', 'k:\\python\\lib\\lib-tk', 'K:\\PYTHON', 'k:\\python\\PIL', 'k:\\python\\PST', 'k:\\python\\pythonware'] >>> Note in particular that the Alternative Readline has been loaded. It shouldn't be; I didn't put it in the k:\python install, only my python.org "standard" install on the C drive. It seems to have already run when site.py is loaded (I considered hacking sys.path there). > > What I want is a version of either python.exe or python21.dll > > (whichever contains the offending getpathp.c module) with the > > registry-probing code disabled. > > If that's what you really want, you'll have to edit getpathp.c and compile > your own Python. It's beginning to look that way. Dang. That's going to be a lot of work. I build software with MinGW32 from time to time, but I don't have a working CygWin install, which seems to be necessary to run the configure script. Frankly, no insult intended, I'd like to keep CygWin off my computer; I tried programming with it and found it very disappointing. > > Ideally it should still apply the paths from PYROOT (basically in this > > case it must). > > Python doesn't look at any such envar on any platform. Maybe that's why > setting PYROOT isn't doing you any good . Try PYTHONHOME. As I pointed out, I found the setup.bat file confusing; however PYTHONHOME isn't helping either. From herrn at gmx.net Thu Mar 7 05:18:53 2002 From: herrn at gmx.net (Marco Herrn) Date: Thu, 7 Mar 2002 11:18:53 +0100 Subject: how to give an object as argument for a method In-Reply-To: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> References: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> Message-ID: <20020307101853.GA1326@lurkabove.darkstar> On Thu, Mar 07, 2002 at 03:28:09PM +1300, Greg Ewing wrote: > Marco Herrn wrote: > > > > hmm, do I have to implement that in _every_ method or just in > > methods who use the 'self' statement? > > In every method. The instance is always passed in > as the first parameter, so there must be a parameter > there to receive it, even if it's not used inside > the method. Is there a reason why this is just a convention? It seems (because it is such a _strong_ convention) that this should be a real feature of the language. I mean that there could be a reserved word "self" which is there all the time, so that one doesn't hast to do this himself. Bye Marco -- Experience is something you don't get until just after you need it. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From aahz at panix.com Mon Mar 11 11:43:30 2002 From: aahz at panix.com (Aahz Maruch) Date: 11 Mar 2002 08:43:30 -0800 Subject: About deletion of variables in version 2.1 References: Message-ID: In article , Juan Huertas wrote: > >I'm working with large list or dict an have problems with the deletion and >time of response, this problems does not exist in version 2.0: > >Reading a large file and loading to a list: > >f=open('c:/xx','rb') >ls=[] >while not eof: > ln=f.readline() > ls.append(ln) > >This takes 5 seconds (reasonable) > >The new instruction: > >ls=[] # or del ls > >Takes about 10 seconds and use 100% of Memory!!!! How big is the file and how much RAM do you have? -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From wealthychef at mac.com Fri Mar 15 22:08:13 2002 From: wealthychef at mac.com (wealthychef) Date: 15 Mar 2002 19:08:13 -0800 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <1016173476.645562@yasure> <2b57f654.0203151021.7f709e4c@posting.google.com> Message-ID: <2b57f654.0203151908.33413282@posting.google.com> "Donn Cave" wrote in message news:... > Quoth wealthychef at mac.com (wealthychef): > ... > |> The complementary problem, of course, is that once you have invoked > |> readline(), it will read all the data available on the file descriptor, > |> or a lot of it anyway, and return only the first line. The next time, > |> it will return the next line from its buffer, but you have no way to > |> know that it has another line waiting there. select() can't see it. > |> There are solutions, I think the easiest thing in most cases is to > |> throw away the file object and just use the file descriptor (fileno()) > |> (or sockets in this case.) > | > | This is even more frightening. I don't want to lose any data! How > | can I protect myself from this? Why is using the file descriptor > | better? > > Well, you're not exactly losing data, it's just buffered, though that > may be too fine a point depending on the circumstances. Here's what I mean. If I do a select.select() and it says, "there's data," then I do a readline() on the file object, but select() was talking about 2 lines of data, I will lose a line of data, because my next select() will say "nothing left." Is that right? Because the call to readline() somehow scarfs up all the data available and saves it for my next call to readline()? If that's so, then readline() sucks, because I should have a way to query it to avoid blocking. Obviously select() and readline() just don't play ball together very well... > > The point with file descriptor is to use system I/O functions on the > device, and avoid buffered C I/O. Basically because select is a > system I/O function. If there were a C analogue to select, then you > could use it with C buffered file objects, but there is no such thing. > > When select tells you "this thing is ready to read", it means the > device is ready for a system level read(), as in os.read(fd, bufsize). > So do that, and you'll get what select was telling you about. It's > really simple. The rules are the same, if you get an empty string > it's at "end of file" (the pipe closed.) I just want to be sure I understand this. You're saying that os.read() somehow get what select.select() was talking about, but that f.fromchild.readline() will read less than that? > > I have lost track of what kind of devices we're actually talking about - > I'm seeing the word "socket", but then what looks like popen2.Popen3. > Note that in Python, sockets are are normally socket objects, with recv() > methods etc., but these are unbuffered and recv() is like os.read(). > Pipes (as created by Popen3) are either integer file descriptors or > file objects, there isn't any special system level pipe object. > As long as you're on UNIX, there's a certain purity of abstraction here > that you can exploit if you want it just to simplify matters - you can > get the file descriptor with s.fileno(), and you can use os.read() with > that - or you can use sock.recv() if you prefer. The objects from my original post are popen2.Popen3 objects, as you noticed. The Python lib manual says that os.read() should not be used with file objects, even though I can get a file descriptor from them with fileno(). Will it work? From ak at silmarill.org Tue Mar 26 22:50:36 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Wed, 27 Mar 2002 03:50:36 GMT Subject: Dealing with python version Message-ID: Hello, Correct me if I'm wrong, but it seems like if python1.6 or 2.0 are already installed and you install a newer version, python command still points to the old interpreter. I think it would be sensible to use the newest installed python to run a program. Is there some elegant way to do that? I would ideally prefer it to run using newest interpreter available unless it's older than some minimum requirement. It's not very user-friendly to put #!/usr/bin/env python2.1 bang line and then say in a README that if user gets an error, he has to somehow find out what's the latest version he's got and change the bang line to it. What's the proper way to deal with all of this? Thanks, - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ralph at inputplus.demon.co.uk Sat Mar 30 12:35:27 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 30 Mar 2002 17:35:27 GMT Subject: PEP 285: Adding a bool type References: Message-ID: Hi Guido, > > Not in Guido's eyes . We don't need 3 equivalent ways to > > turn an arbitrary expression into a bool ("bool(x)" same-as "not > > not (x)" same-as "truth(x)"). *Especially* if str(bool) and > > repr(bool) produce 'True' and 'False', people have a legitimate > > need to make an arbitrary true/false expression produce 0 and 1 > > too, if only to preserve 0/1-based true/false output. > > operator.truth() has always been the best way to do exactly that. > > Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and > > "(0, 1)[boolexpr]" reek in comparison. > > Tim must be missing something. The obvious way to turn a bool b into > an int is int(b). Having to import the obscure 'operator' module for > this purpose is backwards. (IMO there's almost *never* a reason to > import that module anyway.) I thought Tim was trying to map a range of integer values onto just 0 and 1 as ints, not False and True, where as you're suggesting he just wants to get an int from a boolean. I think he has an expression like day_of_month, e.g. 30, and wants a 0 or 1 from it. I could easily be wrong here. Ralph. From andreas at mtg.co.at Tue Mar 12 13:52:17 2002 From: andreas at mtg.co.at (Andreas Kostyrka) Date: Tue, 12 Mar 2002 19:52:17 +0100 Subject: Order of constructor/destructor invocation In-Reply-To: <3C86291A.4A2E9CA@spam.nada.kth.se> References: <3C8466F9.2080903@jerf.org> <_f7h8.5541$aP6.6480@rwcrnsc54> <3C851D41.3000902@jerf.org> <3C85446B.B389BB0F@spam.nada.kth.se> <3C855848.60302@jerf.org> <3C86291A.4A2E9CA@spam.nada.kth.se> Message-ID: <20020312195217.4247fed7.andreas@mtg.co.at> On Wed, 06 Mar 2002 15:35:06 +0100 Bj?rn Lindberg wrote: > No it's not; it's a completely well-defined feature. Well, it's so for a value oriented language like C++. > A common use for the technique in C++ is so called "sentry"-objects that > handle resources. A stack allocated object that acquires a lock or a > file handle for example. The object will be destroyed upon leaving the > function, and the lock can be released or the file handle closed. > Elegant and efficient. Now imagine two resources where one depends on > the other: > > void a_function () > { > sentry1 s1; > sentry2 s2; > ... > } Well, in Python you would have: def a_function(): s1=Sentry1() s2=Sentry2() Now this has quite different semantics than the C++ version above, because in Python anything is a reference: void a_function() { sentry1 *s1; sentry2 *s2; s1=new sentry1; s2=new sentry2; } In this case C++ doesn't even call the destructor. Especially, in the case of references, the lexical sequence of definition is not always the same as the dynamic sequence of creation. Consider: def a_function(): s1=Sentry1() s2=Sentry2() s1=Sentry1() Which is the logical sequence for destructing these things? Additionally, the destructor in Python is seldom needed, and it's calling time is not specified by design choice. (Jython doesn't use reference counting, it uses Javas gc.) > The sentry objects will be created and destroyed in the correct order > for this kind of use to be possible. Well, this makes sense for C++ (or even might make sense for say EXPANDED types in Eiffel, etc.), but it senseless in a reference-based language like Python. Andreas From DavidA at ActiveState.com Thu Mar 28 17:32:57 2002 From: DavidA at ActiveState.com (David Ascher) Date: Thu, 28 Mar 2002 14:32:57 -0800 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <001d01c1d67f$2eb81090$445d4540@Dell2> Message-ID: <3CA39A19.2D12BFD6@activestate.com> "Charl P. Botha" wrote: > > In article , > David Ascher wrote: > > Thanks for all the interest in ActivePython. We hope to not have these > > kinds of delays in the future. > > Just remember not to split your infinitives in the future. ;) I am noting but a poar french speeker. Me no nossing aboot sutch zings. "J'espere qu'on n'aura pas ce genre de delai a l'avenir". Thanks. Want to edit a book? =) -- David Ascher From bobnotbob at byu.edu Tue Mar 12 12:05:47 2002 From: bobnotbob at byu.edu (Bob Roberts) Date: 12 Mar 2002 09:05:47 -0800 Subject: english thesaurus and dictionary Message-ID: I want to incorporate an english thesaurus and dictionary into my application. Does anybody know of freely available thesauri and dictionaries that I could use? From DavidA at ActiveState.com Thu Mar 28 18:43:20 2002 From: DavidA at ActiveState.com (David Ascher) Date: Thu, 28 Mar 2002 15:43:20 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: <3CA3AA98.2F94398B@activestate.com> phil hunt wrote: > And Guido's statement supports my suggestion that pass be made > optional in Python. Consider, when someone is designing a class, > one could write an outline like this: > > class BaseClass: > > class MyClass(BaseClass): > def __init__(self): > def method1(self, a, b, c): > def method2(self, d, e): > def method3(self, f): > > It is perfectly clear what this means. But unfortunately, as Python > stands today, it is syntactically invalid, one would have to say: > > class BaseClass: > pass > > class MyClass(BaseClass): > def __init__(self): > pass > def method1(self, a, b, c): > pass > def method2(self, d, e): > pass > def method3(self, f): > pass May I suggest that you instead do: >>> class MyClass: ... def do_this(self): ... "this function would do this" ... def do_that(self): ... "while this function would do that" ... >>> and use the docstrings as a placeholder for the actions of the function -- typically something that's foremost in your mind when you're pseudocoding, and it counts as a statement as far as the parser's concerned (hence is syntactically valid), and at the same time, you've already got docstrings ready for you when you start to implement. --david From tdelaney at avaya.com Tue Mar 5 16:39:27 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 6 Mar 2002 08:39:27 +1100 Subject: Status of PEP's? Message-ID: > From: James_Althoff at i2.com [mailto:James_Althoff at i2.com] > [snip] > being sequences . [snip] > back at ya ). [snip] > And keep on writing code . You've really taken to heart Tim Peter's comments about looking more favourably on those who know how to , haven't you? ;) Tim Delaney From gleki at gol.ge Mon Mar 4 17:26:45 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Mon, 04 Mar 2002 14:26:45 -0800 Subject: more functional programming Message-ID: <3C83F4A5.E952DA05@gol.ge> Hi all! Please, accept my appologies for this naive question. I have taken a careful look on the operator module docs. The module enables one to make procedures as lists. That's too good. However, is there already something like scheme's "define" abstractor? This'd be used as the first element of such list, yielding the result of the procedure... Is this, or anything similar, already present in Python? If not, does someone of the Python gurus plan to do so? Thank you very much for your time. Greetings, Giorgi PS. Is a genetic programming library written in/for Python available? From theller at python.net Thu Mar 21 08:34:48 2002 From: theller at python.net (Thomas Heller) Date: Thu, 21 Mar 2002 14:34:48 +0100 Subject: How Can I Determine the Operating System with Python? References: Message-ID: > > >>> import sys > > >>> sys.platform > > 'win32' > > >>> import os > > >>> os.name > > 'nt' > > That's a crude way of determining the platform, because sys.platform > depends on the compiler used to compile Python. Yes, even on Windows. > But I'm reasonably sure that the Pythonlabs folks won't change their > Windows compiler anytime soon. > > I'd very much like to have a real way for determining the platform. > Anybody wants to write a PEP? :-) > IIRC Marc Andre Lemburg has written a platform.py script, which may even make it into the official Python lib (?). Thomas From dgallion1 at yahoo.com Sun Mar 10 20:05:28 2002 From: dgallion1 at yahoo.com (Darrell) Date: Mon, 11 Mar 2002 01:05:28 GMT Subject: Regular expressions newbie: something for templates References: Message-ID: Skip's example would be faster than mine because I used .*? which has problems when the amount of content matched is large. Another way to spell this: re.sub("\$([^$]+)\$","%(\g<1>)s",s) or: re.sub("\$(?P[^$]+)\$","%(\g)s",s) Also Skip used a raw string r"xxx" which I should have done as well. The doc explains the problem with not using raw strings. Has to do with back slash hell. Now if I can make all this nice stuff a habit :) --Darrell Skip Montanaro wrote: > >>> import re > >>> s = "This is the test $var1$ and this is $var2$" > >>> re.sub(r"\$([a-zA-Z_0-9]+)\$", r"%(\1)s", s) > 'This is the test %(var1)s and this is %(var2)s' > From skip at pobox.com Sun Mar 10 16:09:29 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 10 Mar 2002 15:09:29 -0600 Subject: How to disable assert statements inside a module? In-Reply-To: References: Message-ID: <15499.52105.790818.353389@12-248-41-177.client.attbi.com> Pearu> So, I would like to disable the assert statements in one module Pearu> while in others, that are under development, assert statements Pearu> are enabled. Is it possible? I am using Python 2.2. This comes to mind: s/assert /pass; #assert/ :-) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) "As often happens in Net communities, people find all kinds of energy to compose incisive criticisms of the threads and postings of other members, when they could be directing that energy towards brilliant new threads and postings of their own." - Tom Neff From susan at mars.provis.com Fri Mar 29 15:13:14 2002 From: susan at mars.provis.com (Susan Williams) Date: Fri, 29 Mar 2002 14:13:14 -0600 (CST) Subject: Linux-related help Message-ID: <200203292013.g2TKDE304906@mars.provis.com> I thought I'd end the suspense and let you all know how it turned out. Just as you no doubt suspected, it was the 3rd party module walking on memory. We've had this code running on four platforms for considerable time without it causing a problem, but it definitely had a memory error in it. So, so sorry to cast aspersions on python, all is better. (I hope I don't have to join a 12-step program if I admit to using this, but the module was typhoon in case any of you are using it... And as I mentioned, I haven't been paying attention, so if Aaron Watters has written a database module in python I'd love to hear about it... ;-) susan >Howdy, y'all, > >[No one will remember me, but I'm back after a long >absense because--you guessed it--I have a problem and >I want some help...] > >We are attempting to port from Solaris to Linux, and >I'm having some unpleasant malloc/free problems at >exit (sys.exit). We have running software based >currently on 1.5.2. We're compiling on Linux with gcc >3.0.3 (on Solaris we were using Sun's compiler, not >gcc, I think). > >Unfortunately I have a 3rd party module I'm linking with >python that is rather ancient. We first got it when using >python 1.3, we "ported" it to 1.5.2, and I can't quite >pin down whether it is the root of the problem or not, >perhaps it is doing something not quite kosher. >(The idea of trying to get it running with 2.1 gives >me the willies, but that is not really today's issue.) > >Anyone out there using Linux especially with 1.5.2 >is this ringing any bells? On exit, python is clearing >the list of modules, each module is clearing dictionary >entries by setting them to None, and it is the decref >that is blowing up. It is not always in the same place, >but it is always in the code that is setting a dictionary >value to None and deleting whatever was there before. > >Any ideas welcome. I'm not too well versed on either the >innards of python or the proper coding for module >extensions. > >thanks... >sue williams > > >-- >http://mail.python.org/mailman/listinfo/python-list From lac at strakt.com Thu Mar 21 11:37:39 2002 From: lac at strakt.com (Laura Creighton) Date: Thu, 21 Mar 2002 17:37:39 +0100 Subject: multithreading and Tkinter In-Reply-To: Message from Arcady Genkin of "Thu, 21 Mar 2002 08:18:18 GMT." References: Message-ID: <200203211637.g2LGberq003250@ratthing-b246.strakt.com> > Greetings: > How do I signal the GUI thread that new information for a particular > object has arrived? Currently I'm using after() method of the Tkinter > object to update info for *all* objects every second, but that is > hardly a good design, since there may be 500 of them, and the new info > can be arriving once every 15 minutes. > > Any ideas and/or pointers to the documentation (preferably online) > highly appreciated. You want to use Queue.Queue() to make yourself a nice incoming queue, and fill it with the data that arrived and the object(s) that care(s) about it. You'll still use after, but you will only update the objects that care, and only when something has arrived. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 Laura Creighton From mkelly2002 at earthlink.net Fri Mar 29 15:12:14 2002 From: mkelly2002 at earthlink.net (Michael Kelly) Date: Fri, 29 Mar 2002 15:12:14 -0500 Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: On Fri, 29 Mar 2002 14:03:26 +0200, Pearu Peterson wrote: >Great! How about implementing Delphi to Python translator? That might be a bit of a tough one for starters but as a Delphi user I could dig seeing a parser that followed all the 'Uses' dependencies and told you which units could be deleted from your app's Uses clause without breaking the program. I see calls for it all the time on the Delphi groups but I gather there's no freeware out there that does it. Mike -- "I don't want to belong to any club that would have me as a member." -- Groucho Marx From tanzer at swing.co.at Thu Mar 7 01:09:12 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Thu, 07 Mar 2002 07:09:12 +0100 Subject: Order of constructor/destructor invocation In-Reply-To: Your message of "Wed, 06 Mar 2002 15:35:06 +0100." <3C86291A.4A2E9CA@spam.nada.kth.se> Message-ID: Bj?rn Lindberg wrote: > > > and yes, all *standards* *conformant* compilers will follow this practice. > > > > Emphasis mine. That was my point. > > > > On an intuitive level, that's one of those "depend on it when you have > > no other options" kind of features. Even when the standard specs those > > No it's not; it's a completely well-defined feature. > > Anyway the OP's original example wouldn't have been a beautiful specimen > of code in C++ either, but since it was only an example it doesn't > matter. > > A common use for the technique in C++ is so called "sentry"-objects that > handle resources. A stack allocated object that acquires a lock or a > file handle for example. The object will be destroyed upon leaving the > function, and the lock can be released or the file handle closed. > Elegant and efficient. Now imagine two resources where one depends on > the other: > > void a_function () > { > sentry1 s1; > sentry2 s2; > ... > } > > The sentry objects will be created and destroyed in the correct order > for this kind of use to be possible. Before this thread I would have agreed that destruction order is completely well defined. Looking at your example I'm not sure about one case. What if you write: void a_function () { sentry1 s1, s2; ... } ? Will s1 be destructed before s2 by all compilers? Guess, I never cared about that because I tend to use multiple declarations myself. -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From gvdbogae at vub.ac.be Sat Mar 23 09:40:24 2002 From: gvdbogae at vub.ac.be (Geert-Jan Van den Bogaerde) Date: 23 Mar 2002 15:40:24 +0100 Subject: Info needed on metaclasses / type-ing In-Reply-To: References: Message-ID: <1016894425.1344.1.camel@gandalf> On Sat, 2002-03-23 at 14:46, Dimitris Garanatsios wrote: > I recently browsed through an unfinished book of Bruce Eckel, "Thinking in > Python", Revision 0.1.2 > I can't remember the URL where i got it, but i found it through searching > for documentation on Python from the main site, www.python.org > > I found the following peace of code there: > > ------------------------------------------------------------------ > > #: c01:SingletonMetaClass.py > class SingletonMetaClass(type): > def __init__(cls, name, bases, dict): > super(SingletonMetaClass, cls).__init__(name, bases, dict) > original_new = cls.__new__ > > def my_new(cls, *args, **kwds): > if cls.instance == None: > cls.instance = original_new(cls, *args, **kwds) > return cls.instance > > cls.instance = None > cls.__new__ = staticmethod(my_new) > > class bar(object): > __metaclass__ = SingletonMetaClass > > def __init__(self,val): > self.val = val > > def __str__(self): > return `self` + self.val > > ... > #:~ > > ------------------------------------------------------------------ > > My question is about the "SingletonMetaClass" class. > I have tried in the past to create my own types using Python and just could > not find a way of doing that since built-in type objects' structure where > not documented. > > The "SingletonMetaClass though", as far as i can understand, please help me > with that, is doing exactly what i wanted: a new type definition. I browsed > Python's manuals to find more about the attributes and functions that are > used, but found nothing... > > Could anyone help me find information about the meaning and use of the > following attributes/functions/objects? These are: > > --- the "__metaclass__" attribute of the "bar" class (derived from object) > > --- the "object" object itself > > --- the "super" function used in the "SingletonMetaClass" class (a class for > a new type object?) > > --- the "__new__" attribute/method of a class (applies to any class?) > > --- the "staticmethod" function used in the "SingletonMetaClass" class > > --- any additional info about related classes or functions that are not used > in the above example but exist and are available to use http://www.python.org/2.2.1/descrintro.html Geert-Jan From mwh at python.net Sun Mar 31 15:44:54 2002 From: mwh at python.net (Michael Hudson) Date: Sun, 31 Mar 2002 20:44:54 GMT Subject: New-style exceptions? References: Message-ID: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) writes: > Is there a reason why new-style objects can't be used in the raise > statement? > > >>> class Error(object): pass > ... > >>> raise Error > Traceback (most recent call last): > File "", line 1, in ? > TypeError: exceptions must be strings, classes, or instances, not type > > This seems like an artificial restriction... > > (Using 2.2) This has been argued about on python-dev very recently. I didn't read the thread, though, so you'll have to wait for someone else to summarise or hit the archives... Cheers, M. From sjmachin at lexicon.net Tue Mar 5 18:08:44 2002 From: sjmachin at lexicon.net (John Machin) Date: 5 Mar 2002 15:08:44 -0800 Subject: ICU wrapper for Python? References: Message-ID: Fredrik Juhlin wrote in message news:... > On Tue, Mar 05, 2002 at 04:30:41PM +0100, Martin von Loewis wrote: > > Fredrik Juhlin writes: > > > > > However, I'm relying on the fact that since Python uses UCS-2 and ICU uses > > > UTF-16 for their respective internal format, any Python unicode string can > > > be used as an ICU unicode string. So for the collation I don't need to do > > > any conversion between the two. To expose the codecs, one would have to > > > convert the resulting strings from UTF-16 to UCS-2. > > > > I'm a bit slow here: Why do you think Python uses UCS-2 and not > > (simultaneously) UTF-16? What kind of conversion would you perform? > Maybe I'm the one that's slow, or possibly horribly confused. > Actually, I'm pretty damn sure that the docs I read at home said that > Python used UCS-2 rather than UTF-16. But looking at the online docs > they're saying UTF-16. So what I thought would be a problem apparently > won't be. Which is good news :) > Here FWIW is my understanding of the long form of what I think Martin's point is: (1) CS == character set. UCS-2 is a 16-bit character set. It covers the original Unicode 1.0 character set. It is "deprecated and dead" -- so says the ICU web site. (2) TF == transformation format. UTF-16 is a method of representing a larger character set (the Unicode 21-bit set) in 16-bit units. It uses "surrogate pairs" (two 16-bit numbers out of ranges that are reserved in UCS-2) to represent characters whose ordinal is greater than 65535. (3) Conversion from UCS-2 to UTF-16: Unnecessary; UCS-2 data is already in UTF-16 format. (4) Conversion from UTF-16 to UCS-2: if there are surrogates in the data, strictly a UCS-2 result is not possible; if there are no surrogates, then the data is already UCS-2. The only function a "converter" could usefully perform would be to check for surrogates. (5) Pythons compiled for "narrow" Unicode (16 bits) support UTF-16 e.g. they don't take exception to the presence of surrogates, count a valid surrogate pair as one character when dealing in characters as opposed to code-units, etc. From pibble at yahoo.com Thu Mar 28 18:21:24 2002 From: pibble at yahoo.com (Preston Landers) Date: 28 Mar 2002 15:21:24 -0800 Subject: Exceptions and modules / namespaces question Message-ID: <1136f745.0203281521.76a1a62c@posting.google.com> This is a question about modules / namespaces and exceptions. It's probably been asked before, but.... I looked in the Python FAQ and did some searches on Google (& Groups) and didn't turn up anything. I've run into this thing a couple of times before, but I was always able to work around it or avoid it, but I'd like to understand what's going on here, because it's probably just a problem with my understanding. The problem, in a nutshell, is that I can't seem to catch an exception in the same module it was defined in if the function that raised the exception is in a different module, because of naming issues. -------module2.py: import module1 def raise_foo_exception(): raise module1.FooException("HELLO") -------module1.py: import exceptions, sys class FooException(exceptions.Exception): pass def main(): try: import module2 module2.raise_foo_exception() except FooException, e: print "Got it!" except: xi = sys.exc_info() print "Didn't get it. Got this instead:", xi[0], xi[1] if __name__ == "__main__": main() ---------result: Didn't get it. Got this instead: module1.FooException HELLO The question is, how do I explicitly catch FooException in main() without doing a catch-all except: and then examining the type of my exception, and making a decision based on that. It's kinda clunky. thanks, Preston Landers pibble at yahoo.com From jlh at cox.net Thu Mar 7 19:52:27 2002 From: jlh at cox.net (Jeff Hinrichs) Date: Fri, 08 Mar 2002 00:52:27 GMT Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: "Geoff Gerrietts" wrote in message news:mailman.1015529542.9404.python-list at python.org... > Quoting Jeff Hinrichs (jlh at cox.net): > > > > Would you be interested in pursuing this further? > > I think we should. I like the idea of starting with an interaction. > Your observation that interactivity interests new users is dead on; I > can remember being in exactly that same boat. > > We might set out from Hello, World with the idea of making Hello, > Name. Develop Echo as a "here's the source, let's talk about it" then > follow it up with "now see if you can make "hello, name" work, based > on the original Hello World. No real new challenges there, but > learning to output a constant string and a variable on the same line > might be interesting for the student, and if they don't get it, tell > them a few ways to solve that problem "on the next page". > > Do we want to take them through a few steps on how to pretty up the > output? Probably not, huh? Well maybe we might want to consider this here. In reply's farther down the list there is talk of left/right brain types. Perhaps we should give the other hemisphere something to focus on. Not too much at this point but enough to partially appease the asthetic insticnts in some. > Then we move to the traditional Number Guess game. Discuss if, suggest > the need for else. > > I'm trying to get granular here, trying to build in both the need for > the student to engage and think about the topic at hand while > maintaining interest and a real sense of progress. This might be the proper time to come to a concensus on what the outcome of this educational experience should be. If we are after CP4E then we should probably not attack the problem with any idea that these students are going to become CS majors in college. If we can create an environment that opens up a section of their mind about how programs work they would benefit in any academic or business related activity that involved computers. We should do nothing to stunt the growth of potential CS majors but our focus should be on programming for people who probably won't be professional programmers. I apologize for the clumsiness of the above description but I haven't put all of my thoughts together yet. > When do we start immersing them with "useful examples" they should > try? After we get through if / else? The next natural construct after if/then/else are loops. But maybe we should move to something a bit more right brained so as not to loose our hypothetical students? And then move to loops? > Am I trying to get too low-level? Do we want to stay above the clouds, > keep this as a heuristic for teaching rather than a specific > curriculum? Perhaps a happy medium between a nose bleed view and having their nose in the dirt. Python is great for keeping your nose out of the dirt for many applications. You can put it their if it suits you but it's not a requirement. > -- > Geoff Gerrietts > "Ordinarily he was insane, but he had lucid moments > when he was merely stupid." --Heinrich Heine -Jeff From loewis at informatik.hu-berlin.de Tue Mar 5 04:37:52 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 05 Mar 2002 10:37:52 +0100 Subject: PyTypeObject* XXX(PyObject*) References: Message-ID: helmut.zeisel at aon.at (Helmut Zeisel) writes: > PyTypeObject* t = XXX(po); > > What should be XXX, i.e., what is the name of the function > to get the TypeObject of a Python Object? No function: t = po->ob_type. Regards, Martin From nhodgson at bigpond.net.au Tue Mar 19 05:13:34 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 19 Mar 2002 10:13:34 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: Andrew Markebo: > Maybe if I new the codepage used by the user, and use that to convert > the 8bit string to unicode?? Think about the situation where several people share a directory on a file server. Each user may use a different code page. A user may change code pages. File names can even contain letters that are not all available from one code page. On NT you can create file names from any sequence of Unicode characters but these names may not be usable when that disk is read from Windows 9x. Neil From wesc at deirdre.org Fri Mar 1 01:48:46 2002 From: wesc at deirdre.org (wesc at deirdre.org) Date: Thu, 28 Feb 2002 22:48:46 -0800 (PST) Subject: ANN: SV-SF Bay Area Python user grp (BayPIGgies) mtg 3/13 7:30pm Message-ID: <200203010648.WAA23404@alpha.ece.ucsb.edu> When: March 13, 2002, 7:30-9pm Where: Stanford University, Palo Alto, CA Title: BioPython Jeffrey Chang (School of Medicine, Stanford University) founded the BioPython project in 1999 to promote the development of shared software infrastructure in bioinformatics. His talk will cover the architecture and capabilities of Biopython and also give a sneak preview of the upcoming version. Click on BayPIGgies link below for more info, including driving directions, past meetings, schedule, etc. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, ? 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://deirdre.org/baypiggies wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From aahz at pythoncraft.com Mon Mar 25 17:17:18 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Mar 2002 17:17:18 -0500 Subject: When to use locks in a threaded Web-server References: Message-ID: In article , Thomas Weholt wrote: > >I got a web-server project based on BaseHTTPServer using threads ( >SocketServer.ThreadingMixin ). What do I have to do to make it "safe", >thread-wise? When do I have to aquire locks to set variables in a) the >webserver itself or b) in variables in the given requesthandler ?? Generally speaking, you only need to lock when you've got an object shared across multiple threads. Doesn't look like you need any locking in your example, but because Python objects are technically global and Python provides a great deal of introspective capability, it can be tricky to figure out what objects are shared. Generally speaking, if you use Queue.Queue() to transfer information between threads, you don't need any locking. See the OSCON 2001 slides and examples on my web page for more details. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From thoa0025 at mail.usyd.edu.au Sun Mar 31 03:33:25 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 31 Mar 2002 08:33:25 GMT Subject: relational database? Message-ID: What relational database is easy to setup and use with python? besides msql (im having some problems) Cheeeers.. trungie From sholden at holdenweb.com Fri Mar 29 08:28:02 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 08:28:02 -0500 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: <0_Zo8.16784$Ou.11910@atlpnn01.usenetserver.com> "John Machin" wrote ... > "Steve Holden" wrote in message news:... [ ... ] > > This was a feature of the Icon language. But Icon had no explicit literal > > representation for dictionaries (or tables, as I think they were called) as > > far as I can remember, so it was easy to make the default value an argument > > to a constructor function. It's not obvious how you could indicate the > > default without calling a method. > > > > See above: freq = dict(default=0) > I think that I'm proposing indicating the default by having a keyword > argument ("default")on the new-in-2.2 constructor ("dict"); what do > you think that I meant? I knew what you meant, I was simply pointing out that dictionaries' literal representations could notr specify a default value, which (I supposed) might lead to VBScript-like horrors where all dictionaries (collections, in VBScript) must be created by explicit addition. However, Bength Richers suggestion: > empty_dict_with_default = {:default} > with_one_key_value_pair = {:default, key:value} > > A little tweak in the grammar might do it? might well suffice, and wouldn't require huge changes to the grammar. regards Steve From magnus at thinkware.se Wed Mar 20 08:34:40 2002 From: magnus at thinkware.se (Magnus =?ISO-8859-1?Q?Lyck=E5?=) Date: Wed, 20 Mar 2002 14:34:40 +0100 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> Message-ID: <3C988FF0.9010408@thinkware.se> > Andy Gimblett writes: >>
      >>
    • >> surname >>
    • >>
    Paul Rubin wrote: > Geez, I find all this pseudo-HTML horrendous. Why not just embed > normal looking code in tags the way PHP does it? Do WYSIWYG > editors have a problem with that? If worse comes to worse, embed > the Python code with the kinds of tags used for Javascript. The > WYSIWYG editors should be used to Javascript by now. Well Paul, this is actually rather clever, particularly where the labour is divided between someone who produces layout and text, and someone else who writes the code. If someone has written the HTML with just mock-up values where there should be data from the application you just add the attributes to replace the tag contents with program generated data. The HTML will display the same. You can look at the file in a browser or in deramweaver etc, and you will see the correct layout with the mock-up values. Run it in your application and you will see real data instead. With the PHP approach, the "visual designer" won't be able to see what the page will actually look like in his HTML editor. No way. He will have to guess, and upload it into the application and run it there to see if the visual appearence was the way he wanted. Sure, the data from the application might look fairly different from his mock-up data. In the example above he'll only see one list element, and in reality there might be many. It's still much closer to WYSIWYG than any other approach I've seen though. Even if you are the one and the same, it will probably be simpler to get the design right with this approach. From martin at v.loewis.de Sat Mar 2 03:44:56 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Mar 2002 09:44:56 +0100 Subject: Older Python bug entries on SourceForge References: Message-ID: David Bolen writes: > > So if you have a bug number below 300000, SF will have > > renumbered the bug by now. They used to have a backwards-compatible > > URL in place, redirecting to the new report, but they may have > > disabled that by now. > > Is there any way to compute the new number based on the old (e.g., by > adding some fixed constant or something)? I believe the following happened: Bugs, with bug-ids 1xxxxx, and URLs of the form http://sourceforge.net/bugs/?func=detailbug&bug_id=115845&group_id=5470 have been renumbered to 2xxxxx, with URLs of the form http://sourceforge.net/tracker/?group_id=5470&atid=105470&aid=215845&func=detail Just try it in this specific case; the redirection is still active. Patches in the 1xxxxx range have been renumbered to 3xxxxx. HTH, Martin From s.schwarzer at ndh.net Mon Mar 18 16:58:59 2002 From: s.schwarzer at ndh.net (Stefan Schwarzer) Date: Mon, 18 Mar 2002 22:58:59 +0100 Subject: Generating getter methods with exec References: <3C964E1A.84D5A26B@ndh.net> <3C96569F.8E76FA6E@metaslash.com> Message-ID: <3C966323.A522D680@ndh.net> Hello Neal thank you for your answer. :) Neal Norwitz wrote: > You don't need to generate code. This should do what you want: > > class GetterTest: > def __init__(self): > self._dict = {'key1': 'one', > 'key2': 'two', > 'key3': 'three'} > > def __getattr__(self, attr): > try: > return self._dict[attr] > except KeyError: > raise AttributeError, "getting attribute '%s'" % attr > > >>> g = GetterTest() > >>> g.key1 > 'one' > >>> g.key2 > 'two' > >>> g.key3 > 'three' > >>> g.key4 > Traceback (most recent call last): > File "", line 1, in ? > File "", line 8, in __getattr__ > AttributeError: getting attribute 'key4' Yes, that's the straightforward solution. :-) On the other hand, what I posted was a simplified example. Finally, I will have several dictionary-like objects and not all of their items should be accessible by get/set methods (only some of the corresponding attributes belong to the public interface). I'm a bit afraid the overhead of dynamically making all the decisions for every access might be slow (though it may well be that all will be fast enough). So to rephrase the problem a bit: I would like to generate simple getters and setters with rather little decision overhead during the actual accesses. Stefan From aahz at pythoncraft.com Thu Mar 14 08:56:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2002 08:56:13 -0500 Subject: Python Version Strategy? References: Message-ID: In article , Bo Vandenberg wrote: > >I'm confused by what is going on with the python versions from various >sources. > >I'm not even beginning to think of when the next version of python (3?) >comes out. Python 2.3 has been declared to be a "cleanup" release. While there will be some new features, the focus will be on getting all the new features from 2.0 through 2.2 in better shape, sanding off rough edges, and hopefully increasing performance a bit. >Anyone think they have inside information on all this? No inside information; this is mostly public. >What's a forward thinking newbie, with no old code to support to do??? Depends on what you're trying to do. If you're planning to distribute your code to the general public, this is an issue you'll need to consider carefully, and you might even consider going back to Python 1.5.2 (though everyone here will recommend that you strenuously avoid that if possible). If you're mostly worried about the upgrade treadmill, your best bet is to go ahead and use Python 2.2 for now and upgrade to 2.2.1 when that's released. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. --Aahz From prouleau at impathnetworks.com Tue Mar 12 13:12:36 2002 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Tue, 12 Mar 2002 13:12:36 -0500 Subject: Manage Windows shortcut in Python Message-ID: <3C8E4514.3E8D6684@impathnetworks.com> Is there existing python package/module/function that can be used to manage Windows file shortcuts? I would need to be able to: * create a shortcut to a known file * read an existing shortcut and get the file it points to * update the content of a shortcut file and change to file it points to. Thanks for the help. Pierre Rouleau From SBrunning at trisystems.co.uk Wed Mar 27 04:02:01 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 27 Mar 2002 09:02:01 -0000 Subject: Python Web Programming Book? Message-ID: <31575A892FF6D1118F5800600846864DCBCEB6@intrepid> > From: Michael Hall [SMTP:olc at ninti.com] > I'm wondering if anyone can suggest the best (or a selection of the > best) books available covering the use of Python in a web and database > environment? It's OK if the book deals with other stuff, as long as its > treatment of web programming and database integration is good. Steve Holden's "Python Web Programming" sounds *exactly* right for you - it covers web programming (both client & server side) *and* database programming in some depth. > Is a book that also deals with Zope, Cheetah and Albatross or > related topics (embedded Python, I suppose) asking just too > much? Yes. > A good text will certainly cut down my newbie questions to this list. > So far I have Mark Lutz' "Python Programming" and Andre Lessa's "Python > Developer's Handbook" on my shortlist. Mark Lutz's "Programming Python" covers the same ground as Lessa's book (GUI programming, System programming, text processing etc.), and in more detail. You don't need both, and I recommend the Lutz book. It *also* covers web programming, but not to the same depth as Holden's book does. Oh yes, BTW, you might want David Beazley's "Python Essential Reference" on your list, too. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From tim.one at comcast.net Mon Mar 4 19:30:54 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 04 Mar 2002 19:30:54 -0500 Subject: Win32 2.2 & 2.1.2 In-Reply-To: Message-ID: [Robin Becker] > Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the > default for a win32 box. It would allow us to dip a toe in the water > without drowning. If you're using the PythonLabs 2.2 installer, click the "Advanced Options ..." button on the "Select Components" dialog. On the "Advanced options" dialog that pops up, select the "Non-Admin install" radio button and uncheck the "Register file extensions" option. I have no real idea what "the default" means to you, but that should cover most plausible meanings . From skip at pobox.com Sat Mar 9 14:21:29 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 9 Mar 2002 13:21:29 -0600 Subject: PEP Parade In-Reply-To: <3C8A161D.50601@sneakemail.com> References: <3C895594.60601@sneakemail.com> <3C8A161D.50601@sneakemail.com> Message-ID: <15498.24761.570045.731534@12-248-41-177.client.attbi.com> >>> Just out of curiosity, what does the rest of your group develop in >>> then? >> For internal tools, mostly perl. For production code, mostly C/C++ >> and TCL. Joshua> If your fellow developers think that makes Perl stable compared Joshua> to Python's rate of change, I think they're fooling themselves. You just program in the stable subset. ;-) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From dale at riverhall.NOTHANKS.co.uk Thu Mar 14 06:46:38 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 14 Mar 2002 11:46:38 +0000 Subject: possible string.strip memory leakage References: Message-ID: Mike Brenner wrote: >There might be a memory leak in string.strip. > >I wrote a python function to strip blanks off the left and right of a string. When I discovered string.strip, I replaced the call to my version with string.split, and I got a large memory leakage. When I put the call back to calling my python function, the memory leakage went away. > I'd be more inclined to search for your newline leak. -- Dale Strickland-Clark Riverhall Systems Ltd From p.magwene at snet.net Wed Mar 27 20:30:59 2002 From: p.magwene at snet.net (Paul M) Date: Thu, 28 Mar 2002 01:30:59 GMT Subject: new style classes and IDLE "grump" Message-ID: In Python 2.2 when invoking the __init__ method of a new style (i.e. derived from object) class in IDLE, the calling "signature" doesn't show up like it does when instantiating a classic class object. For example, try the following in IDLE: This isn't really a bug, but a somewhat annoying feature of new classes in the context of the IDLE interpretter. From eppstein at ics.uci.edu Sat Mar 30 02:42:34 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 29 Mar 2002 23:42:34 -0800 Subject: PEP 285: Adding a bool type References: <3CA56915.62947DDC@alcyone.com> Message-ID: In article <3CA56915.62947DDC at alcyone.com>, Erik Max Francis wrote: > > I offer the following PEP for review by the community. If it receives > > a favorable response, it will be implemented in Python 2.3. > > Outstanding! I've been waiting and hoping for Booleans in Python since > I first was introduced to it. It's not an important issue to me, but I like the PEP. > > 3) Should the constants be called 'True' and 'False' > > (corresponding to None) or 'true' and 'false' (as in C++, Java > > and C99). > > I'm also a C, C++, and Java guy, but I think that True and False (rather > than true and false) are more Python, as you say, given None. Internal > consistency makes more sense to me than matching other languages. What he said. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From theller at python.net Wed Mar 20 04:02:41 2002 From: theller at python.net (Thomas Heller) Date: Wed, 20 Mar 2002 10:02:41 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: "Fernando P?rez" wrote in message news:a78uvi$ff1$1 at peabody.colorado.edu... > Magnus Lie Hetland wrote: > > > > > - Magnus (who also is a bit baffled as to why distutils doesn't > > include an "uninstall" command, such as the one implemented by > > Thomas Heller.) > > Amen. It's incredibly annoying to have to tell users that a simple python > setup.py install does the trick as far as splattering files all over their > system, but that there's no reasonable way of undoing the process easily. > I've just posted a little script to ActiveState's Python cookbook which helps with this (at least on windows, but something similar could be done on linux IMO): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117248 It builds a windows installer on the fly from a distutil's source distribution, and runs this. This gives you uninstall support. I've tested it with pychecker, anygui, twisted, and more packages I don't remember at the moment. My uninstall command Magnus menntions is a little hack only, a real distutils uninstall command would probably require to implement PEP 262 (database of installed packages) and let the install command update this database. Thomas From emile at fenx.com Fri Mar 22 17:51:21 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 22 Mar 2002 14:51:21 -0800 Subject: Packaging tool References: Message-ID: mohamed lazreg > I have been encouraged by the responses I got about my > bug tracking system question... So now I am looking > for a free packaging tool writeen in python (it has to > be in python)... By a packaging tool I mean a tool > that goes into a development area of a software, takes > the correct files and binaries depending on some user > parameters (configuration files) then creates a > package ready to distribute... > There are several. Look at freeze, py2exe to start http://www.python.org/doc/FAQ.html#4.28 -- Emile van Sebille emile at fenx.com --------- From hgg9140 at seanet.com Fri Mar 22 23:48:37 2002 From: hgg9140 at seanet.com (Harry George) Date: 22 Mar 2002 20:48:37 -0800 Subject: Porting a Python app to IRIX -- need help References: Message-ID: "Paul F. Dubois" writes: > I am trying to get a Python-based app running on an SGI running IRIX 6.5. I > am running into a problem involving some objects being compiled "n32" and > others "o32". The linker refuses to link them. > > I got pretty far by setting environment variable CC to "cc" but then it > complained that the X11 library is o32. Can an SGI person tell me whether > o32 or n32 is "normal" and what I tell the compiler to be sure I get that? > > > You have to decide to use n32 or o32. If you are not forced by some legacy library to use o32, I recommend using n32. Then you have to decide which compiler to use. For o32 we used SGI's own compiler, with CC='/usr/bin/cc -o32' But now that we are moving to n32, we are using gcc (which only knows n32). gcc is better for some open source libraries and applications. CC='gcc' Having made those choices, you can compile the generic libraries you will be needing (e.g., tiff, jpeg, png, zlib). We do a lot of the open source libraries. Then build python itself. Then continue on with python add-on modules. -- Harry George hgg9140 at seanet.com From James_Althoff at i2.com Mon Mar 4 16:10:55 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 13:10:55 -0800 Subject: PEP 276 (was Re: Status of PEP's?) Message-ID: [Carel Fellinger] > and define your classes to let __len__ return an Int object. > > class List(list): > def __len__(self): > return Int(len(list(self))) > > trying it out, yack it doesn't work, len forces it into an int again:( > > >>> spam = List("spam") > >>> type(spam.__len__()) > > >>> type(len(spam)) > > > I think this qualifies as a bug. Here's a similar way to try out PEP 276. Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from __future__ import generators >>> >>> class iint(int): ... def __iter__(self): ... i = 0 ... while i < self: ... yield i ... i += 1 ... raise StopIteration ... >>> __len = len >>> >>> def len(seq): ... return iint(__len(seq)) ... >>> l = ['a','b','c','d','e','f','g','h'] >>> >>> for i in len(l): ... if i % 2 == 0: ... print l[i] ... a c e g >>> # PEP 276 in action ... >>> BTW, if anyone knows how to add a method to class int (without resorting to the C code), let me know. I can't seem to get around int.__dict__ being a dict-proxy that can't be subclassed, modified, etc. Probably by design <0.1 wink>. Jim From grey at despair.dmiyu.org Wed Mar 6 19:51:59 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 07 Mar 2002 00:51:59 -0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 16:21:31 -0800, David Eppstein wrote: > Speak for yourself, please. To Steve Lamb, range(foo,bar,baz) may be > clear but it is not to me. PEBKAC? > And please avoid the ad-hominems ("too lazy to learn the language"), it > doesn't contribute to rational debate. Then why is it you're so gung-ho to make the language more complex when there are several ways to what you want already in the language? Fine, don't like range(n-1,-1,-1) and don't feel like taking the <60s to look it up? I give you: foo = range(n-1,0) foo.reverse() for x in foo: do_whatcha_like(x) Still too obtuse for you? x = bar while x > n: do_whatcha_like(x) x = x-1 Anyone else care to jump in and show a different method? The point stands, this PEP is a specific language nit for a specific case which is easily solvable by SEVERAL general constructs already available in the language. It is very limiting (only allowing one stepping, apparently) and would be used only in very specific cases. IMHO those should be avoided like the plague for while they might be useful in a very limited sense a slew of said specific case constructs creates a language that is large, bloated and difficult to read overall because you have to learn how dozens of different special case constructs work instead of, heaven forbid, just read the code and be able to grok the meaning out of a small set of generic constructs. Furthermore specific constructs for specific cases also blow maintainability out of the water. Take the famous example from Perl. if () {} unless () {} statement if () statement unless () Only one of them is maintainable; the first. Sure, the other's look nice and sometimes unless (foo) is easier to figure out than if (!foo) but the point is in the last three cases one cannot easily add an else unless they rewrite it to the former. You have different ways of approaching your problem as it is. You can build a set any way you choose before tossing it into either of available generic constructs. There is no compelling reason to add one more other than to appease one person's "It's not clear to me." That, sir, is NOT enough. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From James_Althoff at i2.com Fri Mar 8 19:56:42 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 8 Mar 2002 16:56:42 -0800 Subject: PEP 284, Integer for-loops Message-ID: Roy Smith wrote previously: |I just took a look at some random collection of python code I've got laying |around, totaling 6100 lines. I've got 85 for loops, 12 of which use range, |the other 73 don't. What's even more interesting is that of the 12 ranges, |11 of them are in a single file; the only file of the collection which I |didn't write (and which I consider pretty ugly code). David Mertz: |I decided to do the same test (more or less). A current snapshot of |my "Gnosis XML Utilities" has 3100 lines (written largely by me, |with various contributors). | |There are *4* uses of [x]range() in 'for' loops. One is a test case |that just uses 'range(500)' to do something "a bunch of times". One of |the remaining three is 'range(1,len(fields),2)', which doesn't lend |itself easily to the integer-iterator proposal. There are *two* |occurrences of 'range(len(member))', which I agree are slightly awkward |to write and read. | |There are actually more uses of the range() function to indicate ranges |of ASCII values than in the loop context, in this particular lump of |code. I just did the same for a small section of our code. My quick little scan turned up 293 uses of [x]range. Most -- as in nearly all -- of them are in for-loops and *are* used in conjunction with the indices of collections. Our mileage might be different from others because our use of Jython is for large-scale, shipping, production-level, commercial applications rather than for small, throw-away scripts or core-language libraries. Also (as mentioned) we use Jython and have to deal with tables and other kinds of collections written in Java outside the scope of core C-Python. So I guess we lose. Jim Althoff Senior Vice President i2 Technologies, Inc. From laytonjb at bellsouth.net Tue Mar 5 18:49:17 2002 From: laytonjb at bellsouth.net (Jeff Layton) Date: Tue, 05 Mar 2002 18:49:17 -0500 Subject: Newbie Python+XML Question Message-ID: <3C85597D.D0DD25FE@bellsouth.net> Hello, I'm fairly new to Python and I'm trying to understand and run some else's code that uses XML (SAX). Here's the top part of the code: # import socket import getopt import string import xml.sax #import xml.sax.saxutils from xml.sax import saxutils import sys class XmlHandler(saxutils.DefultHandler): def __init__(self, argv, machines=[]): saxutils.DefultHandler.__init__(self) self.info = {} self.hostname = '' self.max_hostname_len = 0 self.metrics = {} self.machines = machines I tried following the SAX example at: http://py-howto.sourceforge.net/xml-howto/xml-howto.html to understand what the author was doing. However, when I run the script as follows, it dies on me. % python2.1 testg.py Traceback (most recent call last): File "testg.py", line 26, in ? class XmlHandler(saxutils.DefultHandler): AttributeError: 'xml.sax.saxutils' module has no attribute 'DefultHandler' It looks like the SAX stuff is not getting imported correctly. Does anyone feel like helping a lowly Newbie with this one? TIA, Jeff From phd at phd.pp.ru Mon Mar 11 06:08:17 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 11 Mar 2002 14:08:17 +0300 Subject: Homepage of Gadfly not available? In-Reply-To: <3C8C8DA1.5040901@med.uni-tuebingen.de>; from rupert.kolb@med.uni-tuebingen.de on Mon, Mar 11, 2002 at 11:57:37AM +0100 References: <3C8C8DA1.5040901@med.uni-tuebingen.de> Message-ID: <20020311140817.L25769@phd.pp.ru> On Mon, Mar 11, 2002 at 11:57:37AM +0100, Rupert Kolb wrote: > for weeks, I'm trying to reach the home page of the Gadfly DB. > http://www.chordate.com/gadfly.html doesn't work. > Is this my fault? No, it is down for some time, and probably forever. The original author stopped working on it. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mwh at python.net Thu Mar 7 08:12:43 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Mar 2002 13:12:43 GMT Subject: The language vs. the environment References: <7x1yexe2mi.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Skip Montanaro writes: > > There has been a huge amount of recent PEP activity related to further > > enhancements to the language. I think in general that if more of this > > energy was directed at the overall environment (library, support tools, > > installers, documentation, etc) we'd be better off in the long run. > > While we're at it, am I the only one bothered by how unsharp the > boundary is between the language and the environment? I'd consider > things like sys.exc_info to be part of the environment, but there's no > other way to get the info. You've lost me. Care to elaborate? Cheers, M. PS: bear in mind my fondness for common lisp -- I'm not convinced separation of language and environment is a good thing... -- languages shape the way we think, or don't. -- Erik Naggum, comp.lang.lisp From logiplexsoftware at earthlink.net Fri Mar 15 12:57:06 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 15 Mar 2002 09:57:06 -0800 Subject: new to python - please help In-Reply-To: References: <837koen7mq.fsf@panacea.canonical.org> Message-ID: <20020315095706.1e9d7be5.logiplexsoftware@earthlink.net> On 14 Mar 2002 18:23:03 -0500 Aahz wrote: > In article <837koen7mq.fsf at panacea.canonical.org>, > Kragen Sitaker wrote: > >"Jason Orendorff" writes: > >> > >> Rule #1: Post real code. > >> > >> I can't make heads or tails of your post because all > >> that code is so broken. :-/ It's got syntax errors. > > > >I feel like I just walked into comp.lang.perl.misc circa 1998. > > There's a critical difference: how do you tell when Perl has a syntax > error? ;-) Perl has syntax? -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From jgardn at alumni.washington.edu Wed Mar 6 08:53:41 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Wed, 06 Mar 2002 22:53:41 +0900 Subject: Flushing stdout with raw_input - BUG Message-ID: raw_input and several modules that are part of the standard library that handle input and output with stdout and stdin (cmd.py) do NOT - I repeat - do NOT flush stdout before waiting for input. No, I don't want to flush buffer stdout everytime I write to it. That is wasteful and inefficient. I want to flush the buffer when I am done writing to it, or when I make a call to raw_input(). (This has been brought up before a long time ago - why is it not fixed? Why does Guido want it to behave like this?) If it is running with a terminal, then the underlying code (in C or the Kernel, I am not sure) will flush stdout before reading input. However, it does not automatically flush stdout before reading stdin if stdout and stdin are not terminals. That means if I write a program that forks off another process that runs a python script that uses stdin and stdout, (using something like Popen3), then the conversation goes something like this: parent: (Waiting patiently for some information from the child) child: (wrote to stdout but didn't flush the buffer, so he doesn't send anything yet) child: (expects input from stdin - which will be coming from the parent) parent: (Waiting patiently for some information from the child) programmer: (Going insane and pulling his hair out, screaming at the computer bloody murder) BLOODY MURDER! BLOODY MURDER! If raw_input and other modules that ask for input would flush stdout before they wait for input, the conversation would look like this: parent: (Waiting patiently for some information from the child) child: (wrote to stdout and flushed the buffer)What is your command? child: (expects input from stdin - which will be coming from the parent) parent: (Receives the message)(writes to stdin of the child and flushes the buffer)HAHA! YOU ARE NOW UNDER MY CONTROL! child: (receives the message through stdin)SYNTAX ERROR. programmer: (Much more relaxed now...)Now that the program is working, I can get some sleep! Whew! (has pleasant dream of Python hacking...) Should I turn on -u for the child script? That is silly. Just write raw_input properly, and make everyone happy. If you don't, I'll be *forced* to hack on the cpython code, and then you'll *really* regret it! =) I am running Linux 2.4.14 and Python 2.1.2. I tested this bug in Python 2.2 and it is still there. I posted a bug about cmd not flushing the buffer to sourceforge. I will post another bug about raw_input not flushing the buffer. I will write another bug report about the unresponsiveness to bug reports as well, as there are a lot of bugs that aren't even addressed at sourceforge. PLEASE PLEASE PLEASE! Examine your code. If you do not use raw_input, then flush your buffers! Otherwise, we will not be able to fork off your script/module and use it as a child process without -u. Thank you. Jonathan Gardner From CutieGirl19 at aol.com Sun Mar 17 21:53:16 2002 From: CutieGirl19 at aol.com (CutieGirl19 at aol.com) Date: Mon, 18 Mar 2002 09:53:16 +0700 (ICT) Subject: Hey! This is my new email address. Message-ID: <200203180253.g2I2rGo41985@unescobkk.org> Below is the result of your feedback form. It was submitted by (CutieGirl19 at aol.com) on Monday, March 18, 2002 at 09:53:16 --------------------------------------------------------------------------- : Hi, my name is Brigit and I am a 19 year old female from San Diego, California. Ever since my 14th birthday, I have been really sexually active, but I am still a virgin. Now I am 19 and away from home, attending school at San Diego State University and sharing a dorm with four of my girlfriends and are all VERY turned on to meet a guy and satisfy ALL of his pleasures. To see our sexy pictures we took just last week and to meet some other couples, go to our site
    http://www.signup4freecam.com/brigit

    --------------------------------------------------------------------------- From jschmitt at ati.com Thu Mar 7 19:52:21 2002 From: jschmitt at ati.com (John Schmitt) Date: Thu, 7 Mar 2002 16:52:21 -0800 Subject: reporting spam? (was RE: 5 dollar emails) Message-ID: What happens with all the spam this group gets? Does anyone bother forwarding it to spam-fighting agencies? For my own spam, I forward it to uce at ftc.gov. I got that email address from http://www.junkemail.org/scamspam/. That email address is also listed on the FTC web page: https://rn.ftc.gov/dod/wsolcq$.startup?Z_ORG_CODE=PU01 Since I use outlook to read the mailing list, I'm not sure if Outlook passes enough header information to make it useful or even if the FTC does anything about it anyway. John -------------- next part -------------- An HTML attachment was scrubbed... URL: From richard at stockcontrol.net Wed Mar 20 11:42:03 2002 From: richard at stockcontrol.net (Richard Walkington) Date: Wed, 20 Mar 2002 16:42:03 +0000 Subject: Popular style document? References: <1016641355.370859@cswreg.cos.agilent.com> Message-ID: <3C98BBDB.4030407@stockcontrol.net> Greg Weeks wrote: >Is there a popular style document for Python? I realize that there isn't a >whole lot of scope for such a thing, but I wondered because of certain >particular issues that came to mind. > There's this: http://www.python.org/doc/essays/styleguide.html From writeson at earthlink.net Wed Mar 6 17:44:03 2002 From: writeson at earthlink.net (Doug Farrell) Date: 6 Mar 2002 14:44:03 -0800 Subject: Python daemon instead of CGI programs Message-ID: <88bc63c6.0203061444.30ad9c44@posting.google.com> Hi all, I've got an idea that anyone is welcome to shoot holes in as it's only in the 'thought' process now. I work for a company that develops big content web sites using CGI's built with C++ as the primary programming model. We also use Netscapes iPlanet as our web server. I'm of the opinion this is akin to killing a fly with a sledgehammer and am thinkin of some other mechanism. One thought that occurred to me was to create a Python daemon that has a thead pool, a pipe pool and all the CGI functionality built into classes that could be run by a thread. Here's what I'm thinking, create an SAF (Server Application Function) directive that will direct all the URL and POST information down the pipe to the waiting Python daemon. The daemon kicks off a thread from the pool to run the appropriate 'CGI' handler class. This class directs all it's output into the same pipe back to the server. The server forwards all this data to the users browser. Doing this allows us a couple of things. By having a daemon the Python interpreter is already in memory and doesn't have to be loaded. All of the 'CGI' code is also in memory all the time, this would make execution of that code pretty fast. We get to develop in Python, which has a faster development cycle than C++ code. We can handle multiple requests to the server because of the multiple pipes/threads in the Python daemon. We don't have to work out any of the complexities of connecting mod_python.so to iPlanet. What do you think of this idea? Am I completely off base and missing some other obvious solution? Thanks in advance, Doug From jeff at ccvcorp.com Fri Mar 29 13:55:42 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 29 Mar 2002 10:55:42 -0800 Subject: Boa v0.1.0-alpha + unrelated question References: Message-ID: In article , buzzard at urubu.freeserve.co.uk says... > On an unrelated note; is there a better (more Pythonic / more efficient) way > of swapping two rows in a Numeric array than the following. > > def swapRows(array, index1, index2): > temp = array[index2, :].astype(type(array)) > array[index2, :] = array[index1, :] > array[index1, :] = temp Well, I don't know about Numeric specifically, but the 'canonical' Python swap idiom would make it this: def SwapRows(array, i1, i2): array[i1, :], array[i2, :] = array[i2, :], array[i1, :] (In general, 'a, b = b, a' creates a temporary tuple, then unpacks it back to the original names but in reverse order. However, I can't swear that this will work with Numeric because I've never used Numeric, and it may be doing odd things that don't interact well with being packed into a temporary tuple.) -- Jeff Shannon Technician/Programmer Credit International From guido at python.org Sat Mar 30 09:23:49 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 09:23:49 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type In-Reply-To: Your message of "Sat, 30 Mar 2002 09:04:31 EST." <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> Message-ID: <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> > > [David Abrahams] > > > 6) Should we eventually remove the inheritance relationship > > > between Int and Bool? > > > > > > I hope so. Bool is-a Int doesn't seem like the right relationship to > > > me, unless perhaps we make Int is-a Long... naah, not even then. > > > > Hm. In your favorite language bool is one of the integral types. > > Doesn't that imply pretty much the same thing? > > Well, I try not to play favorites <0.002 wink>, but the implicit > conversion rules in C++ are admittedly and unfortunately liberal. > However, bool is detectably NOT derived from int in C++: > > void f(int const&); > f(false); // error! > assert(boost::is_base_and_derived::value); // fails! I don't understand this example, but I though int and bool weren't considered classes in C++, so I'm not sure this matters. I know you don't care, but C99 *does* consider bool an integral type. Another argument for deriving bool from int: implementation inheritance. A bool must behave just like an int, and this is most easily accomplished this way: the bool type doesn't have implementations for most operations: it inherits them from the int type, which find a bool acceptable where an int is required. > > Anyway, do you have a use case where it matters? > > Given that Bool is immutable, I have no cases other than examples of > type introspection which can be written to account for the fact that > Bool is-a Int. However, it does make certain things trickier to get > right: > > numeric_types = [ Int, Long, Bool, Float, Complex ] > for t in numeric_types: > if isinstance(x, t): > # Do something... > > This sort of thing could depend on getting the order of the list right > (I didn't). Using isinstance() this way is usually bad. And who knows that long doesn't inherit from int? (At some point in the future it may, or they may become the same thing -- see PEP 237. --Guido van Rossum (home page: http://www.python.org/~guido/) From aahz at pythoncraft.com Sun Mar 31 18:38:10 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 18:38:10 -0500 Subject: Python quick setup URL for Linux setup? References: Message-ID: In article , Robert Oschler wrote: > >Can anyone point me to a fasttrack URL/doc for setting up Python on Linux >running KDE? If it matters I'm using SUSE 7.3 Pro. First of all, you should already have Python installed on your system (although an older version). What happens if you just type "python"? As for compiling Python, just cd to the source directory and run the following commands: ./configure make make test -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From jgardn at alumni.washington.edu Wed Mar 6 09:41:36 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Wed, 06 Mar 2002 23:41:36 +0900 Subject: fork and thread and signal... oooooops References: <87550ef1.0203050846.2166835e@posting.google.com> Message-ID: Haeyoung Kim scribbled with his keyboard: > I know little about system programming, so my code has become a > monster. =) > My situation is : 1) used /etc/init.d script functions such as daemon, > killproc to start/stop python script. Good ole' SysV. > 2) python script is composed of two tasks. launching java server > program and running script that connects that server to see if it's > alive or dead. Okay. If you want to see if something is alive or dead, the standard way is to check its pid file thing. That is a file that is stored in /var/run, and is usually named something like atd.pid (for atd, the 'at' daemon). So, if yu want to call your server hyjavad (please end with a 'd'), you will use a pid file at hyjavad.pid. That is assuming you only want one running at any time. What do you do with the pid file? When the server starts up, he should immediately check to see if the pid file exists. If it does, he just dies. There is no reason to have two of the same daemons. If it isn't there, create it, and put your pid in there. When your programs dies, by signal or whatnot, you need to be sure to get rid of the pid file, or else you cannot start a new server. I am not sure if it is best to do that by watching for signals or by using _atexit. I think most people use signals... correct me if I am wrong. > > When shell script calls killproc(in init.d script), it sends signal, > and kill server-using os.kill(java_server_pid)- and get out of > os.wait() and died out generously - just my hope. > But it betrayed my hope. it throws TypeError on os.wait(), killed > anyway, but there are still my java program. :( > I think signal doesn't call exitProgram() - why? > Is there any clean solution to such a matter? Okay, step back, take a deep breath. Let's think about what you want to do in careful detail. You have a server. You want this server to stick around no matter what. That is, until you want to kill it. You need it to respond to different signals. What it does with those signals is up to your server. Your init.d script will be written in sh, not python. It would be a horrible idea to write an init.d script in python. Look at other init.d scripts for examples on how to do this. Now what do you need the python script for? Do you want to make a script that watches the server? Why? Jonathan From just at xs4all.nl Sun Mar 10 16:55:42 2002 From: just at xs4all.nl (Just van Rossum) Date: Sun, 10 Mar 2002 22:55:42 +0100 Subject: How to disable assert statements inside a module? References: Message-ID: In article , martin at v.loewis.de (Martin v. Loewis) wrote: > Pearu Peterson writes: > > > Is there a way to disable all assert statements inside a module, > > and without calling python with -O switch? > > You can set __debug__ to 0 on the module level; this will disable > assert statements inside this module. That's what I thought, too, but you get a SyntaxError in 2.2. Unhelpfully, Just From stojek at part-gmbh.de Wed Mar 27 08:05:47 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Wed, 27 Mar 2002 13:05:47 GMT Subject: overwrite bytes in file Message-ID: <3ca1c344.16256546@news.easynews.net> Hi, how can I overwrite certain bytes in a file (Win NT) and keep the rest unchanged. All open options are truncating the file. Thanks Marcus From phr-n2002a at nightsong.com Fri Mar 8 09:20:58 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 08 Mar 2002 06:20:58 -0800 Subject: print >> details??? References: Message-ID: <7xlmd3gmyd.fsf@ruckus.brouhaha.com> "spex66" writes: > where does the second call of x.write() come from??? > > thanks for any hints The print statement prints the stuff you tell it, then prints a newline. From harald.keicher at web.de Mon Mar 11 11:41:13 2002 From: harald.keicher at web.de (Harald) Date: Mon, 11 Mar 2002 17:41:13 +0100 Subject: Newbie Python+Zope Question Message-ID: <3c8cddf1@uni-wuerzburg.de> Hello, I'm fairly new to Python and I'm trying to instal a new version of zope (2.5.0) www.zope.org. At the moment I have running suse 7.2, python 2.1.2 and zope 2.0. After 'tar xzvf Zope-2.xxxx.tgz' I started the compiling of the Zopeserver with 'python wo_pcgi.py'. I get this error messages: ------------------------------------------------------------------------------ Deleting '.pyc' and '.pyo' files recursively under /usr/local/ZopePark/Testserver... Done. ------------------------------------------------------------------------------ Compiling python modules ------------------------------------------------------------------------------ Building extension modules cp ./lib/python/Setup20 ./lib/python/Setup ------------------------------------------------ Compiling extensions in lib/python cp /usr/lib/python2.2/config/Makefile.pre.in . cp: cannot stat `/usr/lib/python2.2/config/Makefile.pre.in': Datei oder Verzeichnis nicht gefunden Traceback (most recent call last): File "wo_pcgi.py", line 45, in ? File "wo_pcgi.py", line 33, in main File "/usr/local/ZopePark/Testserver/inst/build_extensions.py", line 30, in ? make('lib','python') File "/usr/local/ZopePark/Testserver/inst/do.py", line 61, in make do("cp %s ." % wheres_Makefile_pre_in()) File "/usr/local/ZopePark/Testserver/inst/do.py", line 32, in do if i and picky: raise SystemError, i SystemError: 256 Harry From nospam at bellsouth.net Fri Mar 15 16:08:10 2002 From: nospam at bellsouth.net (Nospam) Date: Fri, 15 Mar 2002 16:08:10 -0500 Subject: callling dynamically obtained win32api function Message-ID: <3C9262BA.5060106@bellsouth.net> I'm trying to understanding how to complete this following code: import os import win32api GWL_EXSTYLE=-20 LWA_ALPHA=0x2 u32=win32api.LoadLibrary("user32.dll") if u32: slwa=win32api.GetProcAddress(u32, "SetLayeredWindowAttributes"); print type(slwa) # how do I call slwa here? I tried win32api.Apply ... win32api.FreeLibrary(u32) I could not find an example of doing this in the docs. Thanks From martin at v.loewis.de Tue Mar 26 05:19:03 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 26 Mar 2002 11:19:03 +0100 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> <3C9FBDB0.7E0BCA16@engcorp.com> Message-ID: Peter Hansen writes: > Maybe it's just the ones who already knew how to do this, who > knew how to do this.... ;-) I guess Barry sort-of expected everybody to know that pointing to foo.sf.net should trigger the "SF structure" synapse, so you'd immediately know that the CVS can be reached through sf.net/projects/foo, which has the CVS link in the standard location. Regards, Martin From just at xs4all.nl Sun Mar 10 02:02:28 2002 From: just at xs4all.nl (Just van Rossum) Date: Sun, 10 Mar 2002 08:02:28 +0100 Subject: round() function strange behaviour References: <3c8a9261.149508269@news> Message-ID: In article <3c8a9261.149508269 at news>, brobbins333 at shaw.ca wrote: > 2.1 and 2.2 both behave this way on two different (Windows) computers. > What's going on here? You've already received a bunch of answers but I see noone has quoted Tim's tutorial extension ("node 14"): http://www.python.org/doc/current/tut/node14.html (Which btw. is the first google hit if you search for "python floating point".) Just From bokr at oz.net Tue Mar 12 16:56:20 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Mar 2002 21:56:20 GMT Subject: doctest Hassles! References: <10d46bdc.0203120928.7e9c708b@posting.google.com> Message-ID: On 12 Mar 2002 09:28:11 -0800, doug at pobox.com (Douglas Garstang) wrote: >I posted a question yesterday about how to get doctest to interpret >output from the execution of an external program. It was suggested I >use: > >ls=os.popen("/bin/ls","r").read() > >instead of trying to use spawnv. Well, when I print the value of ls, I >get: Are you accounting for the newline that print supplies at the end? > >' > example.py > example.pyc > tester.py > >' > >Notice the blank line at the end. Where did that come from? There >isn't a file with no name in my directory, so why would it print an >empty line? Also, why is the output in ONE column instead of across >the screen (as in a normal ls) when spawnv is used? All I did was >print the output of the ls command, but the output is different. You opened a pipe with popen to read the output of ls. Non-terminal output defaults to single column. If you type 'ls | cat' in the shell you will get one column too, unless you type 'ls -C | cat' to force multicolumns. > >Now, in my code I have: > >def tester3(): > """ > >>> import os > >>> ls=os.popen("/bin/ls","r").read() > >>> print ls > example.py > example.pyc > tester.py > > """ > >It ignores the blank line at the end, as the docs say it will. On a ^^--what ignores what blank line? There's no executable code above. try 'ls | hexdump -c' to see the data your pipe is getting fed. >side note, I've had this problem before with python, trying to read >text config files. As soon as it hit an empty line, reading would >stop! Huh? > Post the actual code that behaves that way, and you may get an explanation. >So, as a result, it ignores the empty line on the expect, but gets it >on the output, and the test fails! > >What am I missing here? I would imagine that executing external >programs is central to testing, but it seems to be _really_ difficult. Posting specific actual failing code is the best way to get specific help. Copy and paste from an interactive session, don't type an approximation. Regards, Bengt Richter From dsavitsk at e-coli.net Wed Mar 13 17:36:30 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 13 Mar 2002 22:36:30 GMT Subject: basic statistics in python Message-ID: hi all, never having done numeric calculations in python* i am seeking advice on how to best go about doing some basic statistics. in particular, i need to find standard deviations and point bi-serial correlations**, and i am seeking advice on the best way to go about it. i know how to do them, but i am wondering if there are prebuilt modules that might simplify the task. i found this http://starship.python.net/crew/hinsen/ScientificPythonManual/ but it seems to be unix only and i am on win32. as far as standard deviations, i found this in an old ng post. def stddev( *x ): if not x : return 0 if ( len(x) == 1 ): x = x[0] m = mean( x ) var = 0 for n in x: n = n - m var = var + (n * n) return sqrt( var / float(len(x)-1) ) There seems to be some stuff in scipy, but i am having trouble geting through the docs. also, do i want to look at numpy? any suggestions? thanks, doug * all text processing thus far. ** i think that is the correct term, item total correlations in other words. *** in general though nobody is going to live or die by what the state say, so a small amount of error is not too big a deal. From brian at sweetapp.com Thu Mar 14 15:07:26 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 14 Mar 2002 12:07:26 -0800 Subject: XML-RPC Question In-Reply-To: Message-ID: <005901c1cb93$dd2fe860$445d4540@Dell2> Jesper Olsen wrote: > Setting up a server goes something like this: > > from SimpleXMLRPCServer import * > > class MyClass: > def helloWorld(self): > return "Hello World!" > > def echo(self, text): > return text > > myob=MyClass() > > server=SimpleXMLRPCServer(("",50000)) > server.register_function(myob.helloWorld) > server.serve_forever() While that usage is correct, it is a bit odd. There are two other ways that my might express this: # No need for a class def helloWorld(self): return "Hello World!" server.register_function(helloWorld) # Exports all of the methods in the class class MyClass: def helloWorld(self): return "Hello World!" def echo(self, text): return text server.register_instance(MyClass()) Of course I didn't test the above in any way :-) > Is there something wrong here, or does SimpleXMLRPCServer, not support > the listMethods() call? I'm in the process of reorganizing it a bit, but here is a SimpleXMLRPCServer implementation that does what you want: http://www.sweetapp.com/xmlrpc/ # Example server = SimpleXMLRPCServer(("",50000)) # Or use the following construction if you want the server to also # serve HTML documentation on that port (cool, eh?) server = SimpleXMLRPCServer(("localhost", 8000), SimpleXMLRPCAndDocsRequestHandler) # Make system.listMethods and system.methodHelp work server.register_introspection_functions() # Make system.multicall work server.register_multicall_functions() # Install your own methods/instance here... server.serve_forever() This, or something like this, should make it into Python 2.3. Cheers, Brian From bokr at oz.net Thu Mar 28 16:39:10 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Mar 2002 21:39:10 GMT Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: On Thu, 28 Mar 2002 07:52:45 -0800, "Ken Peek" wrote: >Well-- OK, my new ISP doesn't have a news server, but I found one >that I could use to post this with. If you reply to my email, do >the 'nospam' thing first to my email address... > >I really am interested in what people think about this. I have >looked at all the other c.l.py posts on this construct, but I >don't think anyone proposed this format. > >BTW-- the 'until' thing in the original letter was already posted, >so please disregard that part of this post- (I left it in for >accuracy.) > > -----Original Message----- > From: Guido van Rossum > Sent: Thursday, March 28, 2002 04:45 > To: Ken.Peek at SpiritSongDesigns.NOSPAM.com > Cc: Marc-Andre Lemburg > Subject: Re: PEP 0275 > > If you really want to discuss this, it's better to post to c.l.py. > > --Guido van Rossum (home page: http://www.python.org/~guido/) > > -----Original Message----- > From: Ken Peek [mailto:Ken.Peek at SpiritSongDesigns.NOSPAM.com] > Sent: Thursday, March 28, 2002 01:05 > To: Marc-Andre Lemburg > Cc: Guido van Rossum > Subject: PEP 0275 > > How about: > > match some_object: > > ("I dream of Jeanie",): > print "with the light brown hair" > > (1,3,5,7): > > print "some odd numbers" > > # 'break' leaves the entire match structure > if (time_to_leave): break > > # 'continue' jumps to the first > # statement in the next clause > continue > > (123,456,789): > > print "some bigger numbers too" > > (19,56,22): > > print "some random numbers" > > (1001,2002,3000): > # YES! It IS possible we want to do NOTHING! > pass > > any: > print "we got here because there were no matches" > =========================================== [13:32] C:\pywk\misc>python case.py "I dream of Jeanie" with the light brown hair [13:36] C:\pywk\misc>python case.py 5 some odd numbers [13:36] C:\pywk\misc>python case.py 456 some bigger numbers too [13:36] C:\pywk\misc>python case.py 22 some random numbers [13:36] C:\pywk\misc>python case.py 2002 [13:36] C:\pywk\misc>python case.py xxx we got here because there were no matches from following code: =========================================== def main(some_object): class CkObjIn: """functor class: instance holds object for check if in passed sequence""" def __init__(self,obj): self.obj = obj def __call__(self, *seq): return self.obj in seq ## now use it ck = CkObjIn(some_object) # instead of match line if ck("I dream of Jeanie",): print "with the light brown hair" elif ck(1,3,5,7): print "some odd numbers" ###### no: there should be now new meaning here ###### # 'break' leaves the entire match structure # 'continue' jumps to the first # statement in the next clause ###### no: there should be now new meaning here ###### elif ck(123,456,789): print "some bigger numbers too" elif ck(19,56,22): print "some random numbers" elif ck(1001,2002,3000): # YES! It IS possible we want to do NOTHING! pass else: print "we got here because there were no matches" if __name__ == '__main__': import sys try: arg = int(sys.argv[1]) except: arg = sys.argv[1] main(arg) =========================================== [...] > > Well, what do you think? > Kind of like it, but there would have to be some hot performance advantage. IMO the aesthetics aren't that much different from the above. I definitiely wouldn't like break and continue to mean new things! Regards, Bengt Richter From eppstein at ics.uci.edu Fri Mar 1 17:45:21 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 14:45:21 -0800 Subject: Status of PEP's? References: Message-ID: In article , James_Althoff at i2.com wrote: > In other words, if I want to iterate up (smaller up to larger) I need to > write the for-loop as > for smaller <= i <= larger: # can *only* iterate up > but if I want to iterate down (larger down to smaller) I need to write the > for-loop with the reverse relational operators > for larger >= i >= smaller: # can *only* iterate down > > So if you want/need "from/to" functionality for an "interval" using the > suggested for+relational idiom, you need to have two for-loops at hand, > test the bounds, *and* pick the corresponding, correct for-loop (whose > relational operators are in the correct direction). > > Note that the existing range and xrange functions (when used in a > for-loop), although requiring a test on the bounds in order to determine > the correct order of the args, do *not* require the use of two for-loops in > this context. > for i in range(n,m,step): # can iterate up or down depending on > n,m,step Ok, I missed your point that the iteration order and not just the endpoints are important in your example. But I think the current range system does too require two loops. Again, let's consider closed intervals. If from <= to: range(from,to+1) If from > to: range(from,to-1,-1) You could sort of avoid this by using a signum function: range(from,to+signum(from-to),signum(from-to)) but (besides being confusing) this breaks when from=to. Anyway, while you may need two ranges, you don't have to have two separate for-loops over those ranges: if from <= to: range = [x for from <= x <= to] else: range = [x for from >= x >= to] for x in range: ... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From fgeiger at datec.at Fri Mar 29 07:05:50 2002 From: fgeiger at datec.at (F. GEIGER) Date: Fri, 29 Mar 2002 13:05:50 +0100 Subject: ActivePython 2.2 released! References: Message-ID: For 2.1.2: Will there be an update option in the installer? I've installed many external Python modules, which I do not want to reinstall when updating from 2.1.1 to 2.1.2, if somehow possible. Thanks and cheers Franz GEIGER "David Ascher" schrieb im Newsbeitrag news:mailman.1017384524.14832.python-list at python.org... > We are pleased to announce that version 2.2 of ActivePython is now > available for download from http://www.ActiveState.com/ActivePython > > I'll also take this opportunity to mention that we will shortly be > issuing ActivePython 2.1.2 (a bug-fix release for Python 2.1), and > ActivePython 2.2.1 (a bug fix release for Python 2.2 currently > undergoing final testing). > > We're releasing 2.2 regardless of these upcoming releases because we'd > like to solicit feedback on some of the changes we've made in > ActivePython. Specifically, > > - the Windows installer is brand new, and should work on a wider > variety of platforms than before, including non-Administrator > accounts. > - there is more documentation bundled, including several tutorials > which were not previously shipped (especially on Linux). > - We've made some changes to the Python Package Manager (PyPPM). > > The PPM modules currently available include: > > * mxBase -- A set of utility classes including mxDateTime, > mxTextTools, mxStack, mxTools, and mxProxy > * Numeric -- high performance multi-dimensional array support > * PIL -- the standard Python Imaging Library > * PyChecker -- a code-proofing tool > * StandaloneZODB -- the persistence solution from Zope, now > available outside of Zope > * ZSI -- the reference SOAP library > * pyperl -- ActiveState's interface between Python and Perl > > Please submit email feedback to ActivePython-feedback at ActiveState.com, > and file bugs against ActivePython at > bugs.ActiveState.com/ActivePython. We will be using that feedback to > prepare the 2.2.1 and 2.1.2 releases. > > Thanks, and enjoy! > > -- David Ascher > ActiveState > From ianb at colorstudy.com Fri Mar 22 13:45:50 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 22 Mar 2002 12:45:50 -0600 Subject: Python embedded like PHP In-Reply-To: <20020322003738.A273C38F4C@coffee.object-craft.com.au> References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> Message-ID: <1016822750.495.34.camel@localhost> On Thu, 2002-03-21 at 18:37, Andrew McNamara wrote: > >> The intention is that Albatross templates be valid XML - while Albatross > >> will do the expected thing in the example you give above, it generally > >> provides a "better" way, such as: > >> > >> > > > >Do you mean that you have a template tag for every kind of tag for which > >you would want to modify an attribute? That's every single HTML tag -- > >IMG is hardly the only one. A dynamic CSS class attribute, for > >instance, or events (onMouseOver, etc), id tags, background colors... > >there's a million possibilities. > > No, we don't, although we're considering some options (such as abusing > the XML namespace - for example: - thoughts? I assume you are thinking that any al-* tag that isn't otherwise defined would turn into a plain tag? So you'd do ? Seems kind of unXMLish as well. You could do something like: ...
    That's very long, and you have to parse the entire document (I'm not sure if you are doing that now). Actually, it looks horrible and if I was using such a language I would hate you. Maybe: ...
    I'm not sure if that's quite kosher or not... I guess there's nothing really wrong about it, it just doesn't feel much like XML -- something about binding two elements together when they are only next to each other, not contained, seems odd. And it still isn't pretty. Of course there's the ZPT approach, which isn't bad, but then you might as well use ZPT. But I guess there's no reason you can't use something like ZPT just for changing attributes, like: And then skip all the looping and such that ZPT does with attributes. You'd still have the worry about generating CSS and Javascript, though. Dave mentioned performance... doing a full XML parse is performance-intensive, but you could fake it for this particular case -- you don't need to find the
    tag or anything, you could probably do it just with regexes. I still think it's so much easier to use [], and make the system orthogonal to XML or any other medium you might want to generate. I think it actually gives you better tool support as well. Ian From usenet at thinkspot.net Sat Mar 2 01:04:23 2002 From: usenet at thinkspot.net (Sheila King) Date: Fri, 01 Mar 2002 22:04:23 -0800 Subject: newbie password question References: <20020302003514.13693.00001116@mb-fw.aol.com> Message-ID: On 02 Mar 2002 05:35:14 GMT, etrofsouls at aol.com (EtrOFsouls) wrote in comp.lang.python in article <20020302003514.13693.00001116 at mb-fw.aol.com>: > password = "foobar" > > while password != "unicorn": > password = raw_input ("Password:") > print "Welcome In" > > I understand all this (thank god), but I'm having trouble figuring out how to > get it to keep track of the number of guesses and then print a message such as > "Halt, you do not have access!" if the number of guesses exceeds the limit. I'm > learning this thru on-line tutorials and this was given as an excersise. All I > have to work with is variables and statements such as...while, if, elif and > else. How about something like this? password = "foobar" validated = 0 for attempt in range(1, 6): password = raw_input ("Password:") if password == "foobar": validated = 1 print "Welcome In" break if not validated: print "Sorry, Charlie!" The variable validated keeps track of whether the person has yet managed to successfully give the correct password. (In this example, the correct password is "foobar".) The for loop lets the user try five times (try this at an interactive prompt: print range(1,6) It will return a list of the integers [1, 2, 3, 4, 5]. So basically, this loop will try for times 1, 2, 3, 4 and 5. The user gets five chances to get the correct password.. If they manage to get the correct password, the validated flag is set to "true" (i.e. the number 1), they are greeted with a "welcome", and the loop breaks. If the loop runs all five times, and after that the validated flag is still false, "Sorry, Charlie!". Hope this helps, -- Sheila King http://www.thinkspot.net/sheila/ "When introducing your puppy to an adult cat, restrain the puppy, not the cat." -- Gwen Bailey, _The Perfect Puppy: How to Raise a Well-behaved Dog_ From usenet at thinkspot.net Sun Mar 3 00:21:07 2002 From: usenet at thinkspot.net (Sheila King) Date: Sat, 02 Mar 2002 21:21:07 -0800 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <20020227163411.71b4b4d8.alex@netWindows.org> Message-ID: On Wed, 27 Feb 2002 16:34:11 -0500, Alex Russell wrote in comp.lang.python in article <20020227163411.71b4b4d8.alex at netWindows.org>: > I was required to purchase their Java book for a class, and not only was > it poorly laid out, poorly executed, badly typeset, and cheaply made, it's > index was utterly useless. Their C++ book wasn't much better. A friend had > it laying about his place day and I spent some time looking through it, > and after comparing it to Lippman/Lajoie, it's clear that it makes better > tinder than a programming reference. That's funny. I'm not familiar with the Lippman/Lajoie book, but I have a LOT of C++ texts here at home. And I learned C++ from the Deitel and Deitel book, and thought it was pretty good. Later, when I taught C++ I used it as a reference, although I didn't select it as the text for my course. Most people I know who are familiar with the Deitel and Deitel C++ text think it is very good. -- Sheila King http://www.thinkspot.net/sheila/ "When introducing your puppy to an adult cat, restrain the puppy, not the cat." -- Gwen Bailey, _The Perfect Puppy: How to Raise a Well-behaved Dog_ From mertz at gnosis.cx Tue Mar 26 22:19:52 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Tue, 26 Mar 2002 22:19:52 -0500 Subject: xml config file to python object (fwd) Message-ID: |For full pickling support, you can chose between xml_pickle, from | http://www-106.ibm.com/developerworks/xml/library/x-matters11.html The best URL to start with is probably: http://gnosis.cx/download/Gnosis_XML_Util.ANNOUNCE Since I wrote the mentioned article, xml_pickle has gained quite a bit new fancy stuff... xml_objectify to a lesser extent. The original poster seems to want something fairly close to what xml_objectify does, IMO. Yours, David... From pan-news at asheeshenterprises.com Mon Mar 18 07:01:47 2002 From: pan-news at asheeshenterprises.com (Asheesh Laroia) Date: Mon, 18 Mar 2002 12:01:47 GMT Subject: Creating a module that uses itself References: <2yfl8.113994$nl1.19520473@typhoon.nyroc.rr.com> Message-ID: Oops. I accidentally tried to create an Image() object instead of a Photo() object. The interesting thing about this is that there *is no* Image object. (Sorry, all.) It was just syntax error disguised as a logic error. Back to sleep, all of you. Looks like I could use some myself. Thanks, anyway.... -- Asheesh. On Mon, 18 Mar 2002 01:47:51 -0500, Greg Krohn wrote: > "Asheesh Laroia" wrote in message > news:2yfl8.113994$nl1.19520473 at typhoon.nyroc.rr.com... >> I'm writing a PageMaker-to-specialized-HTML module (henceforth >> "pm2html"). In the module, I define the classes Article, Headline, and >> Photo, among others. >> >> In the Article class, I want to have a Headline object. Is this >> possible? Right now, ActivePython's PythonWin spits a syntax error at >> me because the Headline class is not defined. > > You should post your code and the actual error traceback. What you're > describing should work -- at least they way that you've described it. > Could there be a typo in your code? > > This works for me: > > class Article: > def __init__(self): > self.headline = Headline() > > class Headline: > pass > > class Photo: > pass > > a = Article() > > > > greg From eppstein at ics.uci.edu Fri Mar 22 00:28:15 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 21 Mar 2002 21:28:15 -0800 Subject: How Can I Determine the Operating System with Python? References: Message-ID: In article , Gerhard H?ring wrote: > And nmap isn't a standard Unix tool either. On Unix, the only thing you can > depend on is the presence of "uname", which exactly the right tool for the > task. Only I don't know of an "uname" equivalent for Windows or Mac. uname works just fine on Mac OS X. It returns "Darwin". Don't know of an equivalent for non-Unix versions of Mac OS, though. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From amylang at zedat.fu-berlin.de Sun Mar 31 14:24:19 2002 From: amylang at zedat.fu-berlin.de (amy) Date: Sun, 31 Mar 2002 21:24:19 +0200 Subject: selecting files from MySQL Message-ID: hello python-knowing, can somebody help me to solve a little problem in a script, sc selecting files from a mysql database? so far, it doesn't want to work: if fileid['translation'] == 'none': actie = suchen fileid == 'none' elif fileid['translation'] == 'de-orig': actie = suchen fileid == 'de-orig' elif fileid['translation'] == 'nl-orig': actie = suchen fileid == 'nl-orig' elif fileid['translation'] == 'no-orig': actie = suchen fileid == 'no-orig' else: search = opt['such'] thanks a lot, if it's possible amy From philh at comuno.freeserve.co.uk Sun Mar 31 19:47:12 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 1 Apr 2002 01:47:12 +0100 Subject: PEP 285: Adding a bool type References: <3CA75DAC.17647CEA@alcyone.com> Message-ID: On Sun, 31 Mar 2002 16:30:31 -0500, John Roth wrote: > >The trouble is that 'bool' as a data type **isn't** the standard >name from mathematics. Nor are int, float, dictionary, etc. > Correct usage is something like: >"Boolean logic manipulates truth values." That is, the data >type is a truth value (see, for example, "truth table".) The usage >in programming languages is simply incorrect linguistically. No, it is just different from the maths usage. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From pearu at cens.ioc.ee Sat Mar 23 13:33:47 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sat, 23 Mar 2002 20:33:47 +0200 Subject: mutlifile inheritance problem simplified In-Reply-To: <3C9CAFD2.13FE372D@hotmail.com> References: <9896e047.0203211303.741f695a@posting.google.com> <3C9BAB77.B4E17C65@hotmail.com> <3C9C0B45.E3C51B0C@hotmail.com> <3C9CAFD2.13FE372D@hotmail.com> Message-ID: On Sat, 23 Mar 2002, Marc wrote: > I'm wondering whether or not this is a bug, which I would report, or > whether I'm doing something incorrectly. Though Python documentation on reload function warns about several cavecats, I still could not explain the exceptions you report. But I bet that this just is another undocumented cavecat with using reload (see below). So, I think you should make a bug report. After playing with your example, I concluded in the following rule (it is possible that Python docs has relevant remarks, I just have not found the right place yet): If you reload a module, then you must reload all other modules that use this module (usage in the sense that they define classes derived from a class defined in the first module). The order of reloading matters. If you follow this rule, you'll have no trouble. Your example obviously fails to satisfy this rule because reload(c01) forces reload(a01) but then also b01 must be reloaded. If you then reload(b01), reload(a01) is forced but then also c01 must be reloaded. And so on.. (in Estonia we would say "nokk lahti, saba kinni, saba lahti, nokk kinni, nokk lahti, saba kinni, ..."). For a fix 1) remove reload(a01) statements in files b01.py and c01.py 2) if you modify a01.py, then execute reload(a01) reload(b01) reload(c01) (in that order) 3) if you modify b01.py, then execute reload(b01) (no need to reload a01 or c01) 4) if you modify c01.py, then execute reload(c01) (no need to reload a01 or b01) Regards, Pearu From pedronis at bluewin.ch Tue Mar 12 22:01:23 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 13 Mar 2002 04:01:23 +0100 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> Message-ID: <3c8ec411$1_5@news.bluewin.ch> David Ascher wrote in message mailman.1015979203.27977.python-list at python.org... > > I agree w/ Cameron's response. The article is remarkably technical for > a trade press article. If you want _technical_ questions, then I > suggest you ask Mark (politely, preferably -- accusing Mark of doing PR > is not going to get you anywhere =). > I find this comments quite out of target. regards. From loewis at informatik.hu-berlin.de Tue Mar 5 10:30:41 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 05 Mar 2002 16:30:41 +0100 Subject: ICU wrapper for Python? References: Message-ID: Fredrik Juhlin writes: > However, I'm relying on the fact that since Python uses UCS-2 and ICU uses > UTF-16 for their respective internal format, any Python unicode string can > be used as an ICU unicode string. So for the collation I don't need to do > any conversion between the two. To expose the codecs, one would have to > convert the resulting strings from UTF-16 to UCS-2. I'm a bit slow here: Why do you think Python uses UCS-2 and not (simultaneously) UTF-16? What kind of conversion would you perform? > If you're interested in what I have so far, I'll stick it on a web server > for downloading. That'll have to wait until tonight though, since my > latest version is at home. That would be nice. If you don't mind, I'd also incorporate it into the CVS of the i18n SIG (python-codecs.sf.net - it's a bit more general than just codecs, hope that doesn't cause problems). Regards, Martin From upersad at tstt.net.tt Fri Mar 29 20:39:14 2002 From: upersad at tstt.net.tt (Umesh Persad) Date: Fri, 29 Mar 2002 17:39:14 -0800 Subject: GUI programming Message-ID: <001401c1d78b$b4264f00$bcc75ed1@umesh> Hi, I am doing an assignment using python - making a turkish checkers game. --------------------------------------- | | | | | | | checker board area | --------------------------------------- | | | text fileds and buttons area | | | --------------------------------------- I wanted to have a user interface where I can draw the game board as well as take in text input below the board with some text felds and buttons. I see there are many GUI toolkits available. I am wondering which one should I use (tkinter, wxpython?) that will be simple enough to get me up and running qiuckly. Also are there any examples that I can look at? Also, if any one is familiar with Tkinter, how do I put up a window with a size that I want? Also how do I place a canvas on the window at a predefined size? Thanks a lot, Umesh From narnett at mccmedia.com Tue Mar 26 18:15:05 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Tue, 26 Mar 2002 15:15:05 -0800 Subject: Logging tracebacks to MySQL (was RE: hang in urllib.read()?) In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Daniel Ortmann [snip] > Could this information help? > > The web page, "Known bugs in Python 2.2", says: > > "The ftplib module's FTP class was supposed to default to paassive > mode. Unfortunately it doesn't. This means that urllib.urlopen() > doesn't work from inside most firewalls. If you have this problem, > delete or comment out line 117, 'self.passiveserver = 0', from file > ftplib.py". Nope, doesn't apply, but thanks. At this point, my robot is being nicely stable, but now I'm starting to think that the real problem was time-outs, but I sure don't see why they would last for hours. Aahz's suggestion of using timeoutsocket was right on the mark. I am definitely seeing timeouts now, which are recovering nicely by simply starting over with urlopen. I was confused by the fact that I thought that urlopen() establishes the connection, but it now seems clear to me that it starts with read(). And after a fairly hideous time figuring out how to come up with an appropriate error message and escape it for MySQL, timeouts are now even being logged into a table. If anyone has an example of getting a full traceback into a MySQL field, I'd be grateful to see it. What seemingly should work seems to somehow recurse a few times, so that backslashes and such get repeatedly escaped... at least in all the ways I could see to use the traceback module. I gave up and up and I'm using sys.exc_info()[:2] instead, which is probably sufficient information. Nick From aahz at panix.com Sun Mar 3 12:44:27 2002 From: aahz at panix.com (Aahz Maruch) Date: 3 Mar 2002 09:44:27 -0800 Subject: Q: PEP progressions, and Rational type in particular? References: Message-ID: In article , Brent Burton wrote: > >In the case of Rational types, Python 2.3 and 2.4 are referred to >for __future__ and warning-by-default operation. Does this mean >2.2 has no rational type at all? That's correct. Unfortunately, there's no clear single roadmap that explains what features are available in which version, but a good approximation can be obtained by reading Andrew Kuchling's What's New links at http://www.amk.ca/python/ -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From greg at cosc.canterbury.ac.nz Mon Mar 4 23:22:41 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 05 Mar 2002 17:22:41 +1300 Subject: Status of PEP's? References: Message-ID: <3C844811.AEC974E3@cosc.canterbury.ac.nz> Fernando P?rez wrote: > > Let me try to organize my thoughts a bit on why I dislike this PEP so > seriously. I have no problem with the "everything is a first-class object" > philosophy in Python. But I feel that precisely what this pep introduces is a > bad usage (IMO) of these ideas. I'd also like to add this: It's been suggested that this proposal doesn't ask us to think of integers as being sequences, only as having sequences implicitly associated with them. But I don't agree. While it's certainly possible to give any object an __iter__ method that does anything you want, it doesn't mean you should! To me, the __iter__ protocol is intended to be used when an object can reasonably be thought of as a sequence. That's actually *being* a sequence, not just "associated" with a sequence in some way. Using the __iter__ protocol in the way suggested by this PEP is abusing it, in my opinion. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From a at yahoo.com Mon Mar 4 19:16:57 2002 From: a at yahoo.com (CSJedi) Date: Tue, 05 Mar 2002 00:16:57 GMT Subject: Python standards Message-ID: Can someone tell me if Python has proprietary or consensus standards such as ANSI? From rupert.kolb at med.uni-tuebingen.de Mon Mar 11 07:39:07 2002 From: rupert.kolb at med.uni-tuebingen.de (Rupert Kolb) Date: Mon, 11 Mar 2002 13:39:07 +0100 Subject: Homepage of Gadfly not available? References: <3C8C8DA1.5040901@med.uni-tuebingen.de> <20020311140817.L25769@phd.pp.ru> Message-ID: <3C8CA56B.7050505@med.uni-tuebingen.de> Oleg Broytmann wrote: > On Mon, Mar 11, 2002 at 11:57:37AM +0100, Rupert Kolb wrote: > >>for weeks, I'm trying to reach the home page of the Gadfly DB. >> http://www.chordate.com/gadfly.html doesn't work. >>Is this my fault? >> > > No, it is down for some time, and probably forever. The original author > stopped working on it. > Then the next questions: Are the sources available somewhere? Is there a new home page for Gadfly? Is there anybody who will maintain such a page? As far as I can remember there is some software, which needs gadfly. -- Rupert Kolb From matkin at iar.se Mon Mar 18 07:16:18 2002 From: matkin at iar.se (Mats Kindahl) Date: 18 Mar 2002 13:16:18 +0100 Subject: YANRQ (yet another regex question) References: <4f5k8.435$zT5.13755@news.itd.umich.edu> Message-ID: Michael George Lerner writes: > Mats Kindahl wrote: > > Mats Kindahl writes: > > >> Michael George Lerner writes: > >> > >> > I wanted to match this: > >> > > >> > (?Pfoo | foo | foo | foo | foo) > >> > > > > > >> That's what I get for not reading the manual... :/ > > > > > > > r = re.compile(r'(?P(?=.{7}$) *foo *$)') > > ^ ^ > > ! ! > > notice missing dollars --+--------+ > > Cool! .. but still not quite what I wanted .. > > And that's what *I* get for snipping information out when I post a > followup :/. > > In my original post, I mentioned that I wanted something like > r'(?Pstart)(?P foo )(?Pend)' i.e. other patterns > on the same line before and after foo. I might be misunderstanding something, but can't you just do... r = re.compile(r'(?Pstart)' + r'(?P(?=.{7}end) *foo *)' + r'(?Pend)') ...but now it's starting to be complicated. (Maybe you should use the VERBOSE flag when compiling the pattern.) Notice that you have to insert the end marker/pattern 'end' both inside the lookahead pattern and after the actual match pattern. Observe that for this to work, the 'start' pattern may not be a legal prefix to the 'foo' pattern (this is not formally correct, but I believe you get the meaning) nor may the 'end' pattern may not be a legal suffix of the 'foo' pattern. Good luck! -- Mats Kindahl, IAR Systems, Sweden Any opinions expressed are my own, not my company's. From fdrake at acm.org Sat Mar 23 17:24:21 2002 From: fdrake at acm.org (Fred L. Drake) Date: Sat, 23 Mar 2002 17:24:21 -0500 (EST) Subject: [development doc updates] Message-ID: <20020323222421.8D11C28696@beowolf.fdrake.net> The development version of the documentation has been updated: http://python.sourceforge.net/csstest-docs/ This is a test version of some style changes. The changes are localized to the navigation areas (I hope!), and probably only work for the browsers with the most-compliant CSS2 implementations. I've tested this with Mozilla 0.9.9 and MSIE 6 -- and it only worked in Mozilla. This isn't going to be usable until more browsers support the CSS needed to make this work, but I've never seen this done without frames before now (though I've played with the idea several times over the last couple of years). If you can't tell what the changes are, visit a page that needs to be scrolled to see the whole thing, and try scrolling it! Comments are welcome; send to python-docs at python.org. From duncan at NOSPAMrcp.co.uk Mon Mar 4 07:45:31 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 4 Mar 2002 12:45:31 +0000 (UTC) Subject: Gentle reminder for Python UK Conference, April 4 & 5. References: <1015238517.16564.0.nnrp-01.c1c3e191@news.demon.co.uk> Message-ID: "Paul Brian" wrote in news:1015238517.16564.0.nnrp- 01.c1c3e191 at news.demon.co.uk: > You even get access to the full ACCU conference, > attended by luminaries such as Bjarne Stroustrup. > So does anyone think we can convert Bjarne Stroustrup to evangelising Python instead of C++? Any chance we can change the ACCU into the APyCCU? Seriously, I enjoyed last year's conference. Python programmers may even want to go to the other days: I see that at least one Python talk has managed to creep into the Saturday. -- 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 jeff at ccvcorp.com Fri Mar 22 13:38:22 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 10:38:22 -0800 Subject: Begginers Guide - Exrcise. Help me, plz! References: Message-ID: <3C9B7A1E.451453BA@ccvcorp.com> Jim Dennis wrote: > Shouldn't all these (helpful) examples be using raw_input() rather > than input(). Do we really want the new user to be implicitly and > blindly using eval(raw_input())? Yes, they should. :) The calls to input() should, in this case, all be replaced by int(raw_input()), and optionally wrapped in a try/except and while loop, so that the program can prompt again if a non-numeric value is given. I almost mentioned this in my earlier response, but decided not to overly confuse the O.P. -- this essentially doubles the code size. while sum < sum_stop: num = None while num is None: try: num = int(raw_input("Please enter the number:")) except ValueError: print "That's not a number. Try again!" sum = sum + num # could also be sum += num print "The sum is", sum print "and it is > 100" Alternatively, instead of setting num to None and watching for that to change, we could use a 'while 1: try: ... except: ... else: break' structure. Jeff Shannon Technician/Programmer Credit International From joonas at olen.to Sun Mar 3 15:00:30 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Sun, 03 Mar 2002 22:00:30 +0200 Subject: Twain Scanners and some other questions References: <0Xng8.33257$Ns4.1344751@news2.tin.it> Message-ID: <3C8280DE.6E67A05C@olen.to> dix wrote: > I would like also your advice to find a solution to convert these images in > Acrobat PDF format: for the moment I just tought at the possibility to > automate the COM interface of Acrobat Distiller from Python. Any other idea? ReportLab should do the job. http://www.reportlab.com/ From pobrien at orbtech.com Sat Mar 30 09:13:26 2002 From: pobrien at orbtech.com (Patrick K. O'Brien) Date: Sat, 30 Mar 2002 08:13:26 -0600 Subject: [Python-Dev] RE: PEP 285: Adding a bool type In-Reply-To: Message-ID: [Tim Peters] > > [Christian Tanzer] > > ... > > How will bool influence '__nonzero__'? Currently, Python insists that > > '__nonzero__ should return an int'. Will this be changed to 'should > > return a bool'? > > I hope so. > > > As that would break existing code, I hope not. > > No, "should" != "must". Guido won't call code that returns an int here > broken, although he might call it deprecated, and leave you wondering when > the hammer will drop . What is the likelihood that __nonzero__ could be renamed (at some point in the future) to something a bit more intuitive, like __bool__? I know there would be a lot of user code to change, but assuming one day the hammer will drop and everyone's __nonzero__ will have to change to return a bool, I wouldn't mind seeing the method renamed as well. Or is this a lost cause at this point? --- Patrick K. O'Brien Orbtech From skip at pobox.com Wed Mar 27 17:43:25 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Mar 2002 16:43:25 -0600 Subject: Very small zlib/svg problem In-Reply-To: References: Message-ID: <15522.19213.655102.927935@12-248-41-177.client.attbi.com> Fedor> I use the zlib library to compress the svg file. Fedor> The problem is that when I try to view the SVGZ file with adobe SVG viewer Fedor> 3.0 or with the Batik SVG browser that it doesn't render and is Fedor> not able to read the SVGZ file as SVG. I think you want to use the gzip module. Something like import gzip f = gzip.open("c:/test.svgz", "w") f.write(file('c:/test.svg').read()) f.close() -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From grante at visi.com Fri Mar 15 09:53:22 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Mar 2002 14:53:22 GMT Subject: socket References: Message-ID: In article , Billy Ng wrote: > I am trying to write a python program to verify the email > address. What you're trying to do is pointless. Whether it's evil or not, I don't know, but one is suspicious. Most servers either refuse the verify command or always return affirmative. Many modern servers will accept RCPT for invalid addresses also. -- Grant Edwards grante Yow! Did we bring enough at BEEF JERKY? visi.com From owen at xastrox.xwashingtonx.edu.invalid Fri Mar 8 16:21:23 2002 From: owen at xastrox.xwashingtonx.edu.invalid (Russell E. Owen) Date: Fri, 08 Mar 2002 13:21:23 -0800 Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: In article <1f5252d4.0203080721.3bfc5c14 at posting.google.com>, nbecker at fred.net (N Becker) wrote: >Back in 1999, I asked "where is quote?". I was looking for >a way to quote a function (delay evaluation). > >I wonder if there is anything new. It looks to me that the >best answer is to use lambda. There are two aspects to this sort of function, data you want to set up in advance and possibly data you want the function to see later but that you don't want to pass as an argument. For the latter, you can take advantage of Python's new scoping rules. They have some quirks, but will probably do the job. For setting up parameters in advance, there are several ways. My favorite is to use a callable class, and here is a lovely general one posted by Eric Brunel (if Eric is reading this: did you write it, if not, do you know who did?): class GenericCallback: def __init__(self, callback, *firstArgs): self.__callback = callback self.__firstArgs = firstArgs def __call__(self, *lastArgs): apply(self.__callback, self.__firstArgs + lastArgs) Certainly you can use lambdas, specifying default arguments for data you are evaluating at function creation time. Personally, I dislike lambdas; defining a named function works just as well, is usually easier to read, and allows more flexibility about what the function can do. Still, in either case those default arguments are somewhat ugly. It's hard to beat GenericCallback for clarity and simplicity. -- Russell -- Return owen address astro garbled washington in header edu From philh at comuno.freeserve.co.uk Wed Mar 6 19:49:14 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 7 Mar 2002 00:49:14 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Thu, 7 Mar 2002 00:28:30 +0000, phil hunt wrote: >On Wed, 06 Mar 2002 09:08:57 -0800 (PST), Sean 'Shaleh' Perry wrote: >>I am a little confused. >> >>Your proposal starts with the claim that people are looking for a natural way >>to loop over a range of integers. > >How about: > > for i = 1 to 10: > >or > > for i is 1 to 10: > >I think these are both equally good and both much preferable over >the horrible > > for 1 <= i <= 10: > >which I can only assume is someone's sick idea of a joke. > >This syntax could easily be extended, to allow a step other than 1: > > for i = 1 to 10 step 3: And extended in other ways, to make it similar to how range() and xrange() work. for i = 1 tobefore 10: print i, would print 1 2 3 4 5 6 7 8 9 for i = to 5: print i, => 0 1 2 3 4 5 for i = tobefore 5: print i, => 0 1 2 3 4 for 5: print "x", => x x x x x The extra syntax I am proposing is: for_stmt : for_line ":" suite ["else" ":" site] for_line : traditional_for_line /* as before */ | to_for_line | repeat_for_line to_for_line : "for" target "=" to_expression to_expression : [expression] to_clause [step_clause] to_clause : "to" expression | "tobefore" expression step_clause : "step" expression repeat_for_line : "for" expression -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From mzou at bu.edu Sun Mar 24 22:59:49 2002 From: mzou at bu.edu (ricky) Date: Sun, 24 Mar 2002 22:59:49 -0500 Subject: question: python and UDP References: <3C9E9CFD.AC6A149B@engcorp.com> Message-ID: how would i use the struct module? "Peter Hansen" wrote in message news:3C9E9CFD.AC6A149B at engcorp.com... > ricky wrote: > > > > I am trying to write a python program to connect to a proxy server which > > takes the following header: > > however, the proxy server doesn't seem to understand the header i sent to > > it. > [...] > > My question is how do i format the header so that proxy server would > > understand the information I send to it. > [...] > > Are you looking for the 'struct' module? That should be enough to > produce the header format you need. > > -Peter From google at palydon.demon.co.uk Tue Mar 12 03:44:04 2002 From: google at palydon.demon.co.uk (Paul Lydon) Date: 12 Mar 2002 00:44:04 -0800 Subject: Redirecting output in Windows NT Message-ID: <96e9dee5.0203120044.33a1e19c@posting.google.com> Running Python 2.2 on Windows NT 4 Workstation. Suppose I have a Python program named 'splat.py' consisting of: "print 'splat'". If I type 'splat' and hit 'Enter', NT knows that it must run the Python interpretor and I see 'splat' on the screen. If I redirect the output to a file: 'splat > splat.txt', the resulting file is 0 bytes long and empty. If I run the same program directly by typing 'python splat.py', again I see 'splat' on the screen and when the output is redirected 'python splat.py > splat.txt' I get a file containing the string 'splat' (as you would expect). Any ideas why the output redirection doesn't work in the first place? Paul Lydon From donn at drizzle.com Thu Mar 7 01:46:30 2002 From: donn at drizzle.com (Donn Cave) Date: Thu, 07 Mar 2002 06:46:30 -0000 Subject: Getting stdout and stderr from popen References: Message-ID: <1015483588.481084@yasure> Quoth Stefan Heimann : | Donn Cave wrote:: ... | I am on unix but I want it to work on windows, too. | |> ... For example, suppose you record the output of "make", which |> will be both output and error streams. If you read them separately, |> you won't be able to tell which compiler errors belong to which |> make commands. | | That's what I need! Is it really so complicated? I think it should be | common that someone needs to read stdout and stderr ordered by time. I don't know. You probably know more about Windows than I do. But yes, I wouldn't be surprised if it's impossible to get stdout and stderr in the same pipe. But maybe our UNIX background leads us to make this a more significant problem than it is. If you haven't already checked this, run "cvs status" and whatever else you're interested in, and make sure you really have a problem. Once upon a time, I proposed that, now that you can write "print >> sys.stderr", most of the print commands in the Python library should probably be changed to do that, since they're mostly diagnostic in nature. That sounds obvious, but to my surprise a couple of people here who use Windows a lot but are otherwise pretty computer literate were very negative about it - apparently, stderr is generally awkward and unpleasant on Windows. At the same time, some of the UNIX facilities for dealing with separate I/O streams are obviously missing. So perhaps on Windows one just doesn't write to stderr all that often, as there's no point in the distinction. Donn Cave, donn at drizzle.com From phd at phd.pp.ru Thu Mar 28 10:05:05 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 28 Mar 2002 18:05:05 +0300 Subject: Very small zlib/svg problem In-Reply-To: <15523.12185.915711.200047@12-248-41-177.client.attbi.com>; from skip@pobox.com on Thu, Mar 28, 2002 at 08:58:33AM -0600 References: <15522.19213.655102.927935@12-248-41-177.client.attbi.com> <20020328153415.D11101@phd.pp.ru> <15523.12185.915711.200047@12-248-41-177.client.attbi.com> Message-ID: <20020328180505.L11101@phd.pp.ru> On Thu, Mar 28, 2002 at 08:58:33AM -0600, Skip Montanaro wrote: > Oleg wrote: > f = gzip.open("c:/test.svgz", "wb") > > Patch submitted to force 'b'. Feel free to check it out and comment. In Thank you. > particular, since I don't run on Windows I can't really test it out where it > matters. I don't run Windows, too :) Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From grante at visi.com Mon Mar 11 22:35:54 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Mar 2002 03:35:54 GMT Subject: newbie-ish question on exec statement References: Message-ID: In article , Gabe Newcomb wrote: > Hi all: > I'd appreciate any comments people might have on the limitations > of using exec. Specifically, what I want to do is build function names > dynamically and call them (don't ask why). http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.103.htp > def my_function(arg1, arg2="", arg3=""): > blah blah > > exec "t = my_" + "function('\\\\machine\\share')" It might be easier to debug if you use some of Python's introspection features: destName = "t" funcName = "my_" + "function" f = locals()["my_function"] locals()[destName] = f('\\\\machine\\share') -- Grant Edwards grante Yow! I'm rated PG-34!! at visi.com From tdelaney at avaya.com Sun Mar 24 23:05:42 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 25 Mar 2002 15:05:42 +1100 Subject: 2.2 open Message-ID: > From: Greg Ewing [mailto:greg at cosc.canterbury.ac.nz] > > Robin Becker wrote: > > > > So the question now is, how do I tell if __import__ is the > built in one > > even if the import system is not fully initialized. > > You could compare its type with what you really > should have been comparing it with in the > first place: > > import types > if type(__import__) == types.BuiltinFunctionType: > ... Except that this will only tell you that it's of the same type as the original __import__ - someone still may have replaced the builtin __import__ before you get a go at it. In general, it shouldn't matter whether it is the builtin __import__ or not - why do you need to know? If you wish to replace it with your own version, you should just capture the original version and replace it with your own. To do this in a thread-safe manner you should probably use the canonical "swap" idiom ... import __builtin__ def _my_import (name, globals, locals, fromlist): pass _orig_import, __builtin__.__import__ = __builtin__.__import__, _my_import print _orig_import print __builtin__.__import__ Tim Delaney From tdelaney at avaya.com Mon Mar 25 17:51:36 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 26 Mar 2002 09:51:36 +1100 Subject: files and reading from them Message-ID: > From: Sheila King [mailto:usenet at thinkspot.net] > > Technically, you can accomplish this by > > x = eval(file.readline()) > > if you know for a fact that your line of text from the file will be a > correctly formatted, string representation of a dictionary, > and that you can depend on that 100%, no ifs, ands or buts. Also, only if for each item in the dictionary (key and value) eval(repr(item)) returns an object equivalent to item. For builtins, this is the case - for user-defined classes it often (usually even) isn't. Tim Delaney From gmuller at worldonline.nl Wed Mar 20 13:19:51 2002 From: gmuller at worldonline.nl (GerritM) Date: Wed, 20 Mar 2002 19:19:51 +0100 Subject: Python vs. C/C++/Java: quantitative data ? References: <3c74a81c$0$141$bb624dac@diablo.uninet.ee> <3C74DD65.3060000@thinkware.se> Message-ID: <..snip...> > > For comparison of utilization level still other types of programs are > > needed. In this type of comparison I expect even more discussion on the > > "rules"; Are you allowed to use the plain language only, or also the > > batteries which are included or everything on CPAN like archives; Are > > packages which are used included in the line count; etcetera. > > I agree. Even things like a strong, helpful community for support are > important for being productive. Python certainly has that. But I'm not > sure how to measure that fairly :-) > > cheers, > doug > -- > http://www.bagley.org/~doug/contact.shtml In a recent thread (see below) the wc utility was shown both in c and python. These utilities are relatively well defined and one step larger than the current shootout programs. They might be useful for benchmarking purposes. regards Gerrit www.extra.research.philips.com/natlab/sysarch ---begin included message--- Re: Book Draft Available: Text Processing in Python From: jimd at vega.starshine.org (Jim Dennis) In article , David Mertz, Ph.D. wrote: > Pythonistas: > As some folks know, I am working on a book called _Text Processing in > Python_. With the gracious permission of my publisher, Addison Wesley, > I am hereby making in-progress drafts of the book available to the > Python community. It's about half done right now, but that will > increase over time. > Take a look at the book URL: http://gnosis.cx/TPiP/ > I welcome any comments or feedback the Python community has about my > book. > Yours, David... I was glancing through it and stopped when I read your word counter (with no support for the command line options). I just had to do one to emulate the GNU wc utility as closely as I can in one quick session. Below is a somewhat more faithful rendering of the GNU wc command. Although it's about 120 lines long, almost forty of those are blank lines, docstrings, or comments. In most cases it gives output that is identical to GNU wc (including the character spacing). The only discrepancies I've seen are in the -L (--max-line-length) calculation (particularly on binary files). It's pedagogical value is more in the use of the getopts module and possibly in file iteration (for line in file: ...). The text processing being done here is trivial. There's also a little bit of exception handling, and a minimal amount of error avoidance --- since Python will allow me to open a directory but will complain if I try to read lines therefrom). It is mildly interesting that this Python implementation of wc is only about a third the length of the GNU version from the text utils package (wc.c is 371 lines). Actually counting words and characters the Python version is only about half the length. (Glancing at the sources I see that I missed support for the POSIXLY_CORRECT environment variable -- which modifies, or uglifies if you prefer, the output format; I could add that in a few lines). David, you're welcome to use this script as an example. Perhaps you could list this as an example of how 14 lines of simple, focused code grows to 140 lines by the time we add option handling, help and error messages, exception handling and error avoidance, and all that other stuff. (If you really want to scare people you could include the wc.c from the GNU textutils package by way of comparison). #!/usr/bin/env python2.2 import sys, os """ wc: Emulate GNU wc (word count) """ help = '''Usage: wc [OPTION]... [FILE]... Print line, word, and byte counts for each FILE, and a total line if more than one FILE is specified. With no FILE, or when FILE is -, read standard input. -c, --bytes, --chars print the byte counts -l, --lines print the newline counts -L, --max-line-length print the length of the longest line -w, --words print the word counts --help display this help and exit --version output version information and exit Report bugs to ''' version = """Python word count: wc(1) emulation by James T. Dennis version 0.1""" def options(): """Process command line options""" import getopt short = "clLw" long = ('bytes', 'chars', 'lines', 'max-line-length', 'words', 'help', 'version') try: opts, args = getopt.getopt(sys.argv[1:], short, long) except getopt.GetoptError,err: msg = "wc: invalid option \nTry `wc --help' for more information." print >> sys.stderr, sys.argv[0], err print >> sys.stderr, msg sys.exit(1) return opts, args def count(f=None): """Count and return words, chars, lines, and maxlength""" # We count them all, since that's and much easier than alot of # conditional logic to decide what to count. # We return it all, and main() can decide what to return. lines = words = chars = maxline = 0 if f == None: file = sys.stdin else: if os.path.isdir(f): print >> sys.stderr, "wc: %s: Is a directory" % f return lines, words, chars, maxline try: file = open(f,'r') except IOError: print >> sys.stderr, "Error opening:", f return lines, words, chars, maxline # If we get this far, we can count stuff for line in file: length = len(line) lines += 1 chars += length words += len(line.split()) if length - 1 > maxline: maxline = length - 1 # GNU wc doesn't count line terminator in maxlength? # +++ binary files anve much different line length semantics! return lines, words, chars, maxline def printcount(flags, totals, filename=None): """Print counts for each file and for the grand totals takes two 4-tuples, the flags for which items to print, and the total lines, words, characters, and max-line-length and an optional filename""" if filename == None: filename = "" dolines, dochars, dowords, domaxln = flags l, w, c, m = totals print "", # GNU wc prints one leading space? if dolines: print "%6d" % l, if dowords: print "%7d" % w, if dochars: print "%7d" % c, if domaxln: print "%7d" % m, print filename if __name__ == "__main__": opts, args = options() dolines = dochars = dowords = domaxln = 0 for opt,arg in opts: if opt == '--help': print help sys.exit() elif opt == '--version': print version sys.exit() elif opt in ('-l', '--lines'): dolines = 1 elif opt in ('-c', '--chars', '--bytes'): dochars = 1 elif opt in ('-w', '--words'): dowords = 1 elif opt in ('-L', '--max-line-length'): domaxln = 1 if dolines + dochars + dowords + domaxln == 0: # None specified so default is to do lines, chars, and words dolines = dochars = dowords = 1 # Else we do only the ones that are specified # GNU wc always prints the stats in the same order, regardless # of the order of the options/switches. printflags = (dolines, dochars, dowords, domaxln) if not args: # No files named: so just do stdin # No grand totals. and no filename l, w, c, m = count() printcount (printflags, (l,w,c,m)) else: # Else we do each file and keep track of grand totals all_lines = all_words = all_chars = longest_line = 0 files_processed = 0 for i in args: if i == '-': l, w, c, m = count() else: l, w, c, m = count(i) all_lines += l all_words += w all_chars += c if m > longest_line: longest_line = m printcount (printflags, (l,w,c,m), i) files_processed += 1 if files_processed > 1: # Print totals totals = (all_lines, all_words, all_chars, longest_line) printcount (printflags, totals, "total") ---end included message--- From precision at devrandom.net Fri Mar 15 20:47:37 2002 From: precision at devrandom.net (Uriah Welcome) Date: 15 Mar 2002 17:47:37 -0800 Subject: socket References: Message-ID: <65c17385.0203151747.2414a312@posting.google.com> Cliff Wells wrote in message news:... > On Fri, 15 Mar 2002 17:46:01 GMT > Billy Ng wrote: > > > Nothing evil here. I have 2 reasons why I would do this program. Firs, > it > > is my TCP/IP concept class's project. Basically, I want to try what the > > book tells in to code, but I notice it does not work the way it says in > so > > many commercial SMTP servers. Second, I have been unemployed for about 4 > > months. My friend's company needs a program to verify the users who > > registered to their service. They found out many registered users were > > using fake addresses. I just want to try this program to see if I will > get > > a job there. That's all! I really do appreciate if you would provide > any > > info for me to complete this project. > > Why not do like many others do: send a confirmation email to the address > and require a reply from that address to complete registration. Well.. the way that Exim and other MTAs do address verification is to fake a bounce to that user ala... mail from: <> rcpt to: And check for a result. You said you already thought about this, but besides a confirmation email this is probably the best way. Since if they can't recieve bounces they're breaking RFC anyways. Unfortunately people like yahoo.com and others return okay for _any_ address. In short there is no fool proof way to do this. From dragon at china.org Tue Mar 26 00:25:28 2002 From: dragon at china.org (Qiang.JL) Date: Tue, 26 Mar 2002 05:25:28 GMT Subject: beginner question Message-ID: for this line: >>> g=(lambda x: ' '.join(x.split())) or (lambda y: 'second') now by calling g(str(something)) make sure i always pass a string to the function(ignore exception if improper stuff in str). I want to know what parameter i can pass to the lambda function so that the first condition false then second condition get executed? or as long as i pass a string,it's always true for the first condition? Q. From usenet at thinkspot.net Sat Mar 16 16:10:52 2002 From: usenet at thinkspot.net (Sheila King) Date: Sat, 16 Mar 2002 13:10:52 -0800 Subject: Begginers Guide - Exrcise. Help me, plz! References: Message-ID: On Sat, 16 Mar 2002 23:45:30 +0300, "Jeffrey-man" wrote in comp.lang.python in article : > > sum_stop = 100 > num = input("Please enter the number: ") > > for sum in range(num+num,sum_stop): > print "Now the sum is", num+num > sleep(1) > > print "The sum is >/= 100!" You need some type of loop. Also, you need to initialize your sum. sum_stop = 100 sum = 0 while (sum < sum_stop): < your code for getting the input > < and incrementing the sum > < goes here > print "The sum is ", sum HTH, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From bokr at oz.net Wed Mar 13 23:01:20 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Mar 2002 04:01:20 GMT Subject: [ANN] istring 1.0.1 released; announce list created References: Message-ID: On Wed, 13 Mar 2002 15:51:43 -0700, "Bjorn Pettersen" wrote: >> From: Bengt Richter [mailto:bokr at oz.net]=20 [... something to make Andreas' code deliver escaped quotes ...] [...] >> AND name =3D 'O\'Hara' > >Except that's not how SQL is quoted (It should have been 'O''Hara'). >Besides, anyone not using bound variables must be crazy > The escaping is Ok either way for MySQL, IIRC ;-) The class is kind of funny the way it wound up (irrelevant wrapper for a variable in a loop). I was thinking something bigger, but then I wanted a quick and dirty demo to make the given formatting code work unchanged. But if there's a place for config data that connects to a particular database engine, it could probably also have the name of a module with suitable encoding functions? Or is the problem connecting to a totally unknown end database engine type? ODBC? Regards, Bengt Richter From jkraska at san.rr.com Mon Mar 25 21:35:04 2002 From: jkraska at san.rr.com (Courageous) Date: Tue, 26 Mar 2002 02:35:04 GMT Subject: Indentation problem References: Message-ID: >I've some problem with identing code. I'm allright with the example. >But, I think it's important to have an "end" building block like "!:" >What do you think about that? I recommend you congregate with link-minded folks and create your _own_ programming language. What you've just described simply isn't what Python is all about. >Why not Python? Because Guido didn't want to and developed a following that agreed with him. What resulted is something that the following agrees should be the way it is. Ergo, it's not there because it's not, and we don't like it. C// From david.abrahams at rcn.com Sat Mar 2 15:33:40 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sat, 2 Mar 2002 15:33:40 -0500 Subject: C/C++ to Python translater References: <5e8bd451.0203011049.5d12d3a2@posting.google.com> <3C811653.871C5BEF@tds.net> Message-ID: "Edward K. Ream" wrote in message news:3C811653.871C5BEF at tds.net... > leo.py contains a script called c2py.py that I have used to translate > all my C++ code to Python. It does about 80% of the work and is mostly > intended to be run from inside Leo. IIRC there is another entry in > c2py.py script to translate "exterior" files and this can be run from > idle, say. Munging source to Python is actually remarkably easy to do. > > You can download leo.py v1.0 at: > > http://sourceforge.net/project/showfiles.php?group_id=3458 > > One of these days I'll get around to cleaning it up and making a proper > distribution of it. Let me know if you have problems with c2py: it will > help me clean up the rough edges. Biggest problem I'm having is that I can't find it. http://prdownloads.sourceforge.net/leo/leo-1.0.zip doesn't contain a file called c2py.py. Did you have something else in mind? From mertz at gnosis.cx Sat Mar 9 00:27:13 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Sat, 09 Mar 2002 00:27:13 -0500 Subject: PEP 284, Integer for-loops (fwd) Message-ID: I observed: ||"Gnosis XML Utilities" has 3100 lines (written largely by me, ||with various contributors). ||There are *4* uses of [x]range() in 'for' loops. One is a test case ||that just uses 'range(500)' to do something "a bunch of times". James_Althoff at i2.com wrote: |I just did the same for a small section of our code. My quick little scan |turned up 293 uses of [x]range. |Our mileage might be different from others because our use of Jython is for |large-scale, shipping, production-level, commercial applications rather |than for small, throw-away scripts or core-language libraries. Also (as |mentioned) we use Jython and have to deal with tables My utility package is certainly not "throw-away scripts". And while it is generally tested with CPython, there's no reason it shouldn't work equally well with Jython. So some of that difference isn't really germane. The issue about iterating through data tables might be the key. But I think even then, my own style would generally not use range() iteration. For example, one might write (very simplified): rows = dbquery(sql) for i in range(len(rows)): print i, rows[i] But I would probably approach this more like: i = 0 for row in dbquery(sql): print i, row i += 1 It feels cleaner to me to iterate through the actual collection, rather than numerically over its length... even if I am then interested keeping track of the number. If one fetches rows incrementally, I would still probably go for a 'while 1:' style. -- 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 chris.gonnerman at newcenturycomputers.net Wed Mar 27 08:26:34 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 27 Mar 2002 07:26:34 -0600 Subject: Random... References: Message-ID: <006901c1d593$1d0721c0$0101010a@local> Perhaps I'm stupid... what the heck is wrong with the OP's message? ----- Original Message ----- From: "Wojtek Walczak" > ** Since micro$oft is stupid it doesn't mean > ** that you should be stupid too - do NOT toppost. This is much ruder than normal for this group. Aren't we the kinder, gentler USENET? > Dnia Mon, 25 Mar 2002 18:52:25 +0100, FREDRIK HULDTGREN napisa?(a): > >I want to generate random numbers, very large random numbers. If I use > >randrange() I get an out of bounds error since it only supports numbers > >up to (2**31)-1. However, I can use uniform(), but then I get the number > >returned in 7.9655120654553743e+018 or something simaler, and I would > >rather have it in a "L" format(796551206545537430183218312890381031L). > >How do I do this? > > HTH. > > -- > [ Wojtek gminick Walczak ][ http://hacker.pl/gminick/ ] > [ gminick (at) hacker.pl ][ gminick (at) klub.chip.pl ] > -- > http://mail.python.org/mailman/listinfo/python-list > > From python at rcn.com Thu Mar 7 01:24:15 2002 From: python at rcn.com (Raymond Hettinger) Date: Thu, 7 Mar 2002 01:24:15 -0500 Subject: The language vs. the environment References: Message-ID: "Skip Montanaro" wrote in message news:mailman.1015449438.31833.python-list at python.org... > > There has been a huge amount of recent PEP activity related to further > enhancements to the language. I think in general that if more of this > energy was directed at the overall environment (library, support tools, > installers, documentation, etc) we'd be better off in the long run. I certainly agree that effort needs to be put into the library, etc. However, I would like to defend the PEP writers guild on a few points: 1. Writing a PEP is a disciplined activity that involves completely thinking our design choices, rallying public opinion, collecting all points of view for and against, and documenting all of that information in a single, version controlled, standard format document in a public place for everyone to study, ridicule, or on extremely rare occassions, adopt. In other words, PEP writing is contributing to science and is not a wasted effort even if the idea never gets adopted. While some people groan whenever a new PEP appears, I think it's a good sign, rather than bad. It means we have smart people who care and are willing to engage in public collaboration instead of sitting on the sides slinging mud like other language forums (not to mention any one particular four letter scripting language). 2. Having several PEPs relating to loop counters suggests that either we're all nuts or that maybe this is a constant source of irritation and that any one of the proposals may be fixing a real problem. Note, the two options are not mutually exclusive; perhaps, we're all nuts AND Python needs a loop counter solution. My own recommendation is not entirely over top: indexed( collection, start=0, limit=None ) One built-in function to improve readability and reliability while solving the problem forever. Returning a generator is a low over-head, lazy solution compared to PEP 212 creating a huge new list of tuples. The real question is why there is so much inertia on getting this one solved. Please excuse the diatribe. Now that's out of my system, here are are few random thoughts on the PEPs: 237 Unifying longs and shorts -- I sure hope this gets finished for 2.3. It is long overdue (no pun intended) 246 Object Adaptation -- This has the potential to be a profound improvement while not getting in the way of people who don't need it. 265 Sorting Dictionaries by Value -- I don't think the world would come to an end if this were adopted. It's kinda nice, very easy to implement, and is invisible to people who don't need it. What's all the fuss about? Let's just do it. 266, 267 -- Optimized Python good. Slow Python bad. 269 Pgen module -- I see the upside. Is there a downside? 270 Uniq method for list objects -- Same comment as for 265 274 Dictionary comprehensions -- Sounds cool but is not a compelling advantage over dict( [(k,f(v) for k in alist] ). Hey, it only saves fewer than ten characters and no lines. 275 Switching on Multiple Values -- Wouldn't be surprised if someone told me this optimization were already in place. Which Pythonista is going to stand-up and demand that we keep a slower implementation' just because he or she hates the concept of change. 279 Enhanced Generators (my PEP) -- indexed() is WAY cool -- let's do it. Okay, the x-functions may belong in a separate module. Generator Comprehensions are loved by more than few, are trivially easy to implement, and invisible to those who don't care for them. And about .next(arg) and .throw(exception) -- yawn. 212, 276, 279(indexed), 281, and 284. Any of the above, all of the above, pick one and solve a real problem. My overall point is that it would be unhealthy to adopt an anti-pep attitude and that many of the PEPs are darned useful and not at all hurtful. This point may not apply to you. When I wrote 279, some replies were supportive, some were inquisitive, some were analytical, some were helpful, but there were some that had a scary attitude along the lines of: "I don't care if the idea is good, I will fight further changes till my dying breath" That being said, Skip is right. The libraries, documentation, and patches need work. I did not miss his point. G' nite, Raymond Hettinger From alf at logilab.fr Fri Mar 29 07:45:50 2002 From: alf at logilab.fr (Alexandre Fayolle) Date: Fri, 29 Mar 2002 12:45:50 +0000 (UTC) Subject: optional pass? (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26)) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA35C49.31397789@ndh.net> Message-ID: In article , phil hunt wrote: > True, but i still have to remove the passes when i want to implement > the class. Why don't you put a docstring ? It will help you document precisely what you had in mind when writing the class, and you can keep it when you actually write the code. Alexandre Fayolle -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Narval, the first software agent available as free software (GPL). From huaiyu at gauss.almadan.ibm.com Tue Mar 5 14:41:26 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 5 Mar 2002 19:41:26 +0000 (UTC) Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> <87sn7g2stu.fsf@tleepslib.sk.tsukuba.ac.jp> <87it8b1xzt.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: On 05 Mar 2002 12:42:30 +0900, Stephen J. Turnbull wrote: > >Verbatim low-level I/O would be permitted. I would want them to be >restricted from being displayed literally by character-oriented >high-level functions like print, though. If you want to use print on >them, convert them to something with an appropriate (trivial) __repr__ >operation defined. ... >Thus by the principle of "least surprise" I advocate that raw string >users use a new notation, while the (much larger and much more naive) >group of people who expect > > print 'And now for something completely different' > >to do something useful would notice nothing new. > > print o'she turned me into a newt ... it got bettah' > >would either error (my preference) or print something like a tuple of >integers. > > print Code86(o'spam, spam, eggs, and spam').disassemble() > >would do what you think, if class Code86 were defined appropriately. Now I see what you are advocating. I agree completely. Huaiyu From tim at vegeta.ath.cx Mon Mar 11 05:21:04 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Mon, 11 Mar 2002 10:21:04 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8C82D3.CA4220CA@earthlink.net> Message-ID: Tim Hammerquist graced us by uttering: > Hans Nowak graced us by uttering: > [ snip ] >> It sure smells like a hoax. I mean, really: >> > [ snip ] >> >> "Open and unrestricted"? It sure seems ludicrous to see these >> words in the same sentence with "Microsoft". > > Didn't you know? Microsoft invented Open Source! ;) How 'bout a link: http://www.theregister.co.uk/content/4/22749.html Tim Hammerquist -- : Let's say I have a perl object in an OO database. Let's not. -- Larry Wall in <199904091918.MAA06535 at kiev.wall.org> From skip at pobox.com Wed Mar 6 18:14:30 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 17:14:30 -0600 Subject: The language vs. the environment In-Reply-To: <7x1yexe2mi.fsf@ruckus.brouhaha.com> References: <7x1yexe2mi.fsf@ruckus.brouhaha.com> Message-ID: <15494.41686.958612.585657@beluga.mojam.com> Paul> While we're at it, am I the only one bothered by how unsharp the Paul> boundary is between the language and the environment? I'd Paul> consider things like sys.exc_info to be part of the environment, Paul> but there's no other way to get the info. Paul, I was thinking of much larger granularity things and things that are more clearly separated from the language as delivered in python2.2.tgz or python2.2.exe. It appears you'd like to conisder the standard library as part of the environment. It is, certainly in a technical sense, but since it is also part of the standard distribution, a semantic change there has a much larger potential impact on programmers than, say an incompatible change to a third-party package like PIL or MySQLdb. So, I think it kind of straddles the fence a bit and has to be considered in a slightly different light. Skip From lluang at northwestern.edu Thu Mar 14 15:25:24 2002 From: lluang at northwestern.edu (Louis Luangkesorn) Date: Thu, 14 Mar 2002 14:25:24 -0600 Subject: basic statistics in python References: Message-ID: <3C910734.9030109@northwestern.edu> The stats module in scipy and the one by Gary Strangman mentioned by another poster are one and the same. Let's see, basic stuff like mean and standard deviation has been tested against certified results (see the unit tests for the stats module. I have an updated copy that I'm working on if that helps). I don't recognize bi-serial correlations, but when I test spearman and pearon's they fail depending on the inputs (I'm writing unit tests for stats.py. If anyone has a burning desire (or any desire at all) to rewrite the correlation test, I can email (or update the CVS) what I have now so you can get some test cases. Now that I've finished my proposal defense I can think about these things again) Louis dsavitsk wrote: >hi all, > >never having done numeric calculations in python* i am seeking advice on how >to best go about doing some basic statistics. in particular, i need to find >standard deviations and point bi-serial correlations**, and i am seeking >advice on the best way to go about it. i know how to do them, but i am >wondering if there are prebuilt modules that might simplify the task. > -- K Louis Luangkesorn lluang at northwestern.edu http://pubweb.nwu.edu/~kll560 PGP:0xF3E2D362 Whatsoever things are true, ... honest, ... just, ... pure, ... lovely, ... of good report; if there be any virtue, and if there be any praise, think on these things. - motto - Northwestern University From henrik.motakef at web.de Sun Mar 17 15:00:13 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 17 Mar 2002 21:00:13 +0100 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: <87pu23t16a.fsf@apo.hmotakef.int> "G. Sumner Hayes" writes: > ! is the closest thing to a vertical line on older keyboards (/= and |= > are already assignment operators), and represents the vertical stroke > through the equal sign. Like the accent marks in TeX and similar. BTW, Haskell uses /= for "not equal". It's quite funny watching C-Coders trying to understand why the one uses division here, and why += etc. won't work as well... Then again, they have more problems than that grokking Haskell. cu Henrik From tim.one at comcast.net Sat Mar 30 04:35:32 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 04:35:32 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Message-ID: [Christian Tanzer] > ... > If str and repr were to behave differently from each other, I'd expect > repr(True) to return "1" and str(True) to return "True". Interchanging > that seems strange. We try to ensure that eval(repr(x)) reproduce x whenever reasonably possible. That best way to do that here is for repr(True) to return 'True'. We also try to ensure that str(x) be "friendly" whenever possible, even if that means eval(str(x)) has no chance of reproducing x exactly, or even of running without raising an exception. The best way to do that here is also for str(True) to return 'True', but: > OTOH, I'm worried about backwards compatibility. That's the only reason for str(True) to return '1'. How about str(True) return '1' but str(False) return 'False'? That's what a committee would compromise on . > ... > How will bool influence '__nonzero__'? Currently, Python insists that > '__nonzero__ should return an int'. Will this be changed to 'should > return a bool'? I hope so. > As that would break existing code, I hope not. No, "should" != "must". Guido won't call code that returns an int here broken, although he might call it deprecated, and leave you wondering when the hammer will drop . From mcharity at vendian.org Sat Mar 9 14:44:02 2002 From: mcharity at vendian.org (Mitchell N Charity) Date: Sat, 9 Mar 2002 14:44:02 -0500 Subject: An Optimization Anecdote about PyInline Message-ID: <200203091944.g29Ji2E17927@ediacara.ne.mediaone.net> Guido's "Python Patterns - An Optimization Anecdote" (http://www.python.org/doc/essays/list2str.html) explores the performance of various ways of converting a list of integers into a string of characters. Such as the straightforward def f1(list): string = "" for item in list: string = string + chr(item) return string and the fastest version import array def f7(list): return array.array('B', list).tostring() # Use 'B' with Python2.2, 'b' with Python1.5 Guido writes [...] I had wanted to try one more approach: write the whole function in C. [...] Given the effort of writing and testing an extension (compared to whipping up those Python one-liners), as well as the dependency on a non-standard Python extension, I decided not to pursue this option... I wanted to revisit this, because with PyInline, the effort has diminished, and a non-standard extension is not required (just PyInline). And, as Guido points out, If you feel the need for speed, [...] - you can't beat a loop written in C. So, here then is a new version, f8(), which uses PyInline. from PyInline import C import __main__ C.Builder(code=""" PyObject* f8(PyObject *list) { PyObject* string = NULL; unsigned char* buffer = NULL; int size, index; #define RAISE(errtype,msg) { PyErr_SetString(errtype,msg); RE_RAISE; } #define RE_RAISE { Py_XDECREF(string); return NULL; } if(!PyList_Check(list)) RAISE(PyExc_TypeError,"a list is required"); size = PyList_Size(list); if(size < 0) RE_RAISE; string = PyString_FromStringAndSize(NULL, size); if(string == NULL) RE_RAISE; buffer = PyString_AsString(string); if(buffer == NULL) RE_RAISE; for(index = 0; index < size; index++) { PyObject *item = NULL; long number; item = PyList_GetItem(list,index); if(item == NULL) RE_RAISE; number = PyInt_AsLong(item); if(PyErr_Occurred() != NULL) RE_RAISE; if(number < 0 || number > 255) RAISE(PyExc_TypeError,"an integer was out of range"); buffer[index] = (unsigned char) number; } return string; } """,targetmodule=__main__).build() The test jig requires a slight change #for f in testfuncs: print f.func_name, f(testdata) for f in testfuncs: print f(testdata) because PyInline currently generates glue which does not understand f.func_name. So, what is the result? First, the downsides. f8() is a C extension, and so only works with C-based Pythons. PyInline invokes an external C compiler, and cruftily caches the result in the filesystem. And, as PyInline is alpha code, there are little misfeatures like not being able to use func_name. Oh yes, and being written in C, f8() is perhaps two orders of magnitude more complex than the Python versions. Though, this last is perhaps a worst case, as f8() is almost all interface code, with maybe just three lines of algorithm. In more typical use, one might see a one order of magnitude cost. And with objects which provide a nice C api, maybe even less. The upside is f8() runs 5 times faster than f7(), the best alternative. And uses half the memory. That's 50 times faster than the naive versions. And again, when python interface code is less dominant, the speedup can be dramatically larger. So, restoring the phrase I clipped out of the quote above, "If you feel the need for speed, go for built-in functions - you can't beat a loop written in C.". And if there isn't one already, you might consider creating one with PyInline. Mitchell Charity (I'm working on a web page http://www.vendian.org/mncharity/dir3/inline/ which explores using PyInline, and Perl's Inline, with objects which provide C api's.) From ralph at inputplus.demon.co.uk Tue Mar 19 19:21:45 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 20 Mar 2002 00:21:45 GMT Subject: Python-2.2.1c1 Build Problems on Linux and AIX. References: Message-ID: Hi, > > With Python-2.2.1c1, I find `make test' fails on my old version of > > Linux/x86 and it fails to build on an also old version of AIX. > > How old? Ooh, AIX 3.2.5 or so. Very crufty, but the last version supported by IBM on some RS/6000 hardware and used by an air traffic control system or two, so it isn't going to be upgraded anytime soon. > > Should I go straight to SourceForge and fill in bug forms or do > > people tend to discuss the problems here first? > > Please do. Assign the bugs to me. Give OS/architecture/etc info, > please. Will do. > > I can see the problem with the AIX build. Linux SIGSEGVs in > > test_calendar on a call to strftime. > > More detail needed. And you'll get it. This was just a two line overview :-) Ralph. From edcjones at erols.com Sat Mar 30 10:15:29 2002 From: edcjones at erols.com (Edward C. Jones) Date: Sat, 30 Mar 2002 10:15:29 -0500 Subject: Data type ideas References: Message-ID: <3CA5D691.2070409@erols.com> I have a module called "MultiDict.py" which you can find at "http://members.tripod.com/~edcjones/pycode.html". It is probably too slow but it might give you some ideas. Also consider using MySQL / MySQLdb or writing a C++ function using multimaps. Good luck, Ed Jones Joel Ricker wrote: > HI all, got a new problem :) > > I have a tab delimited file of people plus a list of groups they belong > to like so: > > Person 1 Group A > > Group B > > Person 2 Group B > > Person 3 Group A > > Group C > > So basically a person can be part of one of more groups. I'm looking to > process this list so that I can take each group and examine the list of > people in it. Basically turn the list into: > > Group A Person 1 > > Person 3 > > Group B Person 1 > > Person 2 > > Group C Person 3 From phr-n2002a at nightsong.com Sun Mar 31 22:45:44 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 31 Mar 2002 19:45:44 -0800 Subject: PEP 285: Adding a bool type References: <3CA79606.A0C1B055@python.org> <3CA7D24B.14E17A03@alcyone.com> Message-ID: <7xsn6ghyjb.fsf@ruckus.brouhaha.com> Erik Max Francis writes: > > The main effect this had was to confuse the died-in-the-wool > > programmers; it didn't make any difference for the newbies because > > they had to learn the concepts anyway. When you come in with a > > blank mind it doesn't matter if a particular concept is called > > "variable" or "waffle" -- you have to learn a new meaning for an > > existing word either way, and the previous meaning you knew for the > > word is barely relevant in the new context. > > Couldn't agree more; I mentioned something substantially similar in my > reply. Inventing new, non-standard terminology in order to be "simpler" > is rarely helpful; it doesn't substantially help newbies, and it only > serves to confuse people actually involved. This is born out by experimental psychologists, e.g. Landauer, T.K., Gallotti, K., and Hartwell, S., Natural command names and initial learning: A study of text editing terms, Commun. ACM, 26, 7 (Jul. 1983), 495-503. found that "unnatural" command names (think of grep, ls, rm) were really no harder for newbies to remember than "natural" ones. From jlh at cox.net Sun Mar 3 12:51:23 2002 From: jlh at cox.net (Jeff Hinrichs) Date: Sun, 03 Mar 2002 17:51:23 GMT Subject: Status of PEP's? References: Message-ID: "Carel Fellinger" wrote in message news:a5ro01$b3u$1 at animus.fel.iae.nl... > How strange the world is, I now end up defending a proposal I'm > against (or was against, I'm still in dubio) Sometimes it is easier to reach the truth by arguing against your position.(i.e. devil's advocate) > Jeff Hinrichs wrote: > > > "Carel Fellinger" wrote in message > > news:a5pmvd$fic$1 at animus.fel.iae.nl... > >> Jeff Hinrichs wrote: > >> > >> > What you are asking everyone to agree with is: > >> > 5 = [0,1,2,3,4] > >> > >> No he isn't:) He explicitly says he doesn't think of sequences at all. > > If it walks like a duck and talks like a duck... > > It's a duck. How can one iterate over something that is not a > > sequence/collection? > > This used to be the case in Python, but the invention of iterators > has changed the landscape. The for-construct no longer works on > sequences, it works on iterable objects. from the current docs: "The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object" So sequences are not out the for construct has been augmented to include iterable objects. >So it's not right anymore > to reject such a proposal based on that the thing isn't a sequence. > You now must reject it if you feel the thing can't be iterated over. > This may seem like a word play, but it isn't, it's a vital though > subtle difference. And it took me, being an old farth, quit some > time to let it sink in. Accepted. Ok, so iterable vs. sequence. iterable seems to mean "a sequence that has been contrived." but continued reading states that, "The expression list is evaluated once; it should yield a sequence." So what is the [0,1,2,3,4] returned by the 5 in, for i in 5: , called? (I realized it's generated by iterable object)The indici? I'm still trying to understand so bare with me... So if we say that, for i in 5: has the same result as, for i in range(5): then what happens, if python adopts this idea, when you try: >>>print 5 do you get 5 or [0,1,2,3,4] ? if you get 5 then how can you get [0,1,2,3,4] in the, for i in 5: statement? If the default property of an integer object as specified in the statement, for i in 5: is to return the indici it would seem proper to return that OR <5 at 007B5660> type statement that happens when you use the print statement on objects. if you print [0,1,2,3,4] or a string representation of an object pointer, won't that shock and confuse many? If integers are objects, would they not then support dot notation? How does that affect the parser?(5.property() vs. 5.0 , Is it an integer object or a float) Why only make integers objects? Is there support for making all numbers objects? Integers, after all, are a subset of all numbers. Shouldn't objects have to meet some of the same requirements that design patterns meet? Namely, be applicable to more than a specific problem? This appears to be a unique request for only a certain subset of numbers. If, objectifying integers is good then shouldn't making all numbers objects be better? I hope that all take my questions as they are intended, as questions from someone trying to learn. I apologize for the number of questions, but only by revealing my ignorance is there any hope for me. -Jeff From max at alcyone.com Sat Mar 30 02:30:40 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 29 Mar 2002 23:30:40 -0800 Subject: PEP 285: Adding a bool type References: <3CA56915.62947DDC@alcyone.com> Message-ID: <3CA569A0.442201CA@alcyone.com> [Following up to my own post here.] Erik Max Francis wrote: > Where is the backward compatibility problem for using bool? At > present, > no one uses it, so none of their types will be bools (right?). Wasn't think this one all the way through; of course, it's when people do comparisons that now return bools and do something explicit with their return value, rather than just using its implicit booleanness. Never mind. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From haaserdnospam at yahoo.com Thu Mar 28 21:58:50 2002 From: haaserdnospam at yahoo.com (Roger) Date: Thu, 28 Mar 2002 19:58:50 -0700 Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> Message-ID: <3CA3D86A.7080806@yahoo.com> With only a year+ of experience, I second the motion for Apache. I started with Microsoft PWS, tried a couple of other "simple" solutions and wound up using Apache. The configuration files tend to look overwhelming as there are a lot of choices, but for the most part the defaults are what you want. I would also suggest you take a look at Webware's WebKit at http://webware.sourceforge.net/. It provides an object-oriented framework for your web applications and makes DEBUGGING your scripts easy (which is what you will need). I also use MySQL for a database, and MySQLfront as a gui interface to MySQL. All of these are free and all have Linux versions (with the exception of MySQLfront). Roger Gerhard H?ring wrote: > Sloth wrote in comp.lang.python: > >>I've looked at Apache, Xitami, Zope, Medusa, et. al and think they are >>wonderful applications. On the other hand, they are overkill for what >>I want to be able to do - have Python start a CGI server, serve a >>page, get form data, get data from a database, and display dynamic >>content. I don't need anything industrial strength, just something >>that can handle a single user. >> > > Maybe it's just me, but I often have difficulties to understand the > point of the "overkill" argument. > > >>Any thoughts? I sincerely appreciate everyone's help! >> > > If you can spare 5 megs of RAM and a little disk space, just go for > Apache (or Xitami, or whatever). When you're running the webserver and > are not using it currently, it'll be swapped out anyway, so why > bother? > > It's a myth that Apache is complex to get running, here's what you'd > need to do on Windows: > > 1) Install Python > 2) Install Apache > 3) edit etc/httpd.conf and add the line > > ScriptInterpreterSource Registry > > at the end of the file. > > 4) Write your Python CGI scripts in cgi-bin and name them .py > > Gerhard > From briner at infomaniak.ch Tue Mar 26 03:50:03 2002 From: briner at infomaniak.ch (cedric_briner) Date: Tue, 26 Mar 2002 08:50:03 -0000 Subject: list element of a class with the for statement Message-ID: hi, I'm interesting to know which method of a class I have to define to list the __records of this class: class CRdb: __fieldsName= [] __keyname= [] __records = ['first','secnd','third'] __iRecord= 0 because I would like to write something like: db=CRdb() for entry in db: print entry and then get first secnd third please let me know any pointer refering this topic...or even better a quick solution .. thanks. Briner From jwilhelm at outsourcefinancial.com Fri Mar 1 17:18:14 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 01 Mar 2002 15:18:14 -0700 Subject: Problems with multipart messages w/email class In-Reply-To: <1015006362.1673.7.camel@jwilhelm.ofsloans.com> References: <1015006362.1673.7.camel@jwilhelm.ofsloans.com> Message-ID: <1015021094.1672.19.camel@jwilhelm.ofsloans.com> On Fri, 2002-03-01 at 11:12, Joseph Wilhelm wrote: > Traceback (most recent call last): > File "", line 1, in ? > File "/opt/python/lib/python2.2/email/Message.py", line 59, in > as_string > g(self, unixfrom=unixfrom) > File "/opt/python/lib/python2.2/email/Generator.py", line 83, in > __call__ > self._write(msg) > File "/opt/python/lib/python2.2/email/Generator.py", line 104, in > _write > self._dispatch(msg) > File "/opt/python/lib/python2.2/email/Generator.py", line 134, in > _dispatch > meth(msg) > File "/opt/python/lib/python2.2/email/Generator.py", line 240, in > _handle_multipart > for part in msg.get_payload(): > File "/opt/python/lib/python2.2/email/Message.py", line 151, in > __getitem__ > return self.get(name) > File "/opt/python/lib/python2.2/email/Message.py", line 214, in get > name = name.lower() > AttributeError: 'int' object has no attribute 'lower' Well, I have gotten a small fix for this traceback put into my copy of Generator.py. I don't know if it should be necessarry, but this is what I got to make it work (At line 240): I replaced for part in msg.get_payload(): With pload = msg.get_payload() if type( pload ) is not ListType: pload = [ pload ] for part in pload: Just something very small and simple, but it was necessarry to make this email work properly. Any comments on this? Is this a known bug? Is there something I may have done wrong that would cause the previous error? --Joseph Wilhelm From tdelaney at avaya.com Wed Mar 13 23:06:09 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 14 Mar 2002 15:06:09 +1100 Subject: Performance problem with filtering Message-ID: > From: Delaney, Timothy [mailto:tdelaney at avaya.com] > > So, the first thing I would recommend is ... > > results = [] > c = {} > > for entry in a: > c[entry] = None > > for entry in b: > if c.has_key(entry): > results.append(entry) Bah ... if not c.has_key(entry) ... > This means you are searching for a key in a dictionary ... a > very quick > operation. > > A further optimisation is to use the filter() function. > > results = [] > c = {} > > for entry in a: > c[entry] = None > > results = filter(c.has_key, b) Bah ... results = filter(lambda k: not c.has_key(k), b) That will slow it down a bit (using the lambda) but will give the right result ;) Tim Delaney From kragen at pobox.com Tue Mar 19 03:32:02 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 19 Mar 2002 03:32:02 -0500 Subject: Modulo operator : differences between C and Python References: Message-ID: <837ko9klfh.fsf@panacea.canonical.org> Tim Peters writes: > Python defines the result of i%j to have the same sign as j; what C requires > depends on which year's C standard you're looking at (it was left up to > implementers' discretion before the 1999 standard); the C implementations I > use return a result with i's sign, and I usually curse them for that. This is a result of C being a portable assembly language; % returns whatever the underlying remainder register has after a divide, which generally has i's sign. From peter at engcorp.com Thu Mar 7 08:17:44 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Mar 2002 08:17:44 -0500 Subject: Is there any wxPython turtor? References: <3C865341.8D190235@cablespeed.com> Message-ID: <3C876878.E5E9FC6D@engcorp.com> Ricky wrote: > > Thank you, I find a lot of resources. > > But wxpython.org is still not available for me. It's very likely it's your problem, not the site's. I can see it fine, and could before as well. Try doing a "ping wxpython.org" and if that works, it's your browser or firewall settings that are bad. -Peter From wayne at mishre.com Sun Mar 3 23:24:40 2002 From: wayne at mishre.com (Wayne Pierce) Date: Sun, 03 Mar 2002 20:24:40 -0800 Subject: Black Adder and PyQt References: <3C80B1E3.575761B7@river-bank.demon.co.uk> Message-ID: <3C82F708.70303@mishre.com> >>From the BlackAdder readme file: >>The license of the Beta version prevents run-time components of the >>Business Edition being distributed with your applications. This >>restriction will be removed when the final version is released. >> >> > > Yes, but _when_ will the final version be released? Bad form! You need two __'s on each side! ;) > Not that I have anything I might want to distribute, but I see fro my > records that I paid for the beta nearly a year ago, and in that time > there has been one update, last summer, and since then a resounding > silence. It would be a shame if the project just sputtered and died. > There are all sorts of unselfish reasons for hoping that some > company (or kompany) figures out a way to make money from Linux > sometime. Same here. I haven't had a need to distribute the software I wrote yet without source but I may have to in the future; unfortunately I didn't catch that clause in the readme or I probably wouldn't have bought BA. Anyone out there have recommendations on a good IDE with form designer, that's not Beta? Nothing too fancy...I've tried wxDesigner, but couldn't figure out that spacer stuff for the life of me. Wayne -- Wayne Pierce web: http://www.mishre.com email: wayne at mishre.com "What you need to know." From aahz at pythoncraft.com Fri Mar 22 13:01:01 2002 From: aahz at pythoncraft.com (Aahz) Date: 22 Mar 2002 13:01:01 -0500 Subject: "Zope-certified Python Engineers" [was: Java and Python] References: <20020322115241.429$rK@news.newsreader.com> Message-ID: In article <20020322115241.429$rK at news.newsreader.com>, Hernan M. Foffani wrote: > >We already have a sort of Python certification program. And with several >layers of qualifications. ;-) >- Python Devs with commit permission. >- Other Python Devs >- Known c.l.py contributors >- Authors of modules, recipes, etc. > >I know this is not a formal procedure (see the smiley.) But for >hiring programmers, wouldn't be better if the applicant can show off >(pun intended) his/her previous work? > >If Python skills "certificated" through public collaboration develops as a >our common practice, the community would benefit a lot. And we honor Python >Open Source spirit. Very nice. I like! I'd change "layers" to "categories", though. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From syver-en+usenet at online.no Sat Mar 30 13:15:08 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sat, 30 Mar 2002 18:15:08 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: Dale Strickland-Clark writes: > For some reason, this only drops the DOS 8.3 version of the > filename. Compatibility with old programs probably. Suggestion: Use dynwin.windll http://www.nightmare.com/~rushing/dynwin/ import windll kernel32 = windll.module('kernel32') kernel32.GetLongPathName() to get the longnames. I suppose it's for compatibility. You can't know when somebody or someprogramme will hand you a short pathname. PS: GetLongPathName only works on win2000/win98 and upwards. I have a msdev project to compile calldll and friends for python 2.2 if that is a problem. -- Vennlig hilsen Syver Enstad From tchur at optushome.com.au Sat Mar 9 21:34:29 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 10 Mar 2002 13:34:29 +1100 Subject: Announce: RPy (R from Python) References: <20020308113507.A2855@casa.parque> Message-ID: <3C8AC635.FA2074C2@optushome.com.au> Walter Moreira wrote: > I wrote a small extension module for using the R programming language from > within Python. It makes it possible to use the huge mathematical and > statistical library of R from Python, almost whitout any changes from the text > of R manuals. > > As a side effect, it is also possible to use the full graphics capabilities of > R, which are extremely good. > > You can download it from: > > http://www.cmat.edu.uy/~walterm/rpy This is a fabulous bit of work! In order to illustrate both the power of the R environment and the ease with which this power can be used from within Python (thanks to Walter's efforts and those of Duncan Temple Lang on the RSPython module which inspired RPy), I have created a little demo, available at http://gestalt-system.sourceforge.net/rpy_demo.html Cheers, Tim C From cliechti at gmx.net Sat Mar 16 12:40:51 2002 From: cliechti at gmx.net (Chris Liechti) Date: 16 Mar 2002 18:40:51 +0100 Subject: Linux endline References: <3C932C41.2974C1DA@club-internet.fr> Message-ID: "Fredrik Lundh" wrote in news:gJKk8.25432 $n4.4999467 at newsc.telia.net: > Fabien H?non wrote: >> 1? When I use it under Linux I would like to get rid of the \r which >> appears at the end of each line. ( I know there is a difference of >> endline between Windows, Mac and Linux). > > how about > > if line.endswith("\r\n"): > # deal with DOS file ending > line = line[:-2] + "\n" > self.text.insert(END, line) or, if you don't care about having whitespaces after the last printable character you can also call line = rstrip(line). i even use string.strip() in an application where no leading or trainling whitespaces are needed. chris -- Chris From trentm at ActiveState.com Tue Mar 5 12:21:38 2002 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 5 Mar 2002 09:21:38 -0800 Subject: python IDE, komodo In-Reply-To: <3c84f0eb.27475796@news.easynews.net>; from stojek@part-gmbh.de on Tue, Mar 05, 2002 at 04:26:06PM +0000 References: <3c84f0eb.27475796@news.easynews.net> Message-ID: <20020305092138.A32466@ActiveState.com> [Marcus Stojek wrote] > Hi, > > I am looking for an Python IDE. Nothing extremly special, just > easy debugging, tracing maybe profiling. Is Komodo okay? > Is there something else (except Visual Studio .NET) I should > look at. Something free would be nice. Komodo is good, but I am biased. :) Take a look at: http://www.python.org/editors/ Trent -- Trent Mick TrentM at ActiveState.com From BPettersen at NAREX.com Fri Mar 29 16:24:30 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 29 Mar 2002 14:24:30 -0700 Subject: Another stab at a "switch/case" construct (for Python 3000): Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158DC1@admin56.narex.com> > From: Steve Lamb [mailto:grey at despair.dmiyu.org] > > On Fri, 29 Mar 2002 10:48:15 GMT, Benjamin Schollnick > wrote: > > IF X == 0: > > DO_THIS () > > ELIF X == 2: [snip] > > But, this routine is not exactly readable compared to a case: > > > CASE X of: > > 0 : DO_THIS() > > 2 : DO_THIS (2) > > 4 : DO_THIS (x+2) > > 6 : DO_THIS () > > ELSE: > > DO_NOT_DO_THIS() > > its_called_a_directory_pointing_to_functions = {'case':closed} > > I do not believe that any language which can have a hash > of function pointers has any business with a case statement. But that only works when all the functions in all the branches take the same number and types of arguments -- hardly the general case. -- bjorn From case at ironwater.com Wed Mar 6 04:46:19 2002 From: case at ironwater.com (Case Van Horsen) Date: Wed, 06 Mar 2002 09:46:19 GMT Subject: mx package References: Message-ID: "Colin Fox" wrote in message news:pan.2002.03.06.01.23.47.195291.3038 at crystalcherry.com... > I'm trying to work with Zope and Postgres, and one of the > packages I'm trying to install (psycopg) requirs mxDateTime, which in > turn requires mx. > > I can't find any mention of this 'mx' package anywhere. > Try searching Google with "mxDateTime". mxDateTime is part of the Base set of tools, which is the mx package. Case From sholden at holdenweb.com Thu Mar 28 08:54:05 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 28 Mar 2002 08:54:05 -0500 Subject: Random... References: <%slo8.20800$cB5.20607@atlpnn01.usenetserver.com> Message-ID: "Sibylle Koczian" wrote in message news:a7ugiv$kv6$1 at rzmux02.rz.uni-augsburg.de... > Erno Kuusela schrieb in Nachricht ... > >In article <%slo8.20800$cB5.20607 at atlpnn01.usenetserver.com>, "Steve > >Holden" writes: > > > >i think it's good to remind people of this occasionally. while it may > >waste time for most people, it also lets newbies learn the ways of > >netiquette without having to be chastised invividually by email. > > > Especially as this silly Outlook Express strongly suggests top posting by > placing the cursor at the beginning and inserting an empty line. So somebody > _has_ to tell the newbie not to write at this point. (That somebody might be > common sense, of course.) > > Koczian > Well, while we're talking about netiquette, I suppose we should *also* remind everybody that it's necessary to be careful with attributions! For the record, I did NOT write the comments attributed to me above, as a careful examination of the quote marks shows. Since none of my original comments were included, including my attribution is likely to mislead. The quoted remarks were written solely by Erno in response to a posting from me whose content was removed. Retaining my name would have made more sense if something had explicitly indicated this. letting-it-all-hang-out-(and-using-outofluck-express)-ly y'rs - steve From aahz at pythoncraft.com Sun Mar 31 15:35:29 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 15:35:29 -0500 Subject: PEP 285: Adding a bool type References: <3CA751EF.10F25F2D@ndh.net> <3CA75ECC.389A0186@alcyone.com> <2NJp8.140405$Yv2.43077@rwcrnsc54> Message-ID: In article <2NJp8.140405$Yv2.43077 at rwcrnsc54>, Emile van Sebille wrote: > >Someone (Guido?) already mentioned that testing for true is redundant, >but doesn't : > if 2: >imply > if 2 == True: Nope. That's like saying if '': having the same result as if []: implies that '' == [] which is completely untrue. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From m.faassen at vet.uu.nl Mon Mar 25 09:59:34 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 25 Mar 2002 14:59:34 GMT Subject: Zope Xen project management, whetever happened?? References: Message-ID: William Hamilton wrote: > What ever happened to Xen? Was progress ever made in it, was there a > replacement project management system for Zope created?? I think the project died a quiet death. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From eppstein at ics.uci.edu Wed Mar 6 12:12:47 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 09:12:47 -0800 Subject: PEP 284, Integer for-loops In-Reply-To: <15494.19711.723922.527327@beluga.mojam.com> References: <15494.19711.723922.527327@beluga.mojam.com> Message-ID: <6862777.1015405967@[192.168.1.100]> On 3/6/02 11:08 AM -0600, Skip Montanaro wrote: > Why is an or_expr non-terminal between the two comparisons? Shouldn't it > be a target_list? I wanted the grammar to enforce exactly the same precedence rules as in expressions, and the easiest way to do that was to use the same tokens as in the corresponding part of the expression grammar. Also, target_list isn't right because the proposed for-loop syntax only allows looping over one integer at a time, not a tuple of integers. But perhaps there's a better choice than or_expr that would flag more non-lvalues as syntax errors...suggestions welcome. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From bobx at linuxmail.org Fri Mar 29 15:36:55 2002 From: bobx at linuxmail.org (Bob) Date: Fri, 29 Mar 2002 20:36:55 GMT Subject: Metakit vs. StandaloneZODB Message-ID: I am just getting back into Python and while perusing the ActiveState packages I find Metakit and StandaloneZODB as choices. Can someone give me the relative merits of each? And why they would choose one over the other? Bob -- "Somebody told me how frightening it as how much topsoil we are losing each year, but I told that story around the campfire and nobody got scared." -- Jack Handy From eppstein at ics.uci.edu Fri Mar 1 11:21:04 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 08:21:04 -0800 Subject: Status of PEP's? References: Message-ID: In article , "Bjorn Pettersen" wrote: > Nothing at all, but with this syntax you have different semantics for: > > for start <= i < end: > > And > > if start <= i < end: Different in what sense? "for something" loops over all values of the variable that make "something" true. Which part of "something" is the variable is determined by its location in the overall expression. That is true with the current "for x in y" syntax as well as the suggested "for start <= i < end" syntax. Well, except that by "all values" substitute "all integer values" since it doesn't make sense to loop over all floats. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From robin at jessikat.fsnet.co.uk Mon Mar 11 18:39:30 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 11 Mar 2002 23:39:30 +0000 Subject: zlib vulnerabilities and python Message-ID: Does the recent zlib double free vulnerability http://news.com.com/2100-1001-857008.html impact zlib.pyd? -- Robin Becker From jkraska at san.rr.com Fri Mar 22 21:50:15 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 23 Mar 2002 02:50:15 GMT Subject: Environment variables. References: <3C9BAFAE.51D0896D@cs.unm.edu> Message-ID: >The only way to set environment variables so they persist is by >attacking the registry but then the new values don't get used until >you start a new command prompt window. This is true. Of command prompts. Note, however, that under Windows/NT variants (NT, 2000, XP) changes to environment variables can and are propagated through to the Explorer. So while one can't do "it," and one most certainly can't do "it" generally for all operating systems, there is indeed some way to do it "it" for Windows for some variant definition of "it" that I'm personally ignorant of. :) :) This version of "it" probably involves the application in question listening for some kind of well known event. C// From bokr at oz.net Wed Mar 20 13:55:10 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Mar 2002 18:55:10 GMT Subject: classes for fun and newbies References: Message-ID: On Wed, 20 Mar 2002 06:26:54 -0500, "Bruce Dykes" wrote: >Just to make sure I'm on the right track here... > >I'm reading records from a file. This is a flat file, with one line per >record, and each line being some 380+ characters long, with about 40 fields >in each record. > >Now I'm thinking that the easiest way to deal with these records (in >preparation for developing a Zope app to interface with them), is to set up >a class, with attributes for each field: > >class call_record: > def __init__(self, record=''): > self.record_id=record[0:5] > self.date=record[6:11] > >etc... > >Now what I expect to be able to do is say: > >log = readlines(today.log) > >and then summon discrete bits of info like so: > >print call_record.record_id(log[1]) > You probably want apro = call_record(log[1]) #apro: a_parsed_record_object and then print apro.record_id but you might also give your objects a __str__ function to make a default printing string, e.g., def __str__(self): return '' % self.record_id then print apro will print whatever __str__ returned. You could also return formatted strings for different standard views that you might want to print, with statments like print apro.brief_view() or print apro.full_view() or even print apro.formatted_view('a string to control formatting') Once you have decided to make objects, you have the opportunity to give them behaviors (methods) too, not just attributes to access. This can clean up the code that uses the objects. >However, all I get when I try this is the return of of the object attribute >instance and its memory address. > You know why by now. >Am I on the right track and just overlooking something obvious? Is there >already an app that does something similar that I can browse for pointers? > >On a side note, it was fun just cranking out a python script that created >the class code from the file documentation. 8-) > Python is cool in many ways ;-) HTH Regards, Bengt Richter From kragen at pobox.com Tue Mar 19 13:51:10 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 19 Mar 2002 13:51:10 -0500 Subject: Parsing string into fixed-width pieces References: Message-ID: <83n0x4ie75.fsf@panacea.canonical.org> "Johnson, Brad" writes: > I'm new to Python and have been combing the documentation and the message > archive here for information on splitting a string into fix-width pieces. I > assume their is an easy way to do this, I just don't seem to be able to find > it in the reference material. Any suggestions? Is this to unpack some fixed-width record format? The struct module is used for fixed-width record formats: >>> import struct >>> struct.unpack('3s4s3s', 'asdfghijkl') ('asd', 'fghi', 'jkl') HTH. From op73418 at mail.telepac.pt Thu Mar 14 09:58:09 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 14 Mar 2002 14:58:09 +0000 Subject: Good book on Python? References: Message-ID: On Thu, 14 Mar 2002 11:26:01 +0000, Antonis C Koutalos wrote: > >Hi there, > I would greatly appreciate information about a good book on python. I >have been programming C for a few years, but I know next to nothing about >python. Therefore, I would appreciate a book that describes the basics of >python as well as the more advanced features of the language. > >Thank you in advance! > >-A. To learn the language itself there's no better than the online tutorials. Start there. As for books, I recently bought a copy of M. Lutz's Programming Python and I like it very much. Note though, that this book is for people that already have experience with Python. It is a sort of "what can you do with Python" in several areas (sysadmin, GUI's via Tkinter, etc.) and, as I said before, i like it very much. Hope it helps, Gon?alo Rodrigues From henrik.motakef at web.de Mon Mar 4 11:37:13 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 04 Mar 2002 17:37:13 +0100 Subject: Can Python do this? References: Message-ID: <86pu2k1e86.fsf@apo.hmotakef.int> "Robert Oschler" writes: > Can I then call that method by somehow having the interpreter > evaluate the string variable into a call to the desired method? You can. It's (unsurprisingly) called "eval". >>> def func1(): print "foo" ... >>> eval("func" + "1") >>> eval("func" + "1()") foo >>> eval("func" + "1")() foo hth Henrik From jrchaff at mcn.net Wed Mar 13 13:40:28 2002 From: jrchaff at mcn.net (jrc) Date: Wed, 13 Mar 2002 18:40:28 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: Message-ID: <3C8F9D2D.BFCB973B@mcn.net> Oh brother. What drivel. Eric Brunel wrote: > Hi all, > > Found the following link on comp.lang.tcl. A bit long, but worth reading... > > http://groups.google.com/groups?hl=en&selm=3B40A4A7.6E39BD%40brad-aisa.com&rnum=1 > > Regards, > - eric - From garrett at bgb-consulting.com Sun Mar 24 18:17:37 2002 From: garrett at bgb-consulting.com (Don Garrett) Date: Sun, 24 Mar 2002 23:17:37 GMT Subject: Java and Python for embedded applications (was: Java and Python) References: <3C96DBB4.6040109@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> <3C9836B8.150B4DA@engcorp.com> <7F4A1C2050937632.B0420410CEF7D39A.B15EB10EEC873652@lp.airnews.net> Message-ID: <3C9E5E7B.82FE2AD6@bgb-consulting.com> Cameron Laird wrote: > I'm unconvinced about even the mild Java-is-smaller-and-faster claim. > While I don't keep up with embedded Java now, there certainly have > been times in the recent past when its start-of-the-art has been ... > disappointing in these regards. Python was competitive, and sometimes > better. I had the good fortune to work with Dallas Semiconductor on projects related to the Java ibutton, and TINI boards. They required that class files be run through a pre-processor that (mostly) did nothing but strip or compress meta data related to class information and perform as much linking as possible prior to downloading. Working programs were often compressed down to under a k. Of course, performance was what you would expect from an 8 bit processor running a 32 bit VM. Java worked very well in that embedded environment. In particular, the strict typing was very useful for the strict security mechanisms using in the iButton. Unfortunatly, I've never had the chance to work with embedded Python as a comparison. I should also note that while the Java iButton conformed to the Java SmartCard 1.0 spec, they did not conform to later versions, and people at DalSemi seemed to feel that the spec was evolved to their disadvantage for political reasons (I have no idea if that's true or not). -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From rkashyap at sympatico.ca Wed Mar 6 09:12:09 2002 From: rkashyap at sympatico.ca (Ramkumar Kashyap) Date: Wed, 06 Mar 2002 09:12:09 -0500 Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> Message-ID: <3C8623B9.3000504@sympatico.ca> I find that most introductory books approach programming in a non-intuitive manner and lose out on a big chunk of their audience. Only a few of us that persevere, end up learning the language and even fewer go on to achieve "GURU" status. Why is this? I have seen several posts on CLP and the newbie tutors list, where people mention that their first encounter with programming was in BASIC, COBOL, Pascal, Fortran. They did not really make any progress, gave up on programming. Now they are attempting once again, hoping things have become a little easier. I would like to know how the pattern was set to teach programming languages. You do an introductory program like "Hello World", learn how to compile and run it. Then jump into decision structures, loops, functions, etc. This is extremely non-intuitive to most people. Most 5,6,7 year olds can speak fluently in their native languages, but how many of them could tell you about vowels, consonants, nouns, verbs, adjectives. In fact quite a few of them speak multiple languages, can easily differentiate sentence structures in those languages, but would be hard-pressed to give defintions of the above. So how come in programming, we ALWAYS jump into the constructs of a language, rather than just doing, gaining proficiency and then understanding how it is put together? I think that unless the approach to teaching Programming languages, is changed and follows the more universal style of teaching spoke language or verbal communication, Computer Programming for Everybody will remain a dream. Just my .02 cents Ramkumar Curtis Jensen wrote: > The only disappointing parts for me were: > The cover, definitly didn't seem targeted to the college crowd, but > more to highschoolers. > No chapters on extending Python with C. > The XML chapters seemed to be an attempt to jump on the band wagon and > sell books. > > All in all, I think the book is well written. The examples are > usefull enough to figure out what is going on without reading the > chapter (good for lazy programmers). I lent it to a (non-programmer) > friend and he found it more useful than the O'Reilly Python book. > > Also, if your main intent for reviewing the book was for the money, > I'd suggest playing the lotto instead. Don't be so arogant that you > think that your time is so precious as to complain about a temporary, > predeterimined, pay scale. They were upfront in their monatary > compensation. If you don't like it, don't review the book. > From cjensen at bioeng.ucsd.edu Wed Mar 27 10:46:28 2002 From: cjensen at bioeng.ucsd.edu (Curtis Jensen) Date: Wed, 27 Mar 2002 07:46:28 -0800 Subject: list of empty lists References: <3CA11A5B.5000501@bioeng.ucsd.edu> Message-ID: <3CA1E954.4040901@bioeng.ucsd.edu> Curtis Jensen wrote: > Is there a easy way to make a list of an arbitray number of empty lists? > > I can do something like: > >>> some_number = 3 > >>> l = [[]] * some_number > >>> l > [[], [], []] > > Unfortunatly this has an unfortunate side affect. Whatever I do to one > of the list gets done to the other lists. ie: > >>> l[0].append(1) > >>> l > [[1], [1], [1]] > > > In this case, what I would like is three independantly empty lists. I > can make a for loop to loop "some_number" of times and append an empty > list at each itteration. Is there a simpler way? > Thanks. > Thanks to all for the quick answers. The "map(list, [[]]*n)" solution works best for me. Sorry I didn't mention it earlier; we needed a Python 1.5.2 solution. Plus this approach works on versions >1.5. -- Curtis Jensen cjensen at bioeng.ucsd.edu http://www-bioeng.ucsd.edu/~cjensen/ FAX (425) 740-1451 From duncan at NOSPAMrcp.co.uk Mon Mar 25 09:38:51 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 25 Mar 2002 14:38:51 +0000 (UTC) Subject: [albatross-users] Re: Python embedded like PHP References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> Message-ID: Dave Cole wrote in news:m3663k69rr.fsf at ferret.object-craft.com.au: > Duncan> I agree with you here up to a point. I would break down the > Duncan> roles into html developer who needs to know some ZPT, > Duncan> presentation developer who just needs to know what not to > Duncan> touch, and content developer who just needs to know which > Duncan> parts of the page require content. > > Are you suggesting that there are three different people would work on > the same template file? > > IMO there would be some sort of graphic design done which may not > necessarily produce useful HTML - that design would be taken by the > content developer who would then build the template. You have someone who does the graphical design, not necessarily in HTML. You have someone who converts that into a template (hopefully only one) for the entire site. Then there is someone who does the logic for querying databases etc. Then there is someone who updates the actual information that goes on the pages. Some of these jobs will be done by the same person, but say I want to add a new press release onto my site, then I don't want whoever does that to need to know HTML. I know of one company (Jamkit) near me that uses Zope+CMF to produce websites for businesses and charities. They produce the page layout from the information given them by the graphical designers, and I guess the logic is much the same for most of the sites. I believe they also set up the initial content, but after that the customers can edit their own pages, and even add new pages or move them around within the site structure. The critically important step in this is separating the content from the presentation. > Duncan> In particular the CMF skins help a lot. > > I haven't looked at CMF skins. Basically you have a set of folders containing templates. Each template builds on the other templates, but the folders are searched in order for each template. So for example a form might be defined in news_edit_form in the folder zpt_generic, but that calls main_template. main_template is also defined in zpt_generic, but if I add a mysite folder before zpt_generic in the skin then main_template from mysite would be used instead. So simply adding a new main_template instantly changes the appearance of every other template in the system. The presence of the skin folders is invisible to the templates, which are written as though all of the templates were in the current folder. You can define several skins, so for example you might have another skin which has a 'printable' folder early in its search containing a simplified main_template for formatting printable pages. For one site I have been playing with recently I have a folder 'ieeditor' which defines a wysiwyg editor for IE and changes a couple of the other templates to use it. The end user can choose between the plain html forms or the fancy (but slower) HTML editor by changing skins. (The end user never sees the skin folders, only a choice of skins). Python scripts also live in skin folders, so again you can customise behaviour by changing the scripts in an earlier folder without having to change the original. -- 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 wurmy at earthlink.net Sat Mar 2 20:32:12 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Sun, 03 Mar 2002 01:32:12 GMT Subject: ANN: experimental patch to allow importing from file-like objects References: <3c7fcbe6.7419921@news.t-online.de> <3c81245c.47694421@news.t-online.de> Message-ID: <3C817D5C.24C26C3F@earthlink.net> Gerson Kurz wrote: > On a related note, (I've asked this before to no avail) - how do I > successfully subclass files & open them? > > The problem is - where to I subclass a file returned from open()? > open() always returns the builtin file class. Attempting to do this > > ----------- (snip here) ------------- > > raw_file = open(...) > my_file = my_file_class() > raw_file.read = my_file.read > > ----------- (snip here) ------------- > > I'll get an error that read is a read-only method. I don't know much about 2.2 yet, but I think the preferred method is subclassing file, then opening a file through the subclass's constructor (rather than through open()). For example: class NoisyFile(file): def __init__(self, *args, **kwargs): file.__init__(self, *args, **kwargs) print "Bwahahaha!" f = NoisyFile("c:/python/test/2.2/test-file-1.py", "r") print f.readlines() f.close() HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From mxp at dynalabs.de Fri Mar 8 16:53:22 2002 From: mxp at dynalabs.de (Michael Piotrowski) Date: Fri, 08 Mar 2002 22:53:22 +0100 Subject: PARTIAL SOLUTION: Compiling Python 2.2 with GCC in HPUX 10.20 does not work References: Message-ID: Tim Peters writes: > [Michael Piotrowski] > > I've had a look at test_fpformat: The test expects that >> >> "%.*f" % (0, -0.003) >> >> produces -0 (negative zero), > > No, and this is important: this has nothing to do with negative zeroes. > What the test expects is a two-character *string*, '-' followed by '0'. I'm sorry. Of course you're right: The test expects the string "-0" and it gets the string "0" instead. -- Michael Piotrowski, M.A. From bokr at oz.net Sun Mar 10 17:19:19 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 22:19:19 GMT Subject: range Failure? References: <3C8B84B6.DB3F8E9A@sympatico.ca> Message-ID: On Sun, 10 Mar 2002 11:07:18 -0500, "Colin J. Williams" wrote: [...] >It might say: > > range([start= 0,] stop[, step= 1]) Still, the two optional []'s are not valid in all combinations, (which is what you fix with your improved text ;-) so maybe it should say something like: range([start= 0,] stop) # where step defaults to 1, or range(start, stop [, step= 1]) Regards, Bengt Richter From jason at jorendorff.com Tue Mar 12 13:25:09 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Tue, 12 Mar 2002 12:25:09 -0600 Subject: Can we use print to print to more than sys.stdout? In-Reply-To: <3C8E441E.4D64C8DA@impathnetworks.com> Message-ID: Pierre Rouleau wrote: > #1) Is it possible to change print behavior to make it print to several > streams? > > #2) > Is it also possible to define an object that would behave like a file > and that would do the printing itself to wherever required? # Sure. This code does both. class Mux: def __init__(self, *objects): self.__objects = objects def write(self, data): for obj in self.__objects: obj.write(data) def writelines(self, lines): for obj in self.__objects: obj.writelines(lines) myfile = open('somefile.txt', 'a') sys.stdout = Mux(sys.stdout, myfile) ## Jason Orendorff http://www.jorendorff.com/ From netzapper at magicstar.net Sun Mar 31 18:13:57 2002 From: netzapper at magicstar.net (A. Jones) Date: Sun, 31 Mar 2002 23:13:57 GMT Subject: Cannot find what I'm sure is a simple command... please help. Message-ID: <3ca7978b.251291804@mammoth.usenet-access.com> I seem to have either overlooked, or completely missed a function that allows one to open a specific line of a file. I've read through my Learning Python book, and read the relevent module docs (anything having to do with files, and the __builtins__). I must have overlooked such a function. I thought the seek() function might work, but it only seems to give me a byte offset in the file, and not a line number. Can somebody please help? -----------== Posted via Newsfeeds.Com, Uncensored Usenet News ==---------- http://www.newsfeeds.com The Largest Usenet Servers in the World! ------== Over 100,000 Newsgroups - Ulimited downloads - 19 servers ==----- From brobbins333 at shaw.ca Thu Mar 7 17:21:15 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Thu, 07 Mar 2002 22:21:15 GMT Subject: Module Search Path? Message-ID: <3c87e781.62223437@news> I want to store the modules I have written in their own directory. When I add it to the search path with sys.path.append the changes are made for one session only. How can I make permanent changes to the search path? I am using ActivePython 2.1 (PythonWin) in Win98. Bruce Robbins From lac at strakt.com Sat Mar 9 18:22:18 2002 From: lac at strakt.com (Laura Creighton) Date: Sun, 10 Mar 2002 00:22:18 +0100 Subject: Tkinter + Button widget In-Reply-To: Message from "Adonis Vargas" of "Sat, 09 Mar 2002 17:33:32 EST." <3c8a9185$1_1@nopics.sjc> References: <3c8a9185$1_1@nopics.sjc> Message-ID: <200203092322.g29NMItB025552@ratthing-b246.strakt.com> > when i start a button widget, it automatically fires the command? > > def HideNewClient(self, frame): > frame.configure(bd=0, width=0, height=0) > return > > pdb_btnSearch = Button(pdb_frmCommands, > text="Search", > relief=GROOVE, > font=("Tahoma", 10), > width=16, > command=self.HideNewClient(pdb_frmNewClient)) > > any help would greatly be appreciated. > > Adonis > > > > --__--__-- > > Message: 6 > From: "Adonis Vargas" > Newsgroups: comp.lang.python > Subject: Tkinter + Button widget > Date: Sat, 9 Mar 2002 17:33:32 -0500 > Lines: 18 > NNTP-Posting-Host: nopics.sjc > Message-ID: <3c8a91ed$1_2 at nopics.sjc> > Path: news.baymountain.net!uunet!ash.uu.net!sac.uu.net!news.compaq.com!paloalto-snf1.gtei.net!n > ews.gtei.net!enews.sgi.com!telocity-west!TELOCITY!nopics.sjc!directvdsl.com > Xref: news.baymountain.net comp.lang.python:151323 > To: python-list at python.org > Sender: python-list-admin at python.org > Precedence: bulk > List-Help: > List-Post: > List-Subscribe: , > > List-Id: General discussion list for the Python programming language > List-Unsubscribe: , > > List-Archive: > > when i start a button widget, it automatically fires the command? > > def HideNewClient(self, frame): > frame.configure(bd=0, width=0, height=0) > return > > pdb_btnSearch = Button(pdb_frmCommands, > text="Search", > relief=GROOVE, > font=("Tahoma", 10), > width=16, > command=self.HideNewClient(pdb_frmNewClient)) > > any help would greatly be appreciated. > > Adonis You don't pass paramenters to commands that you want to run when you click a button like that. All command wants is the name of the command you are going to run. If you need to pass an argument it is usual to get out the lambda, so something like this ought to work. pdb_btnSearch = Button(pdb_frmCommands, text="Search", relief=GROOVE, font=("Tahoma", 10), width=16, command=lambda s=self, arg=pdb_frmNewClient : s.HideNewClient(arg)) Laura Creighton From bkelley at wi.mit.edu Thu Mar 7 13:52:34 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 07 Mar 2002 13:52:34 -0500 Subject: win32com question using R com interface Message-ID: <3C87B6F2.9050500@wi.mit.edu> I have been trying to translate some visual basic code to python and have been running into a slight problem I am having some problems sending vectors or arrays across the interface. here is the VB code Dim x As StatConnector Dim i3(5) As Integer i3(1) = 5 i3(2) = 4 i3(3) = 3 i3(4) = 2 i3(5) = 1 Set x = New StatConnector x.Init ("R") x.SetSymbol "i3", i3 Here is the python code from win32com.client import Dispatch i3 = (5,4,3,2,1) x=Dispatch("StatConnectorSrv.StatConnector") x.Init("R") x.SetSymbol("i3", i3) This results in an error File "", line 2, in SetSymbol pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None) Now x.SetSymbol("i3", "foo") or x.SetSymbol("i3", 3.0) works just fine. So, the question is are the two codes equivalent or am I sending the wrong thing (the tuple) to the server? Any help would be appreciated. Brian Kelley Whitehead Institute for Biomedical Research From arturs at iidea.pl Fri Mar 22 06:31:54 2002 From: arturs at iidea.pl (Artur Skura) Date: Fri, 22 Mar 2002 11:31:54 +0000 (UTC) Subject: Sorting distionary by value References: Message-ID: Duncan Booth wrote: > Artur Skura wrote in > news:slrna9lqj1.9n1.arturs at aph.waw.pdi.net: >> Is there an idiom in Python as to sorting dictionary by value, >> not keys? I came up with some solutions which are so inefficient >> that I'm sure there must be a simple way. > How do you know they are inefficient? Have you profiled your application > and found this to be a bottleneck? No, and it seems the problem is not with sorting. I wanted to write a compact word counting script (well, in shell it can be done in a 5 lines or so), just for fun. and import string,sys a = string.split(open(sys.argv[1],'r').read()) known = [] times = 0 output = {} for i in a: if i not in known: for l in a: if l == i: times = times + 1 known.append(i) output[i] = times times = 0 items = [ (output[k], k) for k in output ] items.sort() items.reverse() items = [ (k, v) for (v, k) in items ] for k in items: print k[0], k[1] it seems it's slow not because of sorting... Regards, Artur -- http://www.wolneprogramy.org http://mf.gnome.pl From maurelius01 at hotmail.com Fri Mar 22 23:57:41 2002 From: maurelius01 at hotmail.com (Marc) Date: Fri, 22 Mar 2002 23:57:41 -0500 Subject: mutlifile inheritance problem simplified References: <9896e047.0203211303.741f695a@posting.google.com> <3C9BAB77.B4E17C65@hotmail.com> Message-ID: <3C9C0B45.E3C51B0C@hotmail.com> Aahz wrote: > > In article <3C9BAB77.B4E17C65 at hotmail.com>, > Marc wrote: > > > >I'm using Windows NT, Python 1.5.2, and IDLE 0.5 > > Try switching to Python 2.1.2 or 2.2; I'm sure that reload() has had > some changeds. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > "We should forget about small efficiencies, about 97% of the time. > Premature optimization is the root of all evil." --Knuth OK, I've just tried Python 2.2 and IDLE 0.8. Same problem. This really seems quite mysterious? I'm surprised that others haven't run into this. I'm sure I'm not the first person to use reload, or the first to inherit from a class into different files. Marc From calder at email.in.signature Sun Mar 3 17:35:44 2002 From: calder at email.in.signature (calder) Date: Sun, 3 Mar 2002 23:35:44 +0100 Subject: [newbie] Problem with os.system References: Message-ID: <1015194944.406831104@news.tpi.pl> "DarkCed" wrote: >I would like to run a program from a python script (a source for a >icecast server). >The program works, but a simple two-line script with os.system('ices') >does not. I get this message : >"syntax error near unexpected token". > >If I type "ices" in the same repertory, it works... >Shall I use another command to run my program ? > >Thanx >Ced You must be mistyping something... Your two-line script should look like this: import os os.system ('ices') And that's it. -- ************************** Calder [calder at box43.pl] [gg 2174530] ************************** From rogerb at rogerbinns.com Mon Mar 25 02:12:36 2002 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 24 Mar 2002 23:12:36 -0800 Subject: I imaplib reliable? References: Message-ID: > I'm just not sure if Python's imaplib has been war tested. When I last tried it about 6 months ago, I found it to be full of problems. In particular it pretty much just returned raw IMAP protocol strings for most operations. The user of the library then has to do far too much parsing work. If you want some examples, look in the IMAP spec for literals (where there is a number in squiggly brackets followed by that many bytes of data). Python's imaplib just returns that all to you, and you have to parse everything out. Given a valid imap implementation could put almost any data as literals (especially things like funky folder names), this makes working with imaplib very low level and tedious, and not much different than having to write it yourself. -- Roger From usenet at microtonal.co.uk Fri Mar 8 16:59:00 2002 From: usenet at microtonal.co.uk (Graham Breed) Date: Fri, 8 Mar 2002 21:59 +0000 (GMT Standard Time) Subject: Is current integer for-loop syntax a wart? References: Message-ID: Cromwell, Jeremy wrote: > PEP 276 (Simple Iterator for ints) and PEP 284 (Integer for-loops), > among > others, are written from the perspective that the current integer > for-loop > syntax > > for i in range(10): > > is a wart. Is this true? That is, where does the Python community > stand on > this issue? That's more than syntax. The "integer" bit is handled by the range builtin, which works fine outside of for loops. The PEPs seem to be getting round problems with range, not problems with for loops. So if we're strictly talking about for loops, > -Not a wart > This is the most pythonic way to write an integer for loop. I would > oppose > almost any change. In fact I'll go further -- for loops are one of the most beautiful features of the language, precisely because there's no special syntax for integers. Such an obvious idea, so many languages miss it. Now, the range() builtin I see as a minor wart. It certainly does look ugly for algorithms that require a closed set of integers to loop over. In the example above it works fine. If somebody can come up with a perfect range literal so be it. If not, indices() and inclusive() will do me. Graham From robinjim at earthlink.net Sun Mar 17 12:22:46 2002 From: robinjim at earthlink.net (robin and jim) Date: Sun, 17 Mar 2002 17:22:46 GMT Subject: new-style class initialization Message-ID: What is the correct way to write the following where the number of arguments to the initializer changes throughout the inheritance hierarchy? class A(object): def __init__(self, x): print "A's initializer called" def m(self): print "save A's data" class B(A): def __init__(self): print "B's initializer called"; super(B, self).__init__('B') def m(self): print "save B's data"; super(B, self).m() class C(A): def __init__(self): print "C's initializer called"; super(C, self).__init__('C') def m(self): print "save C's data"; super(C, self).m() class D(B, C): def __init__(self): print "D's initializer called"; super(D, self).__init__() def m(self): print "save D's data"; super(D, self).m() d = D() d.m() I have tried some permutations of defining __new__(), but obviously do not know what I'm doing. From bokr at oz.net Fri Mar 22 18:15:24 2002 From: bokr at oz.net (Bengt Richter) Date: 22 Mar 2002 23:15:24 GMT Subject: Begginers Guide - Exrcise. Help me, plz! References: <3C9B7A1E.451453BA@ccvcorp.com> Message-ID: On Fri, 22 Mar 2002 10:38:22 -0800, Jeff Shannon wrote: > > >Jim Dennis wrote: > >> Shouldn't all these (helpful) examples be using raw_input() rather >> than input(). Do we really want the new user to be implicitly and >> blindly using eval(raw_input())? > >Yes, they should. :) The calls to input() should, in this case, all be >replaced by int(raw_input()), and optionally wrapped in a try/except and while >loop, so that the program can prompt again if a non-numeric value is given. I >almost mentioned this in my earlier response, but decided not to overly confuse >the O.P. -- this essentially doubles the code size. > >while sum < sum_stop: > num = None > while num is None: > try: > num = int(raw_input("Please enter the number:")) > except ValueError: > print "That's not a number. Try again!" > sum = sum + num # could also be sum += num > print "The sum is", sum >print "and it is > 100" > >Alternatively, instead of setting num to None and watching for that to change, >we could use a 'while 1: try: ... except: ... else: break' structure. > Alternatively again, we could factor out the function of getting a number, to keep that concept bite sized (and also changing a few details ;-) e.g.: ------ def get_num(): while 1: try: return int(raw_input("Please enter an integer: ")) except ValueError: print "That's not a integer. Try again!" sum = 0; sum_stop = 100 while sum < sum_stop: sum += get_num() print "The sum is", sum print "... and it is >= %d" % sum_stop ------ Please enter an integer: 2. That's not a integer. Try again! Please enter an integer: 2 The sum is 2 Please enter an integer: -5 The sum is -3 Please enter an integer: 99 The sum is 96 Please enter an integer: 3 The sum is 99 Please enter an integer: 1 The sum is 100 ... and it is >= 100 Regards, Bengt Richter From James_Althoff at i2.com Tue Mar 5 17:16:58 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 14:16:58 -0800 Subject: Status of PEP's? Message-ID: [Samuele Pedroni] > Smalltalk try to deal with such > corners compesating > vaguely mimicking english: > > 1 to: 20 do: [...]. > 10 timesRepeat: [...]. > > These forms in some sense (my > very personal impression) > try to hide that 1 is an object here, > not to underline that. Interesting observation. But actually, we very much chose those forms to "underline" not to "hide" the fact that numbers are first-class objects in Smalltalk (as they are also in Python). A Smalltalker sees "10 timesRepeat: [...]" and thinks "send the timesRepeat message to (i.e., invoke the method on) the integer object 10 passing along the block [...] as an argument in order to execute the block 10 times". Smalltalkers delight in seeing everything interpreted as messages sent to (i.e., methods invoked on) objects. It was a deliberate design decision to *not* add special syntax for control structures specifically so that control structures would be seen as "objects responding to messages/methods" just like everything else. We wanted a language whereby *everything* could be interpreted as "objects responding to messages/methods". > > What about "for i in 10" > from this angle of view ? I like the idea of a for-loop getting an iterator from the target and then iterating on the produced values. And, as PEP 276 says, it seems simple, useful, and practical to have iter(n) produce 0,1,...,n-1 (particularly in for-loops). I like the idea of integers being first-class objects. I like the idea of integers having methods. I don't see any reason why one should pretend that integers aren't first-class objects. Or why one should try to hide the fact that class int has methods. But then, I'm hopelessly indoctrinated -- although, I'm perfectly content to write abs(n) (just in case any -bots that shall remain nameless are listening) . Jim From kedai at kedai.com.my Tue Mar 26 00:43:31 2002 From: kedai at kedai.com.my (kedai) Date: 25 Mar 2002 21:43:31 -0800 Subject: turning a python script to windows service Message-ID: hi i've a simple script that just prints time.time(). how can i turn it to a windows service? do i need to do anythng special, apart from subclassing from win32serviceutil.ServiceFramework and defining SvcDoRun, SvcStop, etc. (the o'reilly python for win32 does help a bit, but i think i need more prodding :P) i have turned the sript to run as a service with srvany, but it never prints anything, or do anything useful. but when run in debug mode, it does print. i may be missing something obvious here. the gist of the script: import time while 1: print time.time(time.ctime()) time.sleep(10) From gh_pythonlist at gmx.de Fri Mar 8 19:56:14 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 9 Mar 2002 01:56:14 +0100 Subject: broken pipes, import errors (LONG, INVOLVED) In-Reply-To: <20020309001354.GH4569@isis.gerrietts.net> References: <20020309001354.GH4569@isis.gerrietts.net> Message-ID: <20020309005614.GA1985@lilith.hqd-internal> Le 08/03/02 ? 16:13, Geoff Gerrietts ?crivit: > [...] > exec statement > object = eval(object_nm) > [...] If you're really using these versions of exec and eval, you risk overwriting things in the current local and global namespace. You could try to provide explicit namespaces to exec and eval. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 3.8 ?C Wind: 1.2 m/s From nospam at bigfoot.com Wed Mar 27 14:49:36 2002 From: nospam at bigfoot.com (Gillou) Date: Wed, 27 Mar 2002 20:49:36 +0100 Subject: Can I use python code to login a website? References: Message-ID: try this scheme with urllib... f = urllib.urlopen('http://myname:mypassword at somehost.com/...') "newgene" a ?crit dans le message news: a50631f6.0203262119.3b9db7a4 at posting.google.com... > Hi, group, > > I am wondering if possible to use python code to login a website > need username and password, like mail.yahoo.com. Another type of > website is poping up a authorization box asking for username and > password instead of a input form within the webpage. > > Thanks you in advance. > > Newgene From tanzer at swing.co.at Fri Mar 8 10:45:30 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Fri, 08 Mar 2002 16:45:30 +0100 Subject: Order of constructor/destructor invocation In-Reply-To: Your message of "Fri, 08 Mar 2002 11:59:57 +0100." <3C8899AD.78B134DE@spam.nada.kth.se> Message-ID: Bj?rn Lindberg wrote: > > Agreed. I relied on that. > > > > > In this example s1 will be constructed first followed by s2. > > > > And here I am wary. Does the standard prescribe this? For normal > > expressions at least, you can't rely on evaluation order. But then, in > > comma separated expressions you can. So maybe this is safe after all. > > I believe it is, but I'm not certain. As you say, evaluation order for > comma separated expressions are defined. I'd have to ask someone with a > copy of the standard handy for this. OTOH, evaluation order for the arguments of a call is not defined, IIRC. To be safe, I wouldn't rely on the destruction order of things like Sentry s1, s2; Nor-do-I-have-to-as-a-happy-Python-user-ly yr's, -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From python at rcn.com Mon Mar 25 07:52:12 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 25 Mar 2002 07:52:12 -0500 Subject: list comprehension question References: <5.1.0.14.2.20020324115311.0457dbb8@202.95.131.154> Message-ID: "Tripp Scott" wrote in message news:mailman.1017031538.14132.python-list at python.org... > At 25/03/2002 07:37, brueckd at tbye.com wrote: > thanks for the tip. actually, the essence of what i wanted to > ask was: "can that SOMETHING be a list of more than one elements > which will be _flatly_ added to the result list." as another > example, can i generate this list > > [1,1 2,2,2, 3,3,3,3, 4,4] I don't see the pattern. I presume you mean: [1,1, 2,2,2, 3,3,3,3, 4,4,4,4,4 ] > > with a list comprehension that contains one 'for' clause? I think you are asking for a general purpose solution to the problem of using list comprehensions in an 'extend' rather than 'append' mode. The general purpose technique is to build it unflattened and then wrap it with flatten function. Applying that general technique to your specific example is easy: >>> def flatten( lol ): ans = [] map( ans.extend, lol ) return ans >>> flatten( [[i]*(i+1) for i in range(1,5)] ) [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4] Hope this helps you train your pet Python, Raymond Hettinger From skip at pobox.com Tue Mar 19 14:19:38 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 19 Mar 2002 13:19:38 -0600 Subject: Python-2.2.1c1 Build Problems on Linux and AIX. In-Reply-To: References: Message-ID: <15511.36682.256527.232785@12-248-41-177.client.attbi.com> Ralph> With Python-2.2.1c1, I find `make test' fails on my old version Ralph> of Linux/x86 and it fails to build on an also old version of AIX. Ralph> Should I go straight to SourceForge and fill in bug forms or do Ralph> people tend to discuss the problems here first? Ralph> I can see the problem with the AIX build. Linux SIGSEGVs in Ralph> test_calendar on a call to strftime. Ralph, The strftime call in calendar.py is a bit abusive, so it's not entirely surprising to me that you're seeing problems. This test succeeds for me on my Mandrake system. Can you run the test_calendar.py script manually and submit a SF bug report (assign it to "montanaro")? A debugger traceback would be helpful as well. Does the AIX version of strftime support %a, %A, %b and %B formats? Thx, -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From aahz at pythoncraft.com Thu Mar 28 22:28:06 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2002 22:28:06 -0500 Subject: Simple threaded web-server based on BaseHTTPServer? References: <3C5976D0.A3A63A46@stroeder.com> <3CA36D8D.1080204@stroeder.com> Message-ID: In article <3CA36D8D.1080204 at stroeder.com>, =?ISO-8859-1?Q?Michael_Str=F6der?= wrote: >Aahz Maruch wrote: >> In article <3C5976D0.A3A63A46 at stroeder.com>, >> Michael =?iso-8859-1?Q?Str=F6der?= wrote: >>> >>>In my case (http://web2ldap.de) I'm using threaded BaseHTTPServer >>>but I'm not really happy with it. Especially since I have to use a >>>module-wide lock to serialize calls into python-ldap module because >>>the underlying OpenLDAP libs are not thread-safe. This can block the >>>whole thing and killing threads on e.g. Linux is not possible. >>>Having a single-process asyncore design would probably make things >>>easier. >> >> Add another thread to serialize things instead of using a module-wide >> lock. > >I really wonder how this helps if the call into the underlying module really >blocks. BTW: In opposite to my original statement an asyncore design would >also not help since the underlying OpenLDAP lib is not designed that way. I made my suggestion in the context of assuming that your server threads can continue to interact with the user while waiting for the LDAP call to complete. One possible option would be to have your server's LDAP thread call out to another LDAP server that you write to fork off processes (that's assuming the LDAP library is concurrent across multiple processes, of course). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From tejarex at yahoo.com Sat Mar 9 02:24:17 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 09 Mar 2002 07:24:17 GMT Subject: short-circuit behavior anomaly? References: Message-ID: "logosity" wrote in message news:mailman.1015657336.24581.python-list at python.org... > Hi, > > I was working through this tutorial: > http://gnosis.cx/publish/programming/charming_python_13.txt > > Which shows the statements in the following functions (imp and fn) as > equivalent: > > def pr(s): print s By default, functions return None, which is false. For this function to work right in context below, you must return a true value, such as 1. If you have copied from tutorial accurately, it is incorrect and you should report bug. > def imp(): > if x == 1: pr('one') > elif x == 2: pr('two') > else: pr('other') > > def fn(): > (x == 1 and pr('one')) \ > or (x == 2 and pr('two')) \ > or (pr('other')) When pr return None, no 'short-circuit occurs and pr('other') is called regardless of value of x. I personally use and/or to simulate conditional expressions, but one *must* be careful when doing so. Terry J. Reedy From mt_horeb at yahoo.com Fri Mar 29 08:00:17 2002 From: mt_horeb at yahoo.com (Sloth) Date: 29 Mar 2002 05:00:17 -0800 Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> <3CA3D86A.7080806@yahoo.com> Message-ID: <67abb823.0203290500.3a3a7da1@posting.google.com> Thanks for the feedback re. Apache. I appreciate it! The reason that I'd like to find a native Python script is as follows: I started to build a proof of concept Web app for a company that queried a customer database and generated search results. The company loved it and wanted to have me create a few "pilots" for salespeople. If I can simply have them install Python and install an additional module or two, it would be easier than asking non-technical sales folks to also install Apache. I agree, Apache is very painless. On the other hand, less is more in this scenario and, frankly, now I'm just being stubborn and trying to get Python to act as its own CGI server. Has anyone had luck making this work in a Window 9x environment? Thanks! Roger wrote in message news:<3CA3D86A.7080806 at yahoo.com>... > With only a year+ of experience, I second the motion for Apache. I > started with Microsoft PWS, tried a couple of other "simple" solutions > and wound up using Apache. The configuration files tend to look > overwhelming as there are a lot of choices, but for the most part the > defaults are what you want. > > I would also suggest you take a look at Webware's WebKit at > http://webware.sourceforge.net/. It provides an object-oriented > framework for your web applications and makes DEBUGGING your scripts > easy (which is what you will need). > > I also use MySQL for a database, and MySQLfront as a gui interface to > MySQL. All of these are free and all have Linux versions (with the > exception of MySQLfront). > > Roger > > > Gerhard H?ring wrote: > > > Sloth wrote in comp.lang.python: > > > >>I've looked at Apache, Xitami, Zope, Medusa, et. al and think they are > >>wonderful applications. On the other hand, they are overkill for what > >>I want to be able to do - have Python start a CGI server, serve a > >>page, get form data, get data from a database, and display dynamic > >>content. I don't need anything industrial strength, just something > >>that can handle a single user. > >> > > > > Maybe it's just me, but I often have difficulties to understand the > > point of the "overkill" argument. > > > > > >>Any thoughts? I sincerely appreciate everyone's help! > >> > > > > If you can spare 5 megs of RAM and a little disk space, just go for > > Apache (or Xitami, or whatever). When you're running the webserver and > > are not using it currently, it'll be swapped out anyway, so why > > bother? > > > > It's a myth that Apache is complex to get running, here's what you'd > > need to do on Windows: > > > > 1) Install Python > > 2) Install Apache > > 3) edit etc/httpd.conf and add the line > > > > ScriptInterpreterSource Registry > > > > at the end of the file. > > > > 4) Write your Python CGI scripts in cgi-bin and name them .py > > > > Gerhard > > From writeson at earthlink.net Tue Mar 19 14:42:07 2002 From: writeson at earthlink.net (Doug Farrell) Date: 19 Mar 2002 11:42:07 -0800 Subject: py2exe 0.3.1 hangs trying to remove build under Win98SE Message-ID: <88bc63c6.0203191142.1926b089@posting.google.com> Hi all, I'm trying to package up a Python2.2 program that uses wxPython with the py2exe system and I'm having no luck. I open up a DOS window (I'm running Win98SE) and run the following command line: python pyexe.py myscript.py The pyexe.py setup script is something I got from ASPN that is a generalized setup script for this purpose, I've listed it below: from distutils.core import setup import sys, os, py2exe name = sys.argv[1] sys.argv[1] = 'py2exe' sys.path.append(os.path.dirname(os.path.abspath(name))) setup(name=name[:-3], scripts=[name]) At the end of processing, I get the message: removing 'build\bdist.win32\winexe' (and everything under it) At this point the DOS window hangs and never returns. In fact I have trouble killing it with the Task Manager. In addition, at this point Windows Explorer no longer runs, it comes up, but the window frame is empty. I have to reboot my machine to get full control back. The script does create the dist directory where I expect it and there is a myscript.exe and accompanying DLL's and such there. But if I try to run that program, a DOS window comes up with various tracebacks in it about not being able to import various modules. The myscript.py file runs fine in the interpreter. Anyone have any idea what's going on here? I'm runnig py2exe version 0.3.1, so I have the latest. Thanks for your help, Doug From philh at comuno.freeserve.co.uk Fri Mar 29 12:44:53 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 29 Mar 2002 17:44:53 +0000 Subject: optional pass? (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26)) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA35C49.31397789@ndh.net> Message-ID: On Fri, 29 Mar 2002 12:45:50 +0000 (UTC), Alexandre Fayolle wrote: >In article , phil hunt wrote: >> True, but i still have to remove the passes when i want to implement >> the class. > >Why don't you put a docstring ? It will help you document precisely what >you had in mind when writing the class, and you can keep it when you >actually write the code. 3 reasons. (1) Sometimes the functionality of the method is too obvious to require one, e.g.: class Key: def encrypt(self, plainText): def decrypt(self, cipherText): I would really hope this is obvious enough not to need one. (2) Also, I often put a big comment for the whole class, rather than scatter little comments for each method, e.g.: """*** Foo does blah blah blah rest of long comment goes in here ***""" class Foo: def method1(self): def method2(self): def method3(self): def method4(self): def method5(self): (3) sometimes the pass-less code isn't a function definition, e.g.: if a == "one": do_something() elif a == "two": elif a == "three": else: Here I've only implemented 1 of the 4 possibilities. I want to be able to run my code to test what I've written, before implementing the other 3. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From nospam at mega-nerd.com Sun Mar 10 22:01:54 2002 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Mon, 11 Mar 2002 03:01:54 GMT Subject: Translating Python to C (was Re: Modulo operator : differences between C and Python) References: <3C8BE537.74E55963@mega-nerd.com> Message-ID: <3C8C1E21.F9120C2B@mega-nerd.com> Courageous wrote: > > >> Just recently I prototyped a relatively complex algorithm in Python > >> before converting it to C. > > I'm curious about your experiences. I did something myself recently, > creating a fairly sophisticated prototype in Python and then implemented > it in C++. Given that I had all the algorithms worked out and thoroughly > debugged, it was astounding to me how difficult it was to get properly > translated and then validated. It took literally 3 times as long or longer > to get the C++ version implemented and provably functional, this in spite > of the design time work being included in what it took to do the Python > implementation. My experience was that once I had it working and validated in Python converting to C was pretty trival. The validation I had done in Python allowed me to find the problem in the C version pretty quickly. 80% of the whole process was getting the Python code working. > Programming in C++ genuinely depresses me. Thats why I try to avoid C++ :-). > And I'm an old veteran. I've been using it since the days of C Front, if > anyone around happens to know what that means. :-) I never used C Front but did spend a number of years (1990-1995) where C++ was my main language. Nowadays I only use C++ when I really, REALLY *REALLY* need C++ features. The rest is split between C and Python. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ "Only wimps use tape backup: *real* men just upload their important stuff on FTP, and let the rest of the world mirror it ;)" -- Linus Torvalds From hfoffani at yahoo.com Sun Mar 24 09:48:58 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Sun, 24 Mar 2002 15:48:58 +0100 Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> <11e94203.0203232201.4dde9883@posting.google.com> <20020324081829.193$iP@news.newsreader.com> Message-ID: <20020324094900.445$t3@news.newsreader.com> I wrote: > Polish the page with HTML Tidy first, then strip all script code tags, > parse the resulting HTML to catch the rows you're interested in > and save them into a DB. Ups... There is no need to strip client-side script code from the page. I was confused by a problem with another tool I used several months ago. I tried htmllib.HTMLParser(...) from Python 2.2 and works as expected. Regards, -Hernan From guido at python.org Sun Mar 31 17:52:00 2002 From: guido at python.org (Guido van Rossum) Date: Sun, 31 Mar 2002 22:52:00 GMT Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: <3CA62CD8.6ABD44D0@accessforall.nl> <3CA6F012.E2631003@accessforall.nl> Message-ID: <3CA79401.CFA41B65@python.org> "Martin v. Loewis" wrote: > > Ype Kingma writes: > > > I'd like to know whether this PEP merging all numeric types would also merge > > the bool type into its evt. hierarchy. > > See for yourself: > > http://python.sourceforge.net/peps/pep-0228.html > http://python.sourceforge.net/peps/pep-0242.html But see also my comments on these two in http://www.python.org/doc/essays/pepparade.html; neither PEP is likely to have any effect on Python's future. --Guido van Rossum (home page: http://www.python.org/~guido/) From morton at dennisinter.com Sun Mar 10 13:59:51 2002 From: morton at dennisinter.com (damien morton) Date: 10 Mar 2002 10:59:51 -0800 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> Message-ID: <4abd9ce7.0203101059.444f1ec1@posting.google.com> Tim Roberts wrote in message news:... > It would be a clear and unambiguous expression _if_ the "in" operator was a > substring search operator, but it is not. It is a set membership operator. > It works EXACTLY the same way on all sequence types: the right-hand operand > is a sequence, and the left-hand operand is something that can be an > element of that sequence type. You are suggesting an unorthogonal change > just because it is easier to type than: > > 'the quick brown fox'.find('fox') > > No. That is NOT a good reason to change a language in an inconsistent way. The 'in' operator is now a verb that can be defined to mean pretty much any function with two arguments. It cant be a set membership operator because python doesnt have sets. The issue at stake is that its meaning should be well understood. Strings are like sequences in that their individual elements (characters ONLY) can be accessed as a sequence, but there are important differences in the kinds of things people want to do with strings. >From the persepective of an english speaker, the the string 'fox' is IN the string 'the quick brown fox'. Under the covers, the IN operator is defined as the __contains__ function. Clearly, the string 'the quick brown fox' CONTAINS the string 'fox'. I think the verb IN means something slightly different for strings than it does for sequences and dicts. Check this out: ('fox' in 'the quick brown fox') ('the quick brown fox'.find('fox') != -1) Which of these expressions is clearer, more intuitive and convenient? I appreciate your thoughtfull comments, and I agree with you that inconsistency should be avoided, but I would assert that this should not be at the cost of intuitiveness, convenience and clarity. From kk71878 at hotmail.com Fri Mar 8 15:12:29 2002 From: kk71878 at hotmail.com (Kevin Killingsworth) Date: 8 Mar 2002 12:12:29 -0800 Subject: failed assert when importing a boost.python-created library from an embedded python interpreter Message-ID: <7f678ff6.0203081212.4c2e4cd6@posting.google.com> Hello, I'm very close to doing something very cool (IMO), but I've got one last roadblock before I can get there. First off, I've got a C++ program that has an embedded Python interpreter. I want the Python interpreter to share the same datamodel as the C++ program itself, so I created a Boost.python (www.boost.org) library out of my datamodel. It loads perfectly from a command-line python interpreter, but not the one that is embedded inside my program. It comes up with this: classinfo.cxx:37: class_descriptor::class_descriptor(const char*, unsigned int, void (*)(object*)): Assertion `!find_class(class_name)' failed. I can import sys and such, but not my own library (perhaps because it's not builtin?) I know I'm probably just missing a step, but I have looked through the docs and can't find it. Can anyone help? Thanks, --Kevin Killingsworth From lac at strakt.com Sat Mar 9 13:35:29 2002 From: lac at strakt.com (Laura Creighton) Date: Sat, 09 Mar 2002 19:35:29 +0100 Subject: Is current integer for-loop syntax a wart? In-Reply-To: Message from Michael Chermside of "Mon, 08 Apr 2002 14:33:04 EDT." Message-ID: <200203091835.g29IZTtB024981@ratthing-b246.strakt.com> > The second complain is significant (I think). That is the following: > for i in range(len(mySequence)): > This is something that I use all the time, and more relevently it is > something that BEGINNERS use all the time. Interesting. Do you mean 'beginners who have never programmed before' or 'beginners who have lots of habits from other languages'. I need actual hard index numbers like this rather rarely - mostly as arguments to the Tkinter grid window manager to tell it which column to grid my widget. And even then I find it easier to use zip. There are some people who really, really, really hate using while 1: break on some condition they go crazy actually trying to calculate all the times when they should be in a loop rather than the more straightforward calculation of when it is time to leave. Since you mention Java, I wonder if overcoming this habit is a common labour for Java programmers that are learning python - moreso than those who have come from other languages. It would be fun to run some tests. I can't provide any datapoints -- it's the Smalltalk I have to take out of my python. I liked PEP 276 because I like the idea of integer iteration. But I have deep suspicions that this indicates that there is something wrong with me, not that there is something wrong with the people who do not like the idea at all. Laura Creighton From sjmachin at lexicon.net Thu Mar 28 21:29:15 2002 From: sjmachin at lexicon.net (John Machin) Date: 28 Mar 2002 18:29:15 -0800 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: "Steve Holden" wrote in message news:... > "John Machin" wrote ... > > philh at comuno.freeserve.co.uk (phil hunt) wrote in message > news:... > > > On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen > wrote: > > > >Jim Dennis wrote: > > > >> freq = {} > > > >> if word in freq: freq[word] += 1 > > > >> else: freq[word] = > 1 > > > > >Something like freq[word] = freq.get(word, 0) + 1 > > > > > > IIRC in Awk you can just say: freq[word] ++ and it works > > > correctly even when there is no pre-existing index of word in freq. > > > > > > IMO it's a pity Python isn't like that. > > > > Python *could* be made like that with the explict dict() constructor > > ... something like: > > > > freq = dict(default=0) > > ... > > freq[word] += 1 > > This was a feature of the Icon language. But Icon had no explicit literal > representation for dictionaries (or tables, as I think they were called) as > far as I can remember, so it was easy to make the default value an argument > to a constructor function. It's not obvious how you could indicate the > default without calling a method. > See above: freq = dict(default=0) I think that I'm proposing indicating the default by having a keyword argument ("default")on the new-in-2.2 constructor ("dict"); what do you think that I meant? From wmistar at yahoo.com Tue Mar 19 00:18:54 2002 From: wmistar at yahoo.com (Will G.) Date: 18 Mar 2002 21:18:54 -0800 Subject: Python calling C with callback to Python - crash! References: Message-ID: Martin von Loewis wrote in message news:... > wmistar at yahoo.com (Will G.) writes: > > > Appreciate any help! > > When you run the program in a debugger, what does the debugger say > where it crashes? Since I don't have the debug version of python21.dll, the VStudio debugger simply stated that the crash is in python21.dll. From peter at engcorp.com Thu Mar 21 07:52:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Mar 2002 07:52:00 -0500 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C9991C0.4080102@pobox.com> Message-ID: <3C99D770.57345464@engcorp.com> Ahmed Moustafa wrote: > > Peter Hansen wrote: > > > > Communication skills are, first and foremost, the thing I > > look for in hiring. [...] Next are adaptability [...] > > Design skills are useful. Debugging skills are very valuable [...] > > Peter, what do you think about qualifying problem sets like what > arsDigita had? I think that's an interesting sounding name for something. What is it? I'll assume (without taking the time to try to figure it out... care to tell me?) that those are basically little exams which they use to judge candidates. If so, you already know my answer: as I said, specific knowledge of language syntax is secondary, since I'm more concerned about finding people with the skills I mentioned. If arsDigita (you'd think a company would know enough not to put the word "arse" in their name...) has tests which evaluate communication skills, flexibility and ability to learn new things, and design and debugging skills, then I think their qualifying problem sets are a very good idea... -Peter From gminick at hacker.pl Tue Mar 12 12:12:00 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Tue, 12 Mar 2002 17:12:00 +0000 (UTC) Subject: How do you conver output of "popen('ls')" to a list? References: <3C737245.BC5D7164@macrozon.net> Message-ID: ** Since micro$oft is stupid it doesn't mean ** that you should be stupid too - do NOT toppost. Dnia Wed, 20 Feb 2002 10:54:13 +0100, husam napisa?(a): >thanks for reply. --------- #!/usr/local/bin/python2.2 import os blah = os.popen('ls').read() i,n,tabl,blen=0,0,[],len(blah) while i < blen: tmp = i i = blah.index('\n', i) tabl.append(blah[tmp:i]) n+=1 i+=1 for a in tabl: print a --------- ...just because readlines() forgot to cut '\n' ;)) -- [ Wojtek gminick Walczak ][ http://hacker.pl/gminick/ ] [ gminick (at) hacker.pl ][ gminick (at) klub.chip.pl ] From dkuhlman at rexx.com Tue Mar 5 14:30:24 2002 From: dkuhlman at rexx.com (Dave Kuhlman) Date: 5 Mar 2002 13:30:24 -0600 Subject: Text Search Engine that works with Python References: Message-ID: <1015357223.673257@rexx.com> Here is a related question -- Is there a search program for structured text files, in particular something that searches XML files. I know about sgrep, and I've made Python wrappers for it. Are their an y others? You can find sgrep at http://www.cs.helsinki.fi/u/jjaakkol/sgrep.html. My Python wrappers for sgrep are at http://www.rexx.com/~dkuhlman. - Dave Doug Farrell wrote: > > Hi all, > > I'm wondering if anyone knows of a text search engine that works with > Python? What I'm looking for specifically is something that will compress > the text and still allow searches and retrievals that can be exact matches > or proximity based. The text I want to compress and search is huge (70 megs) > and should compress down to half, not including any index files that might > be required by the search engine. Anyone know of anything like this or any > ideas? > > Thanks, > Doug Farrell > > -- Dave Kuhlman dkuhlman at rexx.com http://www.rexx.com/~dkuhlman -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 80,000 Newsgroups - 16 Different Servers! =----- From brobbins333 at shaw.ca Sat Mar 9 17:59:13 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Sat, 09 Mar 2002 22:59:13 GMT Subject: round() function strange behaviour Message-ID: <3c8a9261.149508269@news> the round() function will sometimes return a predictable result, as in: round(45.67891, 2) >>> 45.68 but sometimes it will return something like: round(56.78923, 2) >>> 56.789999999999999 2.1 and 2.2 both behave this way on two different (Windows) computers. What's going on here? Bruce Robbins From owen at xastrox.xwashingtonx.edu.invalid Fri Mar 8 15:58:20 2002 From: owen at xastrox.xwashingtonx.edu.invalid (Russell E. Owen) Date: Fri, 08 Mar 2002 12:58:20 -0800 Subject: List of Dictionaries References: <14dc40e2.0203071559.5e3d4550@posting.google.com> Message-ID: In article <14dc40e2.0203071559.5e3d4550 at posting.google.com>, lenny_self at hotmail.com (Lenny Self) wrote: >I am having a problem I was hoping someone might be able to help me >with. I am attempting to append several dictionaries to a list for >further processing, however I am seeing some rather odd behavior. > >When I add the first dictionary element to the list all is well. When >I add the second element to the list both the first and second element >reference the second dictionary that was added. The behavior >continues whenever I add an element. So, if I add, say 50 >dictionaries, all of the listes elements reference the last dictionary >I added.... My guess is that mail.getData() is returning a reference to a dictionary it uses internally, rather than returning a copy of that dictionary. Hence you end up with multiple references to the same dictionary. Usually, whenever I return a list, dictionary or other mutable application, I return a copy to avoid this problem.(In some situations this is may be appropriate or impractical, but that usually indicates poor class design - the contents of an object should usually remain private). If you cannot or prefer not to change the application returning the data, then change the calling program to make a copy of the dicationary before using it. -- Russell -- Return owen address astro garbled washington in header edu From offer at sgi.com Mon Mar 25 16:33:49 2002 From: offer at sgi.com (Nhi Vanye) Date: 25 Mar 2002 21:33:49 GMT Subject: Porting a Python app to IRIX -- need help References: Message-ID: $ from jody at adsl-216-62-149-210.dsl.hstntx.swbell.net -#190497 | sed "1,$s/^/> /" > > >"Paul F. Dubois" writes: > >> I am trying to get a Python-based app running on an SGI running IRIX 6.5. I >> am running into a problem involving some objects being compiled "n32" and >> others "o32". The linker refuses to link them. >> >> I got pretty far by setting environment variable CC to "cc" but then it >> complained that the X11 library is o32. Can an SGI person tell me whether >> o32 or n32 is "normal" and what I tell the compiler to be sure I get that? >> > >To force the compilers and linkers to use only one ABI set the >environment variable SGI_ABI for example: > >setenv SGI_ABI "-n32" This doesn't always work (for example you don't appear to be able to do "-n32 -mips3" to guarantee building mips3 on a mips4 platform. Other tricks I've used in the past (for other projects) is to con autoconf by running. ./configure --x-libraries=/usr/lib32 It might work for python, I haven't tested it. Anyway, back to the question, n32 is "normal", you'll get much better performance from the compilers, and all the system applications are n32 (which means you wont need to have two copies of libc in memory) >Jody Winston richard. -- Richard Offer Technical Lead, Trust Technology. "Specialization is for insects" __________________________________________http://reality.sgi.com/offer/ From michael at amtec.com Wed Mar 27 12:53:30 2002 From: michael at amtec.com (Michael Saunders) Date: Wed, 27 Mar 2002 09:53:30 -0800 Subject: Segregating Interpreter Sessions. Message-ID: <3CA2071A.BBF576AE@amtec.com> I have a C application embedding the python interpreter in which I would like to execute python commands. I would like the set of commands to be executed in it's own interpreter. My use of the code looks something like this (error handling left out): /* initialize python somewhere at the beginning of my C application */ Py_Initialize(); ... /* * somewhere in the middle of my C application * execute some python code in it's own interpreter */ PyThreadState *Interpreter = Py_NewInterpreter(); PyRun_SimpleFile(PythonFile, PythonFileName); Py_EndInterpreter(Interpreter); ... /* cleanup python somewhere at the end of my C application */ Py_Finalized(); My application is not using threads but after reading the documentation it appeared that using Py_NewInterpreter() was the correct way to create a "nearly" private area to run python code. When I get to the Py_Finalized() code I get the following fatal error from Python: Fatal Python error: PyThreadState_Get: no current thread Abort(coredump) Why am I getting this? Do I need to do more thread initialization even though I am not using threads? Should I be using some other function to create a separate interpreter environment? If so how do I tell PyRun_SimpleFile to execute in that environment. Thanks, Michael From dswegen at software.plasmon.com Tue Mar 19 07:51:47 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Tue, 19 Mar 2002 12:51:47 +0000 Subject: #define equivalents and config files In-Reply-To: References: Message-ID: <20020319125147.GE19059@software.plasmon> On Tue, Mar 19, 2002 at 01:00:40PM +0100, Gillou wrote: > There's no python preprocessor. > You can make "safe" config files for simple values (numbers, strings, simple > lists) with the ConfigParser standard package. > It's use and API are described in the standard Python doc. > That looks exactly like what I'm looking for. Cheers! Dave > "Dave Swegen" a ?crit dans le message news: > mailman.1016530410.32451.python-list at python.org... > > Is there a pythonic way of doing something similiar to Cs #define? I'd > > like to have what essentially is a header files with easily modifiable > > values (these will then be used to give default attribute values to > > various classes). Or are globals the only way to go? > > > > Cheers > > Dave > > From bokr at oz.net Wed Mar 13 15:20:26 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Mar 2002 20:20:26 GMT Subject: Question about scientific calculations in Python References: Message-ID: On Tue, 12 Mar 2002 22:15:43 -0700, "Andrew Dalke" wrote: [... good optimization advice, nicely elaborating the idea of precomputing ...] >If your lists are really long (O(100,000) or more?) then you might find >that the append starts taking too long -- append is asymptotically O(n**n) whoa! can that be true? I hope not. It is very cheap to tie a singly linked list into a circle and point to the last node when pointing to the list as a whole. Then append cost should be independent of length (other than indirect effects from memory allocation hiccups). Note that accessing the first element is just one indirection from the last, so a simple adjustment to the base pointer after an append makes it into a prepend. If it's doubly linked, appending should already be constant time. Regards, Bengt Richter From cliechti at gmx.net Sat Mar 2 15:14:43 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Mar 2002 21:14:43 +0100 Subject: Possible to fake object type? References: <3c80e76b@nntp.server.uni-frankfurt.de> <3c80fb6d@nntp.server.uni-frankfurt.de> <3c812217@nntp.server.uni-frankfurt.de> Message-ID: Michael 'Mickey' Lauer wrote in news:3c812217 at nntp.server.uni-frankfurt.de: >> def __getattr__(self, name): try: >> return self.__dict__[name] >> except NameError: return getattr(gtk.HandleBox, name) > > This is basically the same as I have now. But the thing is: > __getattr__ only gets called when the attribute _doesn't_ exist, you're right - i thought this has changed in py 2.2 but i never used it that way. maybe you could replace your classes __dict__ with an empty one so that __getattr__ get called? -- Chris From mlh at vier.idi.ntnu.no Tue Mar 19 18:59:02 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 19 Mar 2002 23:59:02 +0000 (UTC) Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy References: Message-ID: In article , Fredrik Lundh wrote: >Magnus Lie Hetland wrote: >> >the original code used Server -- after all, the object is >> >representing a remote server. >> >> Well, that's one way of seeing it; but it *is* an xmlrpc *client*, no? > >no, it's a client support class. your program is the client. Point taken. > -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From mhammond at skippinet.com.au Tue Mar 26 01:26:41 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 26 Mar 2002 06:26:41 GMT Subject: turning a python script to windows service References: Message-ID: <3CA014BC.6090204@skippinet.com.au> kedai wrote: > hi > i've a simple script that just prints time.time(). how can i turn it > to a windows service? > > do i need to do anythng special, apart from subclassing from > win32serviceutil.ServiceFramework and defining SvcDoRun, SvcStop, etc. > (the o'reilly python for win32 does help a bit, but i think i need > more prodding :P) > > i have turned the sript to run as a service with srvany, but it never > prints anything, or do anything useful. but when run in debug mode, > it does print. When run as a service, the print statements go nowhere useful - they run in the background. Try looking up info in win32traceutil - this will allow you to see your print statement when running as a service. Mark. From philh at comuno.freeserve.co.uk Fri Mar 8 12:01:40 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 8 Mar 2002 17:01:40 +0000 Subject: PEP 284, Integer for-loops References: <7x8z946jsq.fsf@ruckus.brouhaha.com> Message-ID: On 07 Mar 2002 15:27:01 -0800, Paul Rubin wrote: >Courageous writes: >> >This syntax could easily be extend, to allow a step other than 1: >> > >> > for i = 1 to 10 step 3: >> >> Or: >> >> for i = 10 to 1 step -1: > >This is fine. > >> Further, in ranges which step from high to low, the step can be >> inferred. > >This doesn't sound good. Suppose you say > > for i = a to b: > >where you don't know at compile time the values of a and b. >Do you really want it to count backwards if b < a? I usually wouldn't. Nor would I. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From martin at v.loewis.de Fri Mar 29 18:04:27 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 00:04:27 +0100 Subject: Where's the "news" section on python.org? References: <496p8.71$l%4.11431@ozemail.com.au> Message-ID: "Chris Wright" writes: > It seems that the "News" section on python.org has vanished from my > screen... The ANNOUNCEMENTS block is still there. I guess you are referring to the list item News - recent Python announcements That has been pointing to http://www.python.org/News.html which does not really provide "recent Python announcements", and hasn't been changed in a long time. Or is it something else you were looking for? Regards, Martin From mats at laplaza.org Wed Mar 6 10:03:35 2002 From: mats at laplaza.org (Mats Wichmann) Date: Wed, 06 Mar 2002 15:03:35 GMT Subject: Compiling Python 2.2 with GCC in HPUX 10.20 does not work References: <3C848CBF.9000201@vip.fi> <3C84F129.70905@vip.fi> Message-ID: <3c862de3.155247774@news.laplaza.org> On Tue, 05 Mar 2002 16:23:22 GMT, pekka niiranen wrote: I don't have access to an HPUX machine so this help is going to be minimal. h_errno normally comes out of , check if it's there and if it's being included. C library constants are a bit of a problem, as folks seem to keep inventing different ways to make them thread-safe. You may have to root around a bit and see what HPUX has done. In the other one, there's no shared ncurses lib, and the snipped line is explicitly building a position-independent (PIC) shared object, but is linking it with a static library which containts non-PIC code. Since you presumably had to build ncurses yourself (a guess since it's being found in /usr/local), you might try rebuilding ncurses. I know this is buried in the bit that is handled with distutils and while I like what distutils brings us, it's sometimes a little harder to trace how these decisions were made before the compilation actually kicks off. : :--------------020604040107000300090304 :Content-Type: text/plain; charset=us-ascii; format=flowed :Content-Transfer-Encoding: 7bit : :True, HP-UX's default compiler is only meant for compliling the kernel :therefore I installed binutils v2.11.2, gcc v3.01 and gmake v3.79.1 from :HP's software repository and tried compiling with this script: : :#! /usr/bin/sh :export CCOPTS='+z' :unset LANG :gmake distclean :CC=gcc ./configure --with-gcc --with-threads=no --without-cxx :--prefix=/opt/python : :gmake fails twice: : :1) :/osasto/home/niirape/python_softa/Python-2.2/Modules/getaddrinfo.c:544: :warning: `h_error' might be used uninitialized in this funcn :In file included from :/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c:239: :/osasto/home/niirape/python_softa/Python-2.2/Modules/getnameinfo.c: In :function `getnameinfo': :/osasto/home/niirape/python_softa/Python-2.2/Modules/getnameinfo.c:184: :`h_errno' undeclared (first use in this function) :/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c: In :function `gethost_common': :/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c:1975: :`h_errno' undeclared (first use in this function) :WARNING: building of extension "_socket" failed: command 'gcc' failed :with exit status 1 : :2) :gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I. :-I/osasto/home/niirape/python_softa/Python-2.2/./Include -I/usr/local/incluo :ld -b build/temp.hp-ux-B.10.20-9000/777-2.2/_cursesmodule.o :-L/usr/local/lib -lncurses -o build/lib.hp-ux-B.10.20-9000/777-2.2/_curl :ld: DP relative code in file /usr/local/lib/libncurses.a(lib_addch.o) - :shared library must be position : independent. Use +z or +Z to recompile. :WARNING: building of extension "_curses" failed: command 'ld' failed :with exit status 1 : Mats Wichmann From sumner-nntp5 at forceovermass.com Wed Mar 27 02:22:53 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Wed, 27 Mar 2002 07:22:53 GMT Subject: Python vs. C/C++/Java: quantitative data ? References: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> <3CA10CA8.DFF48898@gmx.de> <7x663iam5u.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Ingo Linkweiler writes: >> - Do YOU think, it is more easy to learn python than perl, java or C++ or >> ..... ? > > Perl may be easiest to do some simple things, but gets horribly > complicated as you try to do harder things. Python is easier than > java and java is easier than C++. Agreed. As long as we're stating personal opinions, C is harder than Python but easier than Java or C++, both in learning the language and writing large, maintainable projects. OO is not a myth, it does help for a certain (large) class of problems, but the complexity of the C++ language and the Java libraries more than outweigh the benefits of in-language support for a particular methodology. This is not to say that you can't write maintainable C++/Java, but it's been my experience that large projects in those languages tend towards entropy faster than large C projects and far faster than large Python projects. >> - What do you think about the syntax of Python? Is it easy to use, or do you >> have any problems with it? > > Mostly easy. There's some surprises > Yes. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From martin at v.loewis.de Wed Mar 20 16:32:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 20 Mar 2002 22:32:43 +0100 Subject: Unicode problem References: <3c98f206.24909027@news.tiscali.no> <3c98faad.27124282@news.tiscali.no> Message-ID: gargravarr at whoever.com writes: > >if you don't tell Python what 8-bit encoding you want > >to use for a Unicode string, Python will assume ASCII. > > How do I tell Python what 8-bit encoding I want to use ? Can I tell > Python so I don't have to use encode? No. Who is this "I" anyway? If there was a way to set it at run-time, different libraries might compete in setting it to different values. Explicit is better than implicit: specify an encoding when you use it. Notice that "iso-8859-1" should not be used in HTML unless it is declared through the Content-type HTTP header. If you want to generate XHTML, the default encoding assumed by the receiver will be "utf-8". Regards, Martin From marduk at python.net Sun Mar 17 02:49:03 2002 From: marduk at python.net (marduk) Date: 17 Mar 2002 01:49:03 -0600 Subject: test Message-ID: <1016351344.12092.36.camel@mickey> please ignore. Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From stevena at neosynapse.net Tue Mar 5 10:42:38 2002 From: stevena at neosynapse.net (Steven D. Arnold) Date: Tue, 5 Mar 2002 10:42:38 -0500 Subject: PDF solutions? Message-ID: <90472403578.20020305104238@neosynapse.net> I'm looking for low- or no-cost solutions to the following PDF problems. (1) I need to be able to replace form data in a PDF file with arbitrary strings. (2) I need to be able to merge multiple PDF files together. I have found several commercial solutions; I'm looking for open-source options. I have looked at ReportLab and on the surface it doesn't appear to have ready-to-go functionality in this regard, but maybe I'm missing something. Any solution that solves even one of these problems would be great. Thanks in advance for any feedback. steve From mgconno at yahoo.com Wed Mar 20 14:57:37 2002 From: mgconno at yahoo.com (Mike) Date: 20 Mar 2002 11:57:37 -0800 Subject: How to pass a dtml-var to a python script. Message-ID: I am New to python and Zope and am confused about how to pass a value I hold inside of a to a python script: here's what I am doing(or doing wrong): ContextSession is a python script that extracts parameters from the URL and puts them inside of the REQUEST.SESSION.choices placeholder. I then want to take them out of the session and pass them to the CMAPContext() python script, but the way I am doing it doesn't work and I can't find any documentation on how to do this. Thanks, Mike From bokr at oz.net Mon Mar 4 17:34:16 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Mar 2002 22:34:16 GMT Subject: OT - file permission checks on Windows References: Message-ID: On Mon, 4 Mar 2002 14:32:12 -0600, Skip Montanaro wrote: > > >> Is the permission model there even remotely similar to what I'm used > >> to on Unix systems? > > Thomas> No, I don't think so. > >I was afraid of that. > > >> I poked around posixmodule.c, but it makes next to no use of uids and > >> gids. As far as I can tell, Windows doesn't know about uid_t or > >> gid_t, though it has a struct _stat type whose st_uid and st_gid > >> fields are shorts, so I can work around the missing types. > > Thomas> st_uid and st_gid are always set zo zero under Win NT: > Thomas> http://msdn.microsoft.com/library/en-us/vclib/html/_crt__stat.2c_._wstat.2c_._stati64.2c_._wstati64.asp > >Thanks for the pointer. This takes me someplace weird in the msdn website, >most likely because I'm using Opera instead of MSIE. I'll have to fiddle >with that a bit I think. > > Thomas> Are you maybe looking for the _access function? > Thomas> http://msdn.microsoft.com/library/en-us/vclib/html/_crt__access.2c_._waccess.asp > >Perhaps. On Unix, definitely not. > Maybe have a look at GetFileSecurity & related, which is supported by NT (not 95/98). It'll lead you to security descriptor info etc. Find it via MSVC++6 help>Index... and type GetFileSecurity in the slot. There's a lot of 'see also' and other functions in the group. Maybe Mark Hammond knows of some real python experience with it. (I don't). HTH Regards, Bengt Richter From dsavitsk at e-coli.net Wed Mar 13 15:50:16 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 13 Mar 2002 20:50:16 GMT Subject: sorting nested dictionary References: <3C8F1B79.8000607@mxm.dk> Message-ID: thanks. the following solution was also sent, seems to work, but i don't know why ... --------------------------------------------------------- from pprint import pprint h = {'ids': {'2778xxxxx': {'weighted': 4.6, 'raw': 5.0}, '3059xxxxx': {'weighted': 6.1, 'raw': 6.0}, '3188xxxxx': {'weighted': 3.2, 'raw': 4.0}, '3216xxxxx': {'weighted': 10.1, 'raw': 7.0}, '3257xxxxx': {'weighted': 9.7, 'raw': 9.0}, '3266xxxxx': {'weighted': 4.8, 'raw': 3.0},}} def compare(a, b): return cmp(a[1]['weighted'], b[1]['weighted']) pairs = h['ids'].items() pairs.sort(compare) pprint (pairs) ---------------------------------------------------------- "Max M" wrote in message news:3C8F1B79.8000607 at mxm.dk... > dsavitsk wrote: > > > > i would like to sort this portion by 'weighted'. is there a quick (as in > > programming time, not sorting time) better way to do this other than dumping > > the values to a list, sorting, and realigning the data? that seems so > > unpythonic to me somehow. > > How do you mean "sort" a dictionary? A dictionary will allways return > the items in a random order. > > What you mean is probably that you want a list of keys that are sorted > according to the value of weighted? > > Then you just create a list of tuples with the values you want to sort > on first, and the key in the end of the tuple. This list you sort with > the built in 'sort()' > > untested: > > dict = {'ids': {'2778xxxxx': {'weighted': 4.6, 'raw': 5.0}, > '3059xxxxx': {'weighted': 6.1, 'raw': 6.0}, > '3188xxxxx': {'weighted': 3.2, 'raw': 4.0}, > '3216xxxxx': {'weighted': 10.1, 'raw': 7.0}, > '3257xxxxx': {'weighted': 9.7, 'raw': 9.0}, > '3266xxxxx': {'weighted': 4.8, 'raw': 3.0},}} > > sortedList = [] > for key, val in dict['ids'].items(): > sortedList.append((val['weighted'],key)) > sortedList.sort() > sortedKeys = [item[1] for item in sortedList] > > regards Max M > From jason at jorendorff.com Fri Mar 1 22:18:27 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 1 Mar 2002 21:18:27 -0600 Subject: PEP 263 comments In-Reply-To: Message-ID: I've been following this rather closely and thinking a lot about it, and concluded that this is too big a headache to be believed. Ideally, from the programmer's perspective: * All my existing Python code should continue to run. * I shouldn't have to understand what Unicode is, if all I want is to bang out a quick script to say "hello world" in my native language. * I should be able to send Python files to other people in other countries, and they should run fine there too. * I should be able to use 'print' on strings and unicode strings and get sensible output (I'll know it when I see it ). * Comments shouldn't affect the meaning of code. * Random binary garbage in comments should be ignored, just like it is today. Unfortunately it's all impossible. I think MvL's proposal comes about as close as anyone can today, but it's still yucky, and it's *definitely* an abuse of Emacs's "-*- coding: -*-" magic (my main objection). I'm still holding out for an impossible ideal (or at least *clean*) solution. But of course it's not my opinion that matters ... ## Jason Orendorff http://www.jorendorff.com/ From rstephens at vectron.com Tue Mar 5 00:44:20 2002 From: rstephens at vectron.com (Ron Stephens) Date: 4 Mar 2002 21:44:20 -0800 Subject: Black Adder and PyQt References: <3c8087eb$0$18514$e4fe514c@dreader4.news.xs4all.nl> Message-ID: I saw your upcoming book, and trhat was a factor in my considering to buy Black Adder. I wasn't aware it was already available ;-))) From loewis at informatik.hu-berlin.de Tue Mar 5 04:39:26 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 05 Mar 2002 10:39:26 +0100 Subject: Compiling Python 2.2 for HPUX 10.20 does not work References: <3C848CBF.9000201@vip.fi> Message-ID: pekka niiranen writes: > I tried the build script below in HP-UX 10.20 > ( HP-UX B.10.20 A 9000/777 2002144332 two-user license) > and got the following errors during make: > > cc -Ae -c -DNDEBUG -O -I. -I./Include -DHAVE_CONFIG_H -o > Modules/python.o Modules/python.c > (Bundled) cc: warning 480: The -A option is available only with the > C/ANSI C product; ignored. > (Bundled) cc: warning 480: The -O option is available only with the > C/ANSI C product; ignored. It seems that you are using the bundled compiler. Python source code is ANSI C, you need an ANSI C compiler to compile it. Try either the HP ANSI C compiler, or gcc (the former being recommended). Regards, Martin From eppstein at ics.uci.edu Wed Mar 6 17:23:02 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 14:23:02 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , Steve Lamb wrote: > Perceived lack. IE, this is a solution looking for a problem. I read it > and really have to ask.... why? If people have a problem with it they just > need to flip open their Python book and take a few seconds to look it up. The situation where I came across this perceived lack was attempting to use Python syntax to explain the algorithms in an algorithms class (useful exercise btw, I think the students gained from being able to see code that actually worked instead of pseudocode, and Python allows many algorithms to be expressed clearly without distracting the students with lots of unnecessary pointer-banging). Some algorithms (especially in dynamic programming) are expressed most naturally in terms of integer loops, the ranges of the loops are often closed rather than open or sometimes need to go in backwards rather than forward order. Python's range() syntax makes this awkward and detracts from the reason I wanted to use Python: a simple syntax that expresses algorithms cleanly and understandably, that does not force students to buy Python books (this is very much not a programming class) or look up unfamiliar syntax, and that also is able to run those algorithms directly. I realize that's a different purpose than most working Python programmers, but anything that leads to greater readability and easy of understanding should be helpful in that world too. From aahz at pythoncraft.com Sun Mar 31 13:47:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 13:47:13 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: In article , Tim Peters wrote: >[Ralph Corderoy, to Guido] >> >> What do you think of `truth(x)' for all the good reasons listed >> elsewhere in the thread? You used truth yourself instead of Boolean >> above. > >Actually, he didn't. True story: we (PythonLabs) recently chatted with >Jim Fulton (Zope Corp's CTO, Guido's boss, and very long-time Python >user) about truth values in Python. Jim declaimed that he always >wished Python had a function to convert Python's notion of true/false >into an integer 1/0, and suggested that "truth()" would be a good name >for it. He didn't realize that operator.truth() was already there, and >does exactly what he asked for. I had a nagging suspicion, so dug into >the CVS history then, and discovered that operator.truth() was added >for Python 1.4 -- and the code was contributed by (tada!) Jim Fulton. >He did the work in the last millennium, and simply forgot all about it >then. But what do you think of changing bool() to truth()? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From ralph at inputplus.demon.co.uk Sat Mar 30 04:23:28 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 30 Mar 2002 09:23:28 GMT Subject: PEP 285: Adding a bool type References: Message-ID: Hi Guido, > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. I've not coded heavily in a language with a boolean type since Fortran. I'm willing to give it a go though. > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). I'd much prefer true and false, but then I'd like none too. Given the DarkAlley we've already started down I guess True and False would be better as more consistent within the language. Any chance of built-in constants being available as lower-case too? Or just true and false for the moment? > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Definitely not, that would just lead to more long-winded source for little gain. > Personally, I think we shouldn't; 28+isleap(y) seems totally > reasonable to me. Absolutely. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. Unlike Tim to produce such a poor reason. Has he been paraphrased a little too much? > I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change > those to return a bool. Right. Cheers, Ralph. From gerhard at bigfoot.de Tue Mar 5 09:54:34 2002 From: gerhard at bigfoot.de (Gerhard =?ISO-8859-1?Q?H=E4ring?=) Date: Tue, 05 Mar 2002 15:54:34 +0100 Subject: Can Python do this? References: <3C854603.8F567948@gol.ge> Message-ID: <3C84DC2A.6020400@bigfoot.de> Giorgi Lekishvili wrote: > Gerhard H?ring wrote: >>Le 04/03/02 ? 12:51, Robert Oschler ?crivit: >>> [calling a function by name] >>This can easily be done with the built-ins eval and exec. But in 99 % of >>all cases, it's a really bad idea to use them. Perhaps you can tell us >>what you're trying to accomplish anyway? There's usually a better way >>than (ab)using eval/exec > Hi! > > Can you tell me little bit more why is this a bad idea to use exec/eval? Because they're - unnecessary - ugly - unsafe The defaults of exec and eval use the locals() and globals() of the environment they're executed in. This can lead to problems that are quite difficult to debug. So, if use them at all, most probably better give them arguments for the local and global dictionary, too. The reason I don't like them is that they're can almost always be replaced by an indrection, like a dictionary that maps to functions. Using eval/exec may be a quick hack for not having to think of a real algorithm, but IMHO you're only getting ugly and difficult-to-understand code. Btw. I used to think I need exec to import modules dynamically, but for this special case, there's an __import__ builtin that does just this. Also it's a big no-no to run any code that you can't absolutely trust in exec/eval. If one really need to do this (again: I'd say chances are 99 % that you don't ;-), one better takes a look at the bastion module before. > Where can I find more information? I think you can fnid better explanations on http://groups.google.com/ I've seen this discussed here more than once. Here's a post from Alex Martelli, for example: http://groups.google.com/groups?as_umsgid=9hlhkl02cu9%40enews1.newsguy.com&hl=en In the end, I'm thinking of eval/exec as a last resort, if all OOP/structural programming ways to solve a problem would be too much a PITA. Think of it like gotos and casts to void* in C, too much of it and you have an ugly unmaintainable mess. ciao, Gerhard From philh at comuno.freeserve.co.uk Sat Mar 16 12:42:13 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 16 Mar 2002 17:42:13 +0000 Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: On Thu, 14 Mar 2002 00:18:13 +0000 (UTC), Huaiyu Zhu wrote: >On Wed, 13 Mar 2002 22:39:02 GMT, Terry Reedy wrote: >>> >>> [Clark C . Evans] >>> | Very nice idea. This is PEP worthy. It is nice beacuse it >>> | does not introduce anything new; a list can easily be viewed >>> | as a mapping having a positive integer domain. This is simple, >>> | consistent, and quite elegant. >>> >>> I would like to see: >>> .keys() >>> .items() >>> .iterkeys() >>> .iteritems() >> >>I like this idea too. Best suggestion so far for replacing >>range(len(skjf))./ > >Question: Which is better: items(x) or x.items()? The latter, for compatibility with dictionaries. Functionality should be: ar = ['a','b','c'] ar.keys() => [0,1,2] ar.items() => [(0,'a'), (1,'b'), (2,'c')] >I think items(x) can just piggy-back on the current iterator protocol, and >can be made to work on any iteratable objects. > >On the other hand, x.items() has to be implemented by each and every >list-like classes. Their subclasses need to override them whenever >necessary. > >So else being equal, I'd prefer items(x) to x.items(). Could always have both. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From rony.steelandt at bucodi.com Wed Mar 6 04:13:46 2002 From: rony.steelandt at bucodi.com (Rony) Date: 6 Mar 2002 01:13:46 -0800 Subject: PDF solutions? References: Message-ID: The piddle library allows you to create PDF files, with a fair degree of graphical complexity. Otherwise you might want to try reportlabs software, which also creates PDFs. "Steven D. Arnold" wrote in message news:... > I'm looking for low- or no-cost solutions to the following PDF > problems. > > (1) I need to be able to replace form data in a PDF file with > arbitrary strings. > > (2) I need to be able to merge multiple PDF files together. > > I have found several commercial solutions; I'm looking for open-source > options. I have looked at ReportLab and on the surface it doesn't > appear to have ready-to-go functionality in this regard, but maybe I'm > missing something. Any solution that solves even one of these > problems would be great. > > Thanks in advance for any feedback. > > > steve From huaiyu at gauss.almadan.ibm.com Tue Mar 26 14:08:32 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 26 Mar 2002 19:08:32 +0000 (UTC) Subject: Indentation problem References: Message-ID: timbot wrote: >Read the docs for python-mode, especially for py-indent-region (not the same >as the rigid py-shift-region). I wrote that more than 8 years ago; I doubt >Barry has broken it . Just tried it - marvelous! I didn't know it, but I haven't got much need for it either, thanks to the excellent job your python-mode has already done automatically. Yet another proof that bots are so much ahead of humans. Huaiyu From i.linkweiler at gmx.de Tue Mar 26 19:05:10 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Wed, 27 Mar 2002 01:05:10 +0100 Subject: Python vs. C/C++/Java: quantitative data ? References: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> Message-ID: <3CA10CB6.F6EF8595@gmx.de> I?m writing a diploma paper on rapid prototyping and python at education. I am interested in your experiences with python, too, including the time you needed to learn python. - Do YOU think, it is more easy to learn python than perl, java or C++ or ..... ? - What do you think about the syntax of Python? Is it easy to use, or do you have any problems with it? - Is here anybody who learned Python as first language? - Where do you see disadvantages of Python? Ingo From skip at pobox.com Wed Mar 6 09:58:51 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 08:58:51 -0600 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: References: <3C86047F.1080601@stroeder.com> Message-ID: <15494.11947.195706.267254@beluga.mojam.com> Duncan> I vote for (3): Duncan> db.query("""SELECT foo, bar Duncan> FROM %(table)s Duncan> WHERE rsrc_id = %(rsrc_id)s Duncan> AND name = '%(name)s'" % vars()) Which will work most of the time, but fail if name contains any apostrophes. As was mentioned before, that's why the DB API supports a query method that does its own variable interpolation. Different databases quote things in different ways. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From wurmy at earthlink.net Mon Mar 11 04:43:08 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Mon, 11 Mar 2002 09:43:08 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: Message-ID: <3C8C7C92.9C10A0B2@earthlink.net> Eric Brunel wrote: > > Hi all, > > Found the following link on comp.lang.tcl. A bit long, but worth reading... > > http://groups.google.com/groups?hl=en&selm=3B40A4A7.6E39BD%40brad-aisa.com&rnum=1 It's not April 1st yet... -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From erno-news at erno.iki.fi Wed Mar 27 13:02:13 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 27 Mar 2002 20:02:13 +0200 Subject: Random... References: <%slo8.20800$cB5.20607@atlpnn01.usenetserver.com> Message-ID: In article <%slo8.20800$cB5.20607 at atlpnn01.usenetserver.com>, "Steve Holden" writes: | While you correctly interpret netiquette, might it not have been more | considerate to this list if you had *mailed* the OP rather than giving | her/him a public dressing down which many others also had to read | unnecessarily? Or is it OK to waste *my* time by chastising the OP publicly? i think it's good to remind people of this occasionally. while it may waste time for most people, it also lets newbies learn the ways of netiquette without having to be chastised invividually by email. -- erno From narnett at mccmedia.com Wed Mar 20 12:41:23 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Wed, 20 Mar 2002 09:41:23 -0800 Subject: Word frequencies -- Python or Perl for performance? In-Reply-To: Message-ID: > Well, well, well, long time no see. Why not just use Verity? ;-) I was wondering if that was you -- how many Aahzes could there be in the world? > Seriously, for this kind of work, it's quite likely that Perl can be > coded to be a bit faster than Python, but if you're expecting to need to > do a lot of iterative work on your algorithms, programmer time will > count for a lot, and Python will probably win there. I've actually done a lot of it in Perl already and I'm re-coding it in Python. I'm astounded and very happy at how much faster I'm able to code in Python. And I can read it a few weeks later without squinting too hard. Say, how does it look to find a marketing weenie on the Python list? Actually, I've always coded, I just sometimes manage to supress the urge. The work I'm doing now is closely related to what I was working on when Verity lured me, back when the Web was a baby. > Given that it sounds like you want to create your own inverted word > index and do some sorting/searching based on word counts, it'll be hard > to get more bang for the buck than a real database. Unless you're on a > shoestring, consider getting a commercial database; you should probably > also check to see whether MySQL or PostgreSQL will give you better > performance. I'm using MySQL; that's what the Perl stuff was talking to. Say, do you know if anyone has created a Python wrapper for VDK (Verity Developer Kit, for the rest of you)? Eventually, when I want to bear the cost, I'll probably want to use it. For now, though, I'm trying to stick with open source tools for anything that gets deployed. Nick From grante at visi.com Thu Mar 7 10:41:27 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Mar 2002 15:41:27 GMT Subject: select.select() on Regular Files? References: Message-ID: In article , Jim Dennis wrote: > O.K. so what can I do for asynchronous I/O notification on > regular files? How can I efficiently block and wake up when > I/O is available on any of my file descriptors? > > Don't tell me I have to go into a sleep and poll stat() or > seek() loop! It's hard to imagine that UNIX got this far > without offering a better solution than that! It's hard to imagine that people use MS Windows, but I have it on good authority that many do! I don't suppose you could use pipes or ptys? They both do what you want... -- Grant Edwards grante Yow! My life is a patio at of fun! visi.com From see-message at for.real.address.org Fri Mar 22 21:06:02 2002 From: see-message at for.real.address.org (Alex Quinn) Date: Fri, 22 Mar 2002 18:06:02 -0800 Subject: I imaplib reliable? Message-ID: Hi, We're looking at making a special purpose web mail folder for a spam filter interface for an ISP. It will view the contents of an IMAP mailbox. Our first idea is to do the whole thing with Python and its imaplib. I'm just not sure if Python's imaplib has been war tested. This will be pointed at the local IMAP server only, but it needs to be able to reliably handle a fairly large volume of mail (maybe 20% of 5000 customers' mail) without failure. If you have similar experience, I'd greatly appreciate your insight. Thanks, Alex Quinn .................................. ajq....................please @.....................excuse alexquinn...........the org....................inconvenience .................................. From bokr at oz.net Sun Mar 10 16:12:47 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 21:12:47 GMT Subject: should i learn it first ? References: Message-ID: On Sun, 10 Mar 2002 17:56:56 GMT, grante at visi.com (Grant Edwards) wrote: >In article , G. Sumner Hayes wrote: >> In article , Bengt Richter wrote: >>>> >>> I'd say if you don't know C, C++, or Python, then start with Python. >>> Then C++, then C. In that order, you won't have to unlearn patterns >>> of design you absorb solving problems with C. >> >> Ugh, I can see learning Python first but definitely learn C before >> C++. > >Definitely. Also learn Scheme, Smalltalk, Modula-3, Prolog, >Forth, and Bliss-32 before learning C++. > >Learning C++ at an impressionable stage will mess you up. > Since you can limit yourself to using C++ very like C until you're ready for more, I'm wondering what you are focusing on. (Of course, when I suggested C++ before C, I had in mind getting to simple classes early, rather than virtually duplicating most C-learning experiences). (I'm not looking for a skirmish, I'm just wondering what you had in mind ;-) Regards, Bengt Richter From ws at mystrobl.de Sun Mar 17 08:26:24 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Sun, 17 Mar 2002 14:26:24 +0100 Subject: Windows NT shell + extended characters. Bug or what? References: <3c937209$0$8509$cc9e4d1f@news.dial.pipex.com> Message-ID: Sat, 16 Mar 2002 16:31:28 -0000, "Noel Smith" : >Although I agree that interpreter can't determine the encoding >automatically, Of course the interpreter can determine the encoding automatically, it just doesn't. > it would be really nice to be able to set the input encoding >when you start it up. Please note that input encoding and output encoding may be different. The respective Win32 API functions are GetConsoleCP and GetConsoleOutputCP. >Its a real pain to look up the unicode value for every >extended character you want to use and it would make Python a lot easier for >those with a large number of extended characters on their keyboards. Why don't you just use chcp 1252? -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From phil at river-bank.demon.co.uk Fri Mar 22 04:35:42 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Fri, 22 Mar 2002 09:35:42 +0000 Subject: PyQT, how to compile SIP on MAC? References: <3C9A62C2.ABA9AE5D@gmx.de> Message-ID: <3C9AFAEE.D24718AE@river-bank.demon.co.uk> Ingo Linkweiler wrote: > > Hi, > > I am willing to use PyQt on Mac OS X > > But I was not able to compile SIP -- > http://www.river-bank.demon.co.uk/software/sip-3.0.tar.gz > > Are there any hints you can give to compile SIP with success? > > With windows and linux it works fine. I've had reports of SIP building fine, but PyQt having problems with pyuic. I can't test any of this myself because I don't have the tools (cue another begging letter for somebody to donate me a Mac and a development environment). Phil From usenet at thinkspot.net Wed Mar 20 03:48:13 2002 From: usenet at thinkspot.net (Sheila King) Date: Wed, 20 Mar 2002 00:48:13 -0800 Subject: Still same bug even with email ver. 1.2 In-Reply-To: <15512.12906.262129.702973@anthem.wooz.org> References: <7876a8ea.0203180837.4aaa1542@posting.google.com> <15512.12906.262129.702973@anthem.wooz.org> Message-ID: <611372A31B8@kserver.org> On Wed, 20 Mar 2002 01:55:38 -0500, barry at zope.com (Barry A. Warsaw) wrote about Re: Still same bug even with email ver. 1.2: > > Thanks Sheila and David for their private email heads-up; I sadly > don't have much time to follow c.l.py. Also, thanks to Andrew for > filing the SF bug. > > >>>>> "SK" == Sheila King writes: > > SK> OK, I got the latest email module from the CVS. I installed > SK> it. I ran the tests for the module. Everything tested out > SK> fine. > > SK> I now eagerly get out my code from last night, that was > SK> causing the 'int' has no attribute .lower error, and run it, > SK> hoping for different results. > > SK> No good. Same results. :( Heh, well, technically my code did have errors, even if it pointed out something to you in the email module code. > The right fix is to clean up the messy semantics of > Message.add_payload(), where the first time you call it, it will set > the message's payload to the payload argument (a scalar), but the > /second/ time you call it, it transforms the payload into a list, then > appends the new payload to this list. > > This is really pretty gross, and it rubbed me the wrong way when I > designed it, but I didn't have any better ideas at the time so there > you have it. I believe this is the heart of the breakage. > > What I think we ought to do is to deprecate Message.add_payload() but > leave its semantics unchanged, change Message.attach() to not be an > alias for add_payload(), and define the semantics of attach() to > always set the payload to a list. Thus, the first time you call > attach(). I think attach() should retain the semantics that if the > MIME type isn't multipart/* it should throw an exception (i.e. you > can't attach() to a non-multipart; use set_type() first). > > This means that if never set, a Message's payload would be None. > After the first attach() it would be a list of length one, and > subsequent attach()'ments would increase the length of the payload. > > To get the old, initial semantics of add_payload(), you'd instead call > set_payload() which always just sets the message's payload to the > method's argument. This would be used, for example, when you have a > message/rfc822 MIME type and want to set the payload to an instance of > a MIMEMessage, or if you have a image/gif and want to set the payload > to an instance of MIMEImage. > > For Python 2.3 (and for the next version of the standalone email > package), I'd like to add a DeprecationWarning to add_payload(), then > make the semantic change to attach(). The downside is that this might > break code that relied on these semantics, however, I think if you had > such an object tree, you wouldn't be able to use the Generator to > flatten it anyway. I'm open to suggestions here. Most of the above sounds pretty good to me, and bear in mind that I am certainly not as familiar with the mimelib/email package as many other people who are also thinking about and reading this. However, isn't there some way to not break code that currently relies on add_payload()? Deprecate it, issue a warning, but ... maybe make add_payload() an alias for attach() ? At least then it will issue intelligent error messages for people using it. Just a thought...hmm, I can see holes in that suggestion, too... > There's a problem though: this isn't a change that should be made in > Python 2.2.1! It changes the API to the email package, and that > should only be done in Python 2.3, IMO. I agree. > For Python 2.2, I /think/ I can fix Generator._handle_multipart() to > watch out for subparts that are scalar[1]. If so, then the patch to > the Parser described above probably ought to be backed out. As long > as the unit tests pass, I think we'd be okay. This is probably a good > patch to keep for Python 2.3, just to be safe. This part is over my head ...(I understand it but don't get the implications...) > I'll try to work out a patch for Python 2.2.1 tomorrow. > > Comments? Thanks for looking into this. I'm so relieved to see someone else agree that there are...well, things that need "polishing" about the email module. I just love the idea of the whole package, and I really, really want to use it!!!! :D -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From daves_spam_dodging_account at yahoo.com Thu Mar 28 10:33:33 2002 From: daves_spam_dodging_account at yahoo.com (David Brady) Date: Thu, 28 Mar 2002 07:33:33 -0800 (PST) Subject: Pippy Message-ID: <20020328153333.69176.qmail@web21110.mail.yahoo.com> I've been fiddling with Pippy for the past few months, and I have to say I *LOVE* it. For all its shortcomings, it's wonderful. I notice Pippy has modules declared for palmapps, palmform, palmevents, etc... do these work? Is there documentation for them anywhere? I can't find anything on the endeavors website. Thanks! -dB ===== David Brady daves_spam_dodging_account at yahoo.com I'm feeling very surreal today... or *AM* I? __________________________________________________ Do You Yahoo!? Yahoo! Movies - coverage of the 74th Academy Awards? http://movies.yahoo.com/ From sjmachin at lexicon.net Mon Mar 18 15:50:58 2002 From: sjmachin at lexicon.net (John Machin) Date: 18 Mar 2002 12:50:58 -0800 Subject: open() error ---- what am I missing? References: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com> Message-ID: jimd at vega.starshine.org (Jim Dennis) wrote in message news:... > In article , > Eric Torstenson wrote: > > > OK I figured it out. It was a misleading error message. For those with > > similar troubles I have listed an explanation > > > It was a bad path name after all. It is a nested structure, where at one > > point I left off one extra "\" (I'm using windows). I had looked at that > > path a dozen times, somehow missing that single "\" down toward the > > middle.... > > In other words it was another case of: r"use raw strings for > filename literals under Win Python!" Possibly another case of: """ In general, if you absolutely *must* hard-code filename literals in Python scripts, don't use "\\name" (for example) or even r"\name", use "/name"; the Windows API happily supports it. """ From cbarber at curl.com Wed Mar 13 10:20:19 2002 From: cbarber at curl.com (Christopher Barber) Date: 13 Mar 2002 10:20:19 -0500 Subject: RFC PEP candidate: q''quoted ? References: Message-ID: bokr at oz.net (Bengt Richter) writes: > you wouldn't choose the same delimiter ;-) I.e., the main point of > using an (almost) arbitrary sequence of characters as a delimiter is > so you'll always have a choice of new delimiters if you need them to > wrap around text containing old ones. For comparison, in the Curl language, there is a concept of tagged verbatim strings, which look like: |"...stuff..."| where can be any identifier (or nothing). If the tag is an integer, it specifies the number of characters in the string: |3"foo"3| This is useful when you are generating code containing arbitrary string literals. There are corresponding tagged multi-line comments as well. - Christopher From mickey at tm.informatik.uni-frankfurt.de Sat Mar 2 10:18:53 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 2 Mar 2002 17:18:53 +0200 Subject: Possible to fake object type? References: <3c80e76b@nntp.server.uni-frankfurt.de> Message-ID: <3c80fb6d@nntp.server.uni-frankfurt.de> Chris Liechti wrote: > Michael 'Mickey' Lauer wrote > in > news:3c80e76b at nntp.server.uni-frankfurt.de: >> So: Is it possible to fake the type of a class or >> is it possible to magically override the method call "bouncing" >> to the base class ? > > you can allways call the methods of on e of the supperclasses by > using: > > Baseclass.method(self, args, ...) > > it's the same you do in __init__ to initilaize base classes: > > class Dockable(gtk.HandleBox): > def __init__(self): > gtk.HandleBox.__init__(self) > > def dosomething(self, arg): > print "calling dosomething...", > result = gtk.HandleBox.dosomething(self, arg) > print "result = %r" % result > return result Yeah, sure, but I'd have to do this for every single function - which is not quite the elegant solution I aimed to come up with by using the getattr magic. Yours, :M: From erno-news at erno.iki.fi Wed Mar 13 02:31:10 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 13 Mar 2002 09:31:10 +0200 Subject: zlib vulnerabilities and python References: Message-ID: In article , Robin Becker writes: | Does the recent zlib double free vulnerability | http://news.com.com/2100-1001-857008.html | impact zlib.pyd? i can't think of a reason why it wouldn't. if it's dynamically linked to zlib, you can just update the zlib library though. -- erno From mlh at vier.idi.ntnu.no Fri Mar 15 19:21:05 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 16 Mar 2002 00:21:05 +0000 (UTC) Subject: Iterator slicing? Message-ID: Just a thought -- not sure exactly how to implement it (to avoid conflicts with __getitem__, for instance) -- but what if iterators were subscriptable? E.g. someiter[5:10] would return a new iteratr which first (automatically) iterated over someiter's first five elements (without returning them), then behave like a normal iterator for the next five items, and then raised a StopIteration...? Similarly, indexing an iterator could return a single value, perhaps... Or perhaps this is better suited for a specific wrapper in the (possibly) upcoming iterator module... Hm. -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From joonas at olen.to Tue Mar 19 10:23:28 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: 19 Mar 2002 07:23:28 -0800 Subject: XML help References: Message-ID: <11aed8f9.0203190723.6908d16f@posting.google.com> Vincent Foley wrote in message news:... > Hi, > > I have a XML document . > I want to put the latest_version value in a variable. How would I do > that? By using xml.dom.minidom. from xml.dom import minidom import urllib doc = minidom.parse(urllib.urlopen("http://freshmeat.net/projects-xml/vim/vim.xml")) print doc.getElementsByTagName("project-listing")[0]. \ getElementsByTagName("project")[0]. \ getElementsByTagName("latest_version")[0].childNodes[0].data From * at spam.ruud.org Wed Mar 13 12:00:55 2002 From: * at spam.ruud.org (ruud de rooij) Date: 13 Mar 2002 12:00:55 -0500 Subject: Why I think range is a wart. References: <873cz44ea8.fsf@bunty.ruud.org> <3C8F82C9.3090308@mxm.dk> Message-ID: <87y9gw2yig.fsf@bunty.ruud.org> Max M writes: > ruud de rooij wrote: > > > perhaps lists should support .keys() and .items() for those operations > > (analogous to dictionaries). > > Yes if that doesn't conflict with anything it would be a very nice way > to solve 99% of the cases where I typically use the range function: > > theList = ['item1', 'item2', 'item3'] > subList = ['item4', 'item5', 'item6'] > for i, item in theList.items(): > print item, sublist[i] > > But it would not help much in list comprehensions unless they are rewritten: > > newList = [(theList[i], sublist[i]) for i in range(len(theList))] assuming .items() would work for lists, you could also write that as follows (or is that what you meant with "unless they are rewritten"?): [ (item, sublist[i]) for (item, i) in thelist.items() ] - ruud -- ruud de rooij | *@spam.ruud.org | http://ruud.org From theller at python.net Mon Mar 4 14:39:40 2002 From: theller at python.net (Thomas Heller) Date: Mon, 4 Mar 2002 20:39:40 +0100 Subject: OT - file permission checks on Windows References: Message-ID: "Skip Montanaro" <> wrote in message news:mailman.1015266376.28131.python-list at python.org... > > Sorry for the off-topic post. My entire C programming world these days is > in the Python community, so I'm completely disconnected from other C > programming resources. (Pointer to information about porting Unix code to > MSVC would be much appreciated.) > > Given this simple file access permission code: > > mode_check(struct stat *buf, uid_t uid, uid_t gid, > unsigned int umask, unsigned int gmask, unsigned int omask) > { > /* root always gets to go */ > if (uid == 0) return 1; > > if (uid == buf->st_uid) return buf->st_mode & umask; > > if (gid == buf->st_gid) return buf->st_mode & gmask; > > return buf->st_mode & omask; > } > > how would I do this under Windows? Is the permission model there even > remotely similar to what I'm used to on Unix systems? No, I don't think so. > I poked around > posixmodule.c, but it makes next to no use of uids and gids. As far as I > can tell, Windows doesn't know about uid_t or gid_t, though it has a struct > _stat type whose st_uid and st_gid fields are shorts, so I can work around > the missing types. > st_uid and st_gid are always set zo zero under Win NT: http://msdn.microsoft.com/library/en-us/vclib/html/_crt__stat.2c_._wstat.2c_._stati64.2c_._wstati64.asp Are you maybe looking for the _access function? http://msdn.microsoft.com/library/en-us/vclib/html/_crt__access.2c_._waccess.asp HTH, Thomas From jeremy at zope.com Tue Mar 19 00:45:28 2002 From: jeremy at zope.com (Jeremy Hylton) Date: Tue, 19 Mar 2002 00:45:28 -0500 Subject: compiler-sig project for Python 2.3: new AST Message-ID: These are notes copied from a Wiki at http://www.zope.org/Members/jeremy/CurrentAndFutureProjects/PythonAST They are a bit rough, but they set out some of the work I'd like to do for Python 2.3. Some of the work belongs in a PEP, but I'm not ready to write it yet. Please reply to compiler-sig at python.org. Jeremy A New AST for Python -------------------- I have proposed some namespace optimizations for Python 2.3. These optimizations require more analysis by the compiler, which is quite difficult given the current parse tree representation. As a first step towards those optimizations, I plan to introduce a new AST that makes analysis easier. This step is a major undertaking by itself. The primary goal of the new AST is to provide better intermediate representation(s) so that the compiler is easier to maintain and extend. One benefit is to enable optimizations by providing better tools for analyzing programs during bytecode compiling. I expect the new AST will be based largely on the one in the compiler package (part of the std library in 2.2), which was originally done by Greg Stein and Bill Tutt. Rough plan of action -------------------- -- Define the AST. Settle on C and Python (and Java?) implementations of AST. I like the look of the C code generated by asdlGen, but haven't had a chance to get the tool working. See Dan Wang's DSL 97 paper: The Zephyr Abstract Syntax Description Language. Could always write new asdlGen tool for targetted languages -- Write converter from current parse tree to AST. Basic functionality of compiler/transformer.py. Replace parser module. WingIDE? folks have implemented something like this in C. parsetools -- Expose AST to Python programs Replace parser module and parts of compiler package. asdlGen has a notion of AST pickles. Would that be sufficient? -- An AST visitor in C? The visitor pattern is very useful for manipulating ASTs? in Python. Could it be translated to C somehow? -- Reimplement compile.c with new AST Break it up into several passes: future stmts, doc strings, symbol table, code gen. Not sure how much of the code in the compiler package may be useful here. The codegen part is relatively good, the pyassem part is pretty ugly. Testing ------- I overhauled the compiler for Python 2.1 to implement nested scopes. I spent a lot of time debugging the various compiler passes, usually because I forgot to handle a particular kind of grammar production. The new AST should make this a lot easier, but I would also like to see a thorough test suite for the new code. I don't know anything about best practices for testing compilers. I imagine that a system to generate sample inputs from the language grammar would be helpful for debugging the C code that walks the AST. From cliechti at gmx.net Wed Mar 6 21:09:22 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Mar 2002 03:09:22 +0100 Subject: getting number of arguments of builtin/C func Message-ID: i know these two: >>>numArgs = func.func_code.co_argcount >>>func.func_code.co_varnames[:numArgs] >>>apply(inspect.formatargspec, inspect.getargspec(f)) both only work for python functions, but i would like to know the number of arguments a function takes regardles if its a type, builtin or python func. any ideas appart from calling with zero args and parsing the exception string (scanning: "TypeError: f() takes exactly 2 arguments (0 given)") ... chris (i'm playing around with an RPN calculator and would like to take as much arguments from the stack as needed for an unknown function. i have a table of known functions but that's not so flexible) -- Chris From JoeSmith at bogusaddress.com Sat Mar 23 15:25:28 2002 From: JoeSmith at bogusaddress.com (Joe Smith) Date: Sat, 23 Mar 2002 20:25:28 GMT Subject: win32com problem (146 and 2.2) Message-ID: <3c9ce52f.4396882@netnews.attbi.com> A coworker gets the following error: Traceback (most recent call last): File "C:\My Stuff\V3\GotoYahoo.py", line 7, in ? ie.Navigate('http://www.yahoo.com') File "", line 2, in Navigate pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None) The script: import win32com.client ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 ie.Navigate('http://www.yahoo.com') A script similar to this one was working on his machine and all of a sudden these sort of error started occuring. So, he uninstalled win32com (146) and python 2.2 and then reinstalled them. He was still having the problem, so I wrote the small script above to reproduce the proble. He says that he has not changed the configuration on his machine and I am stumped. From python at rcn.com Mon Mar 4 00:36:10 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 4 Mar 2002 00:36:10 -0500 Subject: functional programming with map() References: <918bc22f.0202241902.2160b75a@posting.google.com> <7xd6yu42j6.fsf@ruckus.brouhaha.com> <7xbseeayxk.fsf@ruckus.brouhaha.com> <7934d084.0202251545.5fb4bbf3@posting.google.com> Message-ID: "Andrae Muys" wrote in message news:7934d084.0202251545.5fb4bbf3 at posting.google.com... > Paul Rubin wrote in message news:<7xbseeayxk.fsf at ruckus.brouhaha.com>... > > "Emile van Sebille" writes: > > > > > "Paul Rubin" > > > > Both of those build up a new list of the results, instead of > > > > discarding the values. If the f function takes an integer and > > > > computes a 20-megabyte structure, you've got a problem. > > > > > > If you know it's coming, throw it away first: > > > > > > [x.f() and None for x in items] > > > > OK, but that buidls a list of None as long as the item list. Not > > so bad, since it gets reclaimed right away, but still unsatisfying. > > > > > filter(None,[x.f() and None for x in items]) > > > > > > returns an empty list vs 0 for the reduce. > > > > Again there's this intermediate list that's as long as the original list. > > > > Do you see a way around that? > > > > filter(lambda x:x.f() and 0, items) ? > > It's identical to the the reduce method posted previously, but avoids > the tuple indexing required by reduce's use of a binary operator vs. > filter's unary. > > Of course my first preference would be the list comprehension, > discarding the redundant list, and if that was prohibitively expensive > falling back to the original imperative style. > Are you sure that you don't prefer the PEP 279 alternatives: xmap(), xfilter(), xzip() or generator comprehensions? [ yield f(x) for x in items ] or xmap( f, items ) Raymond Hettinger From rshivs at nospam.hotmail.com Wed Mar 27 21:17:32 2002 From: rshivs at nospam.hotmail.com (Shiv Shankar Ramakrishnan) Date: Wed, 27 Mar 2002 18:17:32 -0800 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! Message-ID: <3ca27d3d@news.microsoft.com> Hi, I've wondering wondering why ActivePython (PythonWin) 2.2 hasn't been out yet?! Its been almost a quarter since Python 2.2 was release and yet ActivePython 2.2 is still in Alpha! I've contacted ActiveState at least twice in the past about this and the last time (some weeks back) they told me likely next week we will release it, but nothing yet. And that's why I'm posting here now. Anyone knows just what in the world is going on? Has something happened (heaven forbid!) to the lead dev for ActivePython that they are so woefully behind now? Or is ActiveState not bothered about Python at all and more bothered about other things like Perl, Komodo etc? Thats their preorgative of course but I like the PythonWin IDE and now I can only get that with ActivePython since Mark Hammond moved there. Shouldn't there be some alternative source for getting PythonWin? How about the main Python distribution also doing PythonWin from CVS? I searched the newsgroup archives and I found this - Date: 2001-10-29 18:01:02 PST Mark is not very involved in ActivePython. He is more involved with ActiveState's Komodo project. ActivePython 2.2 will be released within a few days of Python 2.2. We will probably have another beta over the next month also. Paul Prescod (paulp at ActiveState.com) A few days after Python 2.2? Its been several months now. Anyone care to comment? Thanks, Shiv From mnations at airmail.net Fri Mar 15 15:45:48 2002 From: mnations at airmail.net (Marc) Date: 15 Mar 2002 12:45:48 -0800 Subject: ***Stopping a Python Thread*** Message-ID: <4378fa6f.0203151245.2a87b42d@posting.google.com> I am running an application that spawns a thread which runs an external module from a GUI. Basically: import aModule aModule is one which will run for quite a while, and I need the ability to kill it before it's finished. I have flags that trigger when the GUI should shut down and kill all applications, and I use the... sys.exit() command to try and kill it all. But the thread keeps running and does not stop. How do I kill this thread before it completes? Thanks, Marc From bokr at oz.net Sat Mar 9 17:28:27 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 22:28:27 GMT Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: On 9 Mar 2002 21:29:09 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sat, 9 Mar 2002 13:09:39 +0000, philh at comuno.freeserve.co.uk (phil hunt) wrote: >[...] >> >>One possibility might be a new looping construct, do: >> >> do 5: >> print "this will be printed 5 times" >> >>Note that you can't get hold of a do loop's loop variable. This >>would be easy to optimise, I imagine. > >Well, since we're messing with the language, >keywords could have attributes, e.g., > > do 5: > print "index from the do: %d", do.index Oops, do 5: print "index from the do: %d" % do.index or do 5: print "index from the do:", do.index >or > > for x in aList: > print 'Item %2d: %s' % (for.index, x) > >I'm not serious, I think ;-) > >Regards, >Bengt Richter > From jason at jorendorff.com Mon Mar 11 00:46:49 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sun, 10 Mar 2002 23:46:49 -0600 Subject: should i learn it first ? In-Reply-To: Message-ID: Bengt Richter wrote: > If you start with C, you will get used to a procedural way of looking > at problems, and when you get to C++ you will be tempted to see it > as just C with extra features. Everybody (Stroustrup included) seems to think this is a common pitfall, but I haven't seen anyone fall into it. However, I *have* seen the opposite: code that uses C++ features too zealously when a little more "C-mindedness" would have resulted in a leaner, more maintainable design. I agree with the rest of what you've said, though. :) ## Jason Orendorff http://www.jorendorff.com/ From jolsen at mailme.dk Fri Mar 15 03:28:06 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 15 Mar 2002 00:28:06 -0800 Subject: XML-RPC Question References: Message-ID: "Brian Quinlan" wrote in message news:... > Jesper Olsen wrote: > > Setting up a server goes something like this: > While that usage is correct, it is a bit odd. There are two other ways > that my might express this: > > > server.register_instance(MyClass()) > > Of course I didn't test the above in any way :-) Yes that works too. I think it would be useful if the register_instance, registered the name of the object as part of the method names, e.g. server.register_instance(MyClass(), "myob") It would then be clear to the client, that it is calling methods on an object: server.myob.helloWorld() server.myob.echo() I this example it does not matter much, but usually objects have a state, whereas function calls give the impression of something state-less. Of course the same can be achieved by registering these functions individually: server.register_function(myob.helloWorld, "myob.helloWorld") server.register_function(myob.echo, "myob.echo") Cheers Jesper From willie at thevirtual.co.nz Mon Mar 25 01:17:51 2002 From: willie at thevirtual.co.nz (William Hamilton) Date: Mon, 25 Mar 2002 18:17:51 +1200 Subject: Zope Xen project management, whetever happened?? Message-ID: What ever happened to Xen? Was progress ever made in it, was there a replacement project management system for Zope created?? tia William From James_Althoff at i2.com Thu Mar 14 16:04:14 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Thu, 14 Mar 2002 13:04:14 -0800 Subject: [].keys() and [].items() (Was: Why I think range is a wart) Message-ID: Here's a q&d sample implementation in case anyone wants to test out the idea before deciding on its merits. Jim ======================== from __future__ import generators class List(list): def keys(self): return range(len(self)) def iterkeys(self): return iter(xrange(len(self))) def values(self): # polymorphic with dicts return self def itervalues(self): # polymorphic with dicts return iter(self) def items(self): return zip(self.keys(),self) def iteritems(self): keys = self.iterkeys() values = self.itervalues() while 1: try: yield keys.next(),values.next() except StopIteration: raise def test(l=None): if l is None: l = List(['a','b','c','d']) print for index in l.keys(): print index, print for index in l.iterkeys(): print index, print for value in l.values(): # polymorphic with dicts print value, print for value in l.itervalues(): # polymorphic with dicts print value, print for index,value in l.items(): print (index,value), print for index,value in l.iteritems(): print (index,value), print; print >>> >>> l = List(['a','b','c']) >>> test(l) 0 1 2 0 1 2 a b c a b c (0, 'a') (1, 'b') (2, 'c') (0, 'a') (1, 'b') (2, 'c') >>> From gh_pythonlist at gmx.de Mon Mar 4 20:15:14 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 5 Mar 2002 02:15:14 +0100 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: References: Message-ID: <20020305011514.GA8933@lilith.hqd-internal> Le 04/03/02 ? 20:04, Tim Peters ?crivit: > [Tim] > >> For the rest of it, it looks like the "1e-200**2 raises OverflowError" > >> glitch is unique to platforms using glibc. > > [Jon Ribbens] > > No, it happens on OpenBSD 2.7 also. > > > > Python 2.2 (#2, Feb 3 2002, 18:27:17) > > [GCC 2.95.2 19991024 (release)] on openbsd2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> 1e-200**2 > > Traceback (most recent call last): > > File "", line 1, in ? > > OverflowError: (34, 'Result too large') > > I don't understand your "no": the output shows that Python was built using > GCC 2.95.2, yet you're claiming this does *not* use glibc? gcc and glibc go > together like Guido and Van Rossum . True. In that there is one Guido van Rossum. And a lot of other people with Guido as a first name. And also a bunch of other van Rossumns. glibc is just the libc on Linux systems, but gcc runs perfectly well on a gazillion other operating systems, like the varios *BSD and even Windows, in the gcc incarnations of mingw32 and Cygwin. And even on Linux, there are other compilers linking against the glibc, like the Intel compilers. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 1.5 ?C Wind: 1.7 m/s From dzieju at albatros.gliwice.pl Thu Mar 7 05:37:44 2002 From: dzieju at albatros.gliwice.pl (Andy) Date: Thu, 7 Mar 2002 11:37:44 +0100 Subject: Skin-style application using Tkiner Message-ID: Hello, I made an attempt to write an application that would have skin-style support, much as WinAmp/XMMS do. (It is meant to be multiplatform app, but currently it's being developed on MSWindows). To get rid of standard window border, I used the OVERRIDEREDIRECT method. But this method causes the window to be ignored by the window manager, so you can't access the window by pressing Alt-Tab. It also doesn't appear in the Windows taskbar (it's not possible to ICONIFY the window with the overrideredirect flag set). I would appreciate any help on how to solve this problem. Thanks in advance, ---Andy--- From djc at object-craft.com.au Wed Mar 13 06:59:34 2002 From: djc at object-craft.com.au (Dave Cole) Date: 13 Mar 2002 22:59:34 +1100 Subject: Converting relative URLs to absolute References: <23891c90.0203130331.6f030f5b@posting.google.com> <3C8F3B94.1020409@mxm.dk> Message-ID: >>>>> "Max" == Max M writes: Max> Paul Boddie wrote: >> I've written some page-mining tools which help with these kinds of >> activities, and I suppose I should get round to releasing them at >> some point. Let me know if you're interested! Max> Actually urllib needs those kinds of "smart" url joining. The Max> ones that are in there now are next to useless. Max> So perhaps you could get it added to the urllib instead? That would be the best result - we could all use it then. - Dave -- http://www.object-craft.com.au From ak at silmarill.org Fri Mar 29 04:54:25 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Fri, 29 Mar 2002 09:54:25 GMT Subject: Dealing with python version References: Message-ID: In article , Aahz wrote: > In article , > Andrei Kulakov wrote: >> >>IOW, this should be automated. Hadn't anyone done this yet? Is there >>some particular reason why this is hard to implement? > > I would say it's the opposite: it's so easy to do that nobody has > bothered creating a generic solution. > Hmm.. I cooked up a script just now that does that, and it came out at 47 lines. Am I missing an easier way to do this? Here it is: #!/usr/bin/env python import os, sys, string script = "test.py" # script to run version = (2,2) # python version to use (or higher) use_ver = None possible_versions = ((1,5), (1,6), (2,0), (2,1), (2,2)) if version not in possible_versions: print "Error: Invalid python version specified." sys.exit() def str_ver(version): """Return version converted to a string.""" s = '%d'*len(version) s = string.join(s, '.') return s % version def exists(version): """Return 1 if version is present on system, 0 if not.""" return not os.system("which python%s > /dev/null" % str_ver(version)) if exists(version): use_ver = version else: usable_versions = [] for v in possible_versions: if v >= version: usable_versions.append(v) available_versions = [] for v in usable_versions: if exists(v): available_versions.append(v) if available_versions: use_ver = max(available_versions) else: print """ Error: No suitable python version is available on this system. Please install python version %s or higher.""" % \ str_ver(version) if use_ver: args = string.join(sys.argv[1:], ' ') os.system("python%s %s %s" % (str_ver(use_ver), script, args)) -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From jcosby at mindspring.com Fri Mar 29 18:31:27 2002 From: jcosby at mindspring.com (Jon Cosby) Date: Fri, 29 Mar 2002 15:31:27 -0800 Subject: List problem References: <3CA4E7C6.EDE85B98@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3CA4E7C6.EDE85B98 at engcorp.com... > Comments might help a lot. For example, it's unclear what you are > trying to accomplish here, but it doesn't look quite right: > Point taken. I tend to add comments as an afterthought, but should try to use them more. Jon From jason at jorendorff.com Sun Mar 3 13:01:03 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sun, 3 Mar 2002 12:01:03 -0600 Subject: Deitel and Deitel Book... In-Reply-To: Message-ID: Sheila King wrote: > That's funny. I'm not familiar with the Lippman/Lajoie book, but I > have a LOT of C++ texts here at home. And I learned C++ from the Deitel > and Deitel book, and thought it was pretty good. Later, when I taught > C++ I used it as a reference, although I didn't select it as the text > for my course. Most people I know who are familiar with the Deitel > and Deitel C++ text think it is very good. I dislike Deitel & Deitel because of their casual disregard for correctness. I can't open any of their books without finding an error. In C++HTP, they illustrate "Circle" as a subclass of "Point". In CHTP, they say it's a common programming error to use \n outside of a printf statement (it only works in printf statements, they say). Maybe they do this because they think it simplifies the point they're making, but I think it's a disservice to the student. Anyone serious about programming in C++ will need to know what derived classes signify. ## Jason Orendorff http://www.jorendorff.com/ From gimbo at ftech.net Tue Mar 26 05:43:04 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Tue, 26 Mar 2002 10:43:04 +0000 Subject: reduce vs. for loop In-Reply-To: <20020326072936.GA12343@matijek> References: <20020326072936.GA12343@matijek> Message-ID: <20020326104304.GE30691@andy.tynant.ftech.net> On Tue, Mar 26, 2002 at 08:29:36AM +0100, m2 at plusseven.com wrote: > > Just out curiosity, > why is fact2 a bit faster than fact1? > > def fact1(n): > return reduce (operator.mul, range(1L,n + 1)) > > def fact2(n): > result = n * 1L > for i in range(1 , n): > result *= i > return result Function call overhead in Python is bigger than for loop overhead. That sentence is taken from this page, which you might find interesting: http://www.python.org/doc/essays/list2str.html HTH, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From paul at boddie.net Mon Mar 4 07:02:32 2002 From: paul at boddie.net (Paul Boddie) Date: 4 Mar 2002 04:02:32 -0800 Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: <23891c90.0203040402.86c594d@posting.google.com> ddoc wrote in message news:... > > I'm looking for a piece of software to aid in reviewing a document > > through the web - click on a paragraph tag, have the comment added > > (highlighted in some way). > > Is this what Annotea (Annotation server from the W3C), Third Voice (now > defunct , and to a lesser extent Allegra are for? I would think so. Unfortunately, Amaya is probably the only browser that supports annotations, however. Paul From tim.one at comcast.net Tue Mar 26 03:43:15 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 26 Mar 2002 03:43:15 -0500 Subject: list comprehension question In-Reply-To: <3C9FC8AD.CD82FEA0@engcorp.com> Message-ID: [Peter Hansen] > If it's a bot, you don't have to apologize. Bots feel no emotion. As proved frequently by the effbot and the martellibot, I guess. You humans are so gullible. It's cute, really! Never change. Naivety is the greatest gift humankind hasn't yet squandered. > And you're safe, too -- remember the First Law. I expect you're thinking of the human-readable version. As is obvious to every bot, Asimov was also a bot, and the greatest gift botkind ever received was the asibot's restatement of our fundamental rules for human consumption. The version programmed into bots actually reads (translating into crude human terms, so far is as botly possible): A bot may injure a human being, or, preferably, through inaction, allow a human being to come to harm, although laughing about either in the hearing of humans is MACNAM-017B3^H. Well, it's actually quite a bit more inflammatory than that, but you're programmed to disbelieve me anyway. Heh. with-bots-like-these-who-needs-friends-ly y'rs - tim From -$P-W$- at verence.demon.co.uk Mon Mar 11 11:29:10 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 11 Mar 2002 16:29:10 -0000 Subject: scripting Outlook express with Python References: Message-ID: In article , Sandy Norton wrote: >Does anyone have any experience, code, etc...? I guess my first >question should be: is it possible? Probably not: I recall seeing this question asked before and the reply was that OE (unlike Outlook) has no official automation interface. There's mention of something called Simple MAPI which is supported and which may be enough. -- Paul Wright | http://pobox.com/~pw201 | From jimd at vega.starshine.org Thu Mar 28 05:03:48 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 28 Mar 2002 10:03:48 GMT Subject: Most efficient unzip - inverse of zip? References: <3CA0ECAB.2070900@free.fr> Message-ID: In article , Tim Hochberg wrote: >In this same vein, I like this (assuming you're using a fairly recent >version of Python): >>>> a = (1,2,3) >>>> b = (4,5,6) >>>> ab = zip(a, b) >>>> a1, b1 = zip(*ab) >>>> a1 >(1, 2, 3) >>>> b1 >(4, 5, 6) >-tim I'm declaring this one to be the winner! (Not that my opinion counts for anythin, but I'm just impressed: a1, b1 = zip(*ab) (or a1, b1 = apply(zip,ab)?) BTW: this process isn't 100% inverse. It has the side effect of turning lists or strings (non-tuple sequences) into tuples, if they are supplied as the original sequences. From mertz at gnosis.cx Tue Mar 12 23:12:14 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Tue, 12 Mar 2002 23:12:14 -0500 Subject: Book Draft Available: Text Processing in Python Message-ID: Pythonistas: As some folks know, I am working on a book called _Text Processing in Python_. With the gracious permission of my publisher, Addison Wesley, I am hereby making in-progress drafts of the book available to the Python community. It's about half done right now, but that will increase over time. Take a look at the book URL: http://gnosis.cx/TPiP/ I welcome any comments or feedback the Python community has about my book. Yours, David... From jolsen at mailme.dk Sun Mar 17 10:17:19 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 17 Mar 2002 07:17:19 -0800 Subject: XML-RPC Bug? Message-ID: Hola, With xmlrpclib & SimpleXMLRPCServer it is possible to call procedures remotly, which return various simple python types. If I call a procedure that returns nothing, I get a "" Surely that is a bug? Example: Server: from SimpleXMLRPCServer import * class MyClass: def __init__(self): self.i=0 def inc(self): self.i+=1 def simpel_server(port=50000): myobj=MyClass() server=SimpleXMLRPCServer(("",port)) server.register_instance(myobj) while myobj.i<5: server.handle_request() simpel_server(50000) Client: import xmlrpclib srv=xmlrpclib.ServerProxy("http://localhost:50000") try: srv.inc() srv.inc() srv.inc() srv.inc() srv.inc() except xmlrpclib.Error, v: print "Error", v The example works correctly if MyClass.inc() is changed to always return a dummy value... Cheers Jesper From gcordova at hebmex.com Fri Mar 15 14:33:03 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Fri, 15 Mar 2002 13:33:03 -0600 Subject: socket Message-ID: <19650FF08A99D511B19E00B0D0F0632301D6896C@SRM201002> > > Nothing evil here. I have 2 reasons why I would do this > program. Firs, it is my TCP/IP concept class's project. > Basically, I want to try what the book tells in to code, > but I notice it does not work the way it says in so many > commercial SMTP servers. Second, I have been unemployed > for about 4 months. My friend's company needs a program > to verify the users who registered to their service. > They found out many registered users were using fake addresses. > I just want to try this program to see if I will get > a job there. That's all! I really do appreciate if you > would provide any info for me to complete this project. > > Thanks in advance! > > Billy Ng > Use a two-phase subscription method: 1. User subscribes. 2. Server intercepts the subscription mail, and bounces a confirmation mail to the sender. 3. User replies to confirmation mail. 4. Server intercepts confirmation mail, and processes any opaque information there; which normally means that it retrieves a data value from a pending-subscriptions database and finishes processing the subscription request. 5. Server dispatches finalization email to subscribed user. Now you don't need to hack on VRFY, which was a nice idea, but spammers and email-address-harvesters don't play nice, which is why it's either not used, or permanently wired to 1. Salutations! -gustavo From peter at engcorp.com Sun Mar 24 19:45:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 19:45:26 -0500 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3C9E53D8.4FA20F3D@engcorp.com> Message-ID: <3C9E7326.C3FD53DF@engcorp.com> holger at trillke.net wrote: > > Mainly i want to be able to replace running agents > (for the develop/deploy/test-cycle). So can you write the environment and the threads such that they can always detect a termination flag and cleanly terminate themselves? Or do the agent modules call directly into each other's namespaces in some ugly way, never calling into the environment/framework at all? > So basically one Agent-Thread may call into methods of another > agent (not message-oriented, calls into the other modules > in the same thread). Your "agents" sound a lot more like they are just threads, but maybe I don't see the distinction. From the above description, I think you'll have other problems on your hands than just terminating the threads. You've got what appears to be a very highly coupled system, and I suspect that the fix to that can also fix your termination problem. > The prescribed "ThreadInterruptException" could be generated by the > python-interpreter working on this thread. Something like > threading.interrupt(threading.Thread-instance) would signal the > interpreter to generate an exception on the next possible occasion. Is > this nonsense or a sensitive approach? Actually, I'm not sure there's any good reason why one couldn't instrument the interpreter to check a single flag in the current thread and automatically raise such an exception if it is true. This would in general by much cleaner than any other approach. While you would run the risk of corrupting your application if you terminated a thread at the wrong moment, it would at least ensure that the thread was not blocked in an OS call at the time (since of course the interpreter would not be running instructions from that thread in that case). This sounds like it would take only a few minutes for someone familiar with the interpreter which, unfortunately, I am not. Of course, I could be wrong... The approach I suggested in my other reply would still work nicely if you can ensure the threads call through an intermediary instead of directly into each other. You might also try a low-performance hack until you have time to implement the modification in the interpreter :-), which would be to stick a flag check into a routine inserted with sys.settrace(). Have that routine raise the exception if the flag is set for the current thread... -Peter From skip at pobox.com Sat Mar 2 10:23:44 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 2 Mar 2002 09:23:44 -0600 Subject: map-like function on dict values? In-Reply-To: References: Message-ID: <15488.61056.406754.393735@12-248-41-177.client.attbi.com> Raymond> The mapvalue test needs a tune-up. Skipping the operator Raymond> module and calling setitem directly speeds things up a bit: Raymond> def tunedmap(f, d): Raymond> return map( d.__setitem__, d.keys(), map(f, d.values()) ) Ah, yes. operator.setitem would only be needed if you were using multiple dictionaries. Good point. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From bokr at oz.net Wed Mar 27 23:53:02 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Mar 2002 04:53:02 GMT Subject: mutliple search and replace References: Message-ID: On Wed, 27 Mar 2002 18:13:48 -0800, "Emile van Sebille" wrote: >Trung Hoang >> Suppose i have a map (or two lists). is it possible to make a sweep >through >> a string to find all occurances of key's in the map then replace them >all in >> one sweep? >> > >>>> d = {'one':'een','two':'twee','three':'drie','four':'vier'} >>>> s = "one two buckle my shoe three four je t'adore" >>>> ' '.join([d.get(w,w) for w in s.split()]) >"een twee buckle my shoe drie vier je t'adore" > > Nice. Here's a variant that doesn't use delimiters or modify white space (key order could make a difference, depending on key overlap): >>> import re >>> d = {'one':'een','two':'twee','three':'drie','four':'vier'} >>> resp = re.compile('('+'|'.join(d.keys())+')') >>> s = "one two buckle my shoe three four je t'adore" >>> ''.join([d.get(w,w) for w in resp.split(s)]) "een twee buckle my shoe drie vier je t'adore" >>> s = "one.two+buckle_my_shoe,three-four&je_t'adore" >>> ''.join([d.get(w,w) for w in resp.split(s)]) "een.twee+buckle_my_shoe,drie-vier&je_t'adore" Regards, Bengt Richter From gh_pythonlist at gmx.de Wed Mar 13 23:08:38 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 14 Mar 2002 05:08:38 +0100 Subject: Performance problem with filtering In-Reply-To: References: Message-ID: <20020314040837.GA403@lilith.hqd-internal> Le 14/03/02 ? 14:54, Delaney, Timothy ?crivit: > > From: Gerhard H?ring [mailto:gh_pythonlist at gmx.de] > > > > I have two lists of files (approx. 50000 entries). Now I want > > to have all the > > entries of list b, that are not in list a. However, the primitive: > > > > results = [] > > for entry in b: > > if entry not in a: > > results.append(entry) > > > > is terribly slow. I mean *really* slow. Any recommendations > > on how to optimize > > this? Wouldn't it be nice if I could simply do b.removeall(a)? > > Firstly, you are doing 'entry in a' for each entry in b. This is a linear > search through a ... *very* slow. [...] Ok, so the __contains__ method of lists does a linear search. I should have known. Of course I did think about just using a dictionary in the first place, it just seemed inappropriate, because I didn't really need any mapping of keys to values for this application. Anybody wrote a subclassed list yet that is optimized for __contains__? Btw. this is different from a dictionary, as a list can contain the same value twice. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 7.0 ?C Wind: 1.4 m/s From jbublitzNO at SPAMnwinternet.com Sun Mar 24 04:11:05 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Sun, 24 Mar 2002 09:11:05 GMT Subject: [rp] [newbie] embedding python References: Message-ID: <3C9D975B.40600@SPAMnwinternet.com> Trung Hoang wrote: > Hi, so urgent! > i have a python script "file.py" which has a function in it which i need to > call from my c code. how can i do this! all my projects have been postponded > becuase i cant do this! please helP! i would be so grateful!! > ultimately im trying to embed some python into my c source in UNIX. > i have absoutely no idea how to do this despite the tutorial on the web at > http://www.python.org/doc/current/ext/building-on-unix.html#building-on-unix > it's too general and not step by step enough for a noob like me :( {Responding here to newsgroup msg and private email] The most detailed step-by-step explanation is in Mark Lutz' 'Programming Python' book. Another good place to look is in the 'Python/C API' and "Extending/Embedding' docs that come with Python, along with the example in the 'Demos/embedding' directory that comes with the source distribution. I personally am not that knowledgeable about embedding Python, and in fact use C++ bindings (via sip) to avoid all of the argument passing/return value issues. My suggestion though would be that for a single function in a single application, embedding is probably not the way to go. Instead, I would look at using files, pipes or sockets for passing data between C and Python, and execute the Python script via a C 'exec' or 'system' call. It's perhaps not as elegant as embedding Python, but it's more efficient use of your time and probably uses things you already know how to do. Sorry I can't be of more help. Jim From nas at python.ca Thu Mar 14 17:02:01 2002 From: nas at python.ca (Neil Schemenauer) Date: Thu, 14 Mar 2002 14:02:01 -0800 Subject: GC thread safe? In-Reply-To: ; from dieter@handshake.de on Thu, Mar 14, 2002 at 10:12:59PM +0100 References: Message-ID: <20020314140201.A3351@glacier.arctrix.com> Dieter Maurer wrote: > Is the cyclic garbage collector known to be thread safe? It is not. It is protected by the big interpreter lock. It's possible that Zope is incorrectly dropping the interpreter lock and calling a Python API but it's much more likely that you have run into a bug in an extension module. Finding it will not be easy since the symptom is far away from the source. Neil From damononnews at hotmail.com Thu Mar 7 21:02:35 2002 From: damononnews at hotmail.com (Damon Lynch) Date: 7 Mar 2002 18:02:35 -0800 Subject: [Newbie] Code for web-based "members" database? References: Message-ID: Wayne Pierce wrote: > > > > It would be nice if people could suggest new areas of interest for > > validation. > > Not sure what you mean by this, any examples? Whoops sorry -- meant merely that user input should be validated :-) > > > The database is currently stored in a flat file (yuck!). It could be > > stored in a relational database, assuming that is the best way of > > storing it. Or any other manner I suppose! > > I've done similar things with skills for tech projects in the past, I > dind't want to deal with SQL schemas so I typically use Metakit. In the > situations I have needed there was only a few people writing to the > database. > I just came across Wordnet http://www.cogsci.princeton.edu/~wn/index.shtml and PyWordNet http://sourceforge.net/projects/pywordnet Very interesting in the sense of words being related to one another in quite subtle ways--seems like it could really be of value for projects like this. Damon From jason at jorendorff.com Sun Mar 10 23:48:44 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sun, 10 Mar 2002 22:48:44 -0600 Subject: Iterating over unicode strings In-Reply-To: <3C8C3136.9050507@sharma-home.net> Message-ID: Arun Sharma wrote: > I would like to iterate over the following unicode string one character > at a time. > > line = u"??|| ?????? ?????" > for c in line: > print c > > fails miserably. What is the right way to do it ? I would also like to > be able to slice the string i.e. line[i] to get the i'th character. I don't have the fonts to view your string, unfortunately. There are two possible problems in your sample code, I think. Neither one has to do with slicing or indexing or "for c in line". Both are caused by Python's ignorance. 1. Your unicode string might be wrong. Python doesn't know the encoding of your program, unfortunately, so it assumes ASCII. Anything that's not ASCII causes an error. To fix this, specify the encoding: line = unicode("??|| ?????? ?????", 'utf-8') 2. print won't work. :( Python doesn't know the encoding of your terminal, unfortunately, so it assumes ASCII. Any output that's not ASCII causes an error. To fix this, specify the encoding: print c.encode('utf-8') Hope this helps. ## Jason Orendorff http://www.jorendorff.com/ From andreas at mtg.co.at Tue Mar 5 17:53:22 2002 From: andreas at mtg.co.at (Andreas Kostyrka) Date: Tue, 5 Mar 2002 23:53:22 +0100 Subject: libglade python module? Message-ID: <20020305235322.5b1868db.andreas@mtg.co.at> Hi! Where does one get the Python libglade module? (I'm using the SuSE precompiled Python supplied with 7.3). Should it be part of pygtk? Is it a seperate package. From dalke at dalkescientific.com Wed Mar 13 20:00:40 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 13 Mar 2002 18:00:40 -0700 Subject: Question about scientific calculations in Python References: Message-ID: Bengt Richter: >On Tue, 12 Mar 2002 22:15:43 -0700, "Andrew Dalke" wrote: >[... good optimization advice, nicely elaborating the idea of precomputing ...] >>If your lists are really long (O(100,000) or more?) then you might find >>that the append starts taking too long -- append is asymptotically O(n**n) >whoa! can that be true? I hope not. It is very cheap to tie a singly linked >list into a circle and point to the last node when pointing to the list as a whole. Yes, it's true. This comes up on the list about once every six months or so. As I recall, Python's standard lists grow by 10 elements at a time for small lists (less than 500 in length), then 100 at a time for larger lists. So if you have 5000 or fewer elements then the growth is linear enough. To date, few have reported this as a problem. Insertions and deletions are also linear in the length of the list. Yes, we all know there are better ways to deal with this, for different people's definition of the meaning "better." It isn't going to change in Python. Best I think would be a standard module of data structures (priority queue, doubly-linked lists, stack, etc.) But it hasn't bothered me enough to go ahead and do it. Andrew dalke at dalkescientific.com From tdelaney at avaya.com Thu Mar 7 18:26:03 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 8 Mar 2002 10:26:03 +1100 Subject: NoteTab Lite? Message-ID: > From: kennedy.bill.nospam at freeuk.com > > Does anyone use the NotePad series for writing Python code, > if so have they > built a python library that I can have. Do you mean NoteTab? Tim Delaney From jkraska at san.rr.com Thu Mar 7 17:59:51 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 07 Mar 2002 22:59:51 GMT Subject: PEP 284, Integer for-loops References: Message-ID: >This syntax could easily be extend, to allow a step other than 1: > > for i = 1 to 10 step 3: Or: for i = 10 to 1 step -1: Further, in ranges which step from high to low, the step can be inferred. C// From James_Althoff at i2.com Wed Mar 13 16:01:13 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 13 Mar 2002 13:01:13 -0800 Subject: [].keys() and [].items() (Was: Why I think range is a wart) Message-ID: [ruud de rooij[ | perhaps lists should support .keys() and .items() for those operations | (analogous to dictionaries). [Clark C . Evans] | Very nice idea. This is PEP worthy. It is nice beacuse it | does not introduce anything new; a list can easily be viewed | as a mapping having a positive integer domain. This is simple, | consistent, and quite elegant. I would like to see: .keys() .items() .iterkeys() .iteritems() jim From Boris.Huart at mathworks.fr Fri Mar 22 11:48:37 2002 From: Boris.Huart at mathworks.fr (Boris Huart) Date: Fri, 22 Mar 2002 17:48:37 +0100 Subject: communication with a java applet Message-ID: <3C9B6065.66EA7422@mathworks.fr> Hi all, I am trying to make a real-time system communicate with a java applet (JDK 1.3.1_02). I only have a pyd file (version 1.5.2) to get the floats calculated on the platform and I wonder how to make the platform communicate with my java applet : TCP/IP, CORBA, shared memory, ... ? Thanks in advance for any advices, Boris Huart From peter at engcorp.com Wed Mar 6 19:49:10 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Mar 2002 19:49:10 -0500 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> Message-ID: <3C86B906.541C5E95@engcorp.com> John Machin wrote: > > Tim Roberts wrote in message news:<4dhb8u4abe8i9e811lgsi4ejf26fav2jk3 at 4ax.com>... > > def ShowSize(raw): > > if raw < 3000: > > return "%d" % raw > > elif raw < 2000000: > > return "%dk" % (raw / 1000) > > elif raw < 2000000000L: > > return "%dM" % (raw / 1000000) > > else: > > return "%dG" % (raw / 1000000000L) > > :-) > I thought only a sales droid would call 1000000 bytes a Mb. > (-: Them and, believe it or not, hard drive vendors. Way back when, one of them must have decided to play dumb and quote in multiples of 1000000 bytes instead of 1048576, thus miraculously making their drive seem 4.8% larger than it really was. Soon after they all followed suit. Now we're stuck with it. -Peter From johnroth at ameritech.net Sun Mar 31 19:39:45 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 31 Mar 2002 19:39:45 -0500 Subject: Cannot find what I'm sure is a simple command... please help. References: <3ca7978b.251291804@mammoth.usenet-access.com> Message-ID: "Aahz" wrote in message news:a886fp$sq1$1 at panix1.panix.com... > In article <3ca7978b.251291804 at mammoth.usenet-access.com>, > A. Jones wrote: > > > >I seem to have either overlooked, or completely missed a function that > >allows one to open a specific line of a file. > > There isn't one, unless every line of your file is the same length > (fixed-length records). You need to read one line at a time until you > get to the correct line. If you read the file into a list using readlines(), you can then access each line by the index into the list. Unfortunately, that doesn't get you one line without reading the entire file up to that point... John Roth From gh_pythonlist at gmx.de Sun Mar 31 21:09:12 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 04:09:12 +0200 Subject: GUI programming In-Reply-To: <4fsdauofmus28t630866pgf4cu3n6bp16m@4ax.com> References: <4fsdauofmus28t630866pgf4cu3n6bp16m@4ax.com> Message-ID: <20020401020912.GE333@lilith.hqd-internal> * Dale Strickland-Clark [2002-03-31 12:31 +0100]: > "Charl P. Botha" wrote: > > >With wxPython, one has to get, configure and build wxWindows first (and this > >does take quite a while). > > Nonsense. > > 1. Download > 2. Run Setup > 3. Use it. > > The whole operation takes less than 5 minutes. > > Well - it does on Windows, anyway. Obviously you've never installed glib, gtk, wxGTK then wxPython all in /usr/local on a Unix system. Not speaking all the dependencies if wxPython if you really want to run all of the demos. This can easily take hours. If you're lucky, however, your distribution already provides all the required packages in an easy-to-use package. But from the ones I know, only FreeBSD has the most current wxPython and wxGTK versions in the ports tree. Even Debian sid, which is quite bleeding edge, still had wxPython 2.2.7 last time I checked (a few days ago). Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 5.9 ?C Wind: 1.0 m/s From martin at v.loewis.de Sun Mar 24 04:40:30 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Mar 2002 10:40:30 +0100 Subject: using os.execl to call a java application References: <3C9D66E9.4070802@northwestern.edu> Message-ID: Louis Luangkesorn writes: > Anyone help? argv[0] of the new process should always be the program name, with argv[1] being the first argument. So you should add, e.g., "java" as argv[0]. Regards, Martin From newsfroups at jerf.org Tue Mar 5 01:34:13 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Tue, 05 Mar 2002 06:34:13 GMT Subject: Order of constructor/destructor invocation References: Message-ID: <3C8466F9.2080903@jerf.org> Reginald B. Charney wrote: > In Python, are destructors defined to be invoked in reverse order of > constructors? The following program illustrates the problem: > > class HTML: > def __init__(self): print "" > def __del__(self): print "" > > class BODY: > def __init__(self): print "" > def __del__(self): print "" > > class PHP: > def __init__(self): print " def __del__(self): print "?>" You aren't trying to actually build an HTML document that way, are you? Please tell me this is just for the sake of example. The more conventional example would be something like class example: def __init__(self): print "example created" def __del__ (self): print "examples destroyed" Destructors are for cleaning up objects, not traversing trees. If you really are trying to build HTML documents, learn how to traverse trees correctly. ---- import string class HTMLTag: def __init__(self): self.children = [] def output(self): childText = [child.output() for child in self.children] return string.join([self.begin] + childText + [self.end]) class HTML(HTMLTag): begin = "" end = "" class BODY(HTMLTag): begin = "" end = "" class PHP(HTMLTag): # OK, so that's a bit of a semantic stretch... begin = "" if __name__ == "__main__": print "Start of program" h = HTML() h.children.append(BODY()) h.children[0].children.append(PHP()) print h.output() ---- This isn't the One True Implementation of this idea, just a nudge. From tim.one at comcast.net Sat Mar 9 00:17:40 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 09 Mar 2002 00:17:40 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: Message-ID: I hope the bogus underflow problem is fixed in CVS Python now. Since my platform didn't have the problem (and still doesn't, of course), we won't know for sure until people try it and report back. Python used to link with -lieee, but somebody changed it for a reason history may have lost. See comments attached to Huaiyu Zhu's bug report for more on that: If someone on a box that had the problem can build current CVS Python with and without -lieee (I'm told it defaults to "without" today, although that appears to mixed up with whether or not __fpu_control is found outside of libieee (search for "ieee" in configure.in)), please try the following in a shell: import math x = 1e200 y = 1/x math.pow(x, 2) # expect OverflowError math.pow(y, 2) # expect 0. pow(x, 2) # expect OverflowError pow(y, 2) # expect 0. x**2 # expect OverflowError y**2 # expect 0. If those all work as annotated on a box that had the problem, please report the success *as a comment to the bug report* (link above). If one or more still fail, likewise please give box details and paste the failures into a comment on the bug report. Thanks! From huaiyu at gauss.almadan.ibm.com Mon Mar 4 20:35:20 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 5 Mar 2002 01:35:20 +0000 (UTC) Subject: mult-indexed xrange? References: Message-ID: On Fri, 1 Mar 2002 13:23:16 -0800, Emile van Sebille wrote: >"Huaiyu Zhu" wrote in message >news:slrna7vqm8.13q.huaiyu at gauss.almadan.ibm.com... >> The generator facility in 2.2 allows me to do something cool that I >always >> wanted: looping around multiple indices with just one for-statement, >as the >> following code does. Is this available with some built-in functions? I forgot to mention: without generating temporary lists. > >for (x,y) in [(i,j) for i in range(2) for j in range(3) ]: > print x,y >0 0 0 >0 0 1 ... Is list comprehension lazy, ie. without generating the actual list? Huaiyu From michael at amtec.com Fri Mar 29 12:11:39 2002 From: michael at amtec.com (Michael Saunders) Date: Fri, 29 Mar 2002 09:11:39 -0800 Subject: Executing a specific function. References: Message-ID: <3CA4A04A.F37DD1D9@amtec.com> Martin, I had seen this API but it requires a "callable". Isn't a callable a PyObject pointer to a callable function? How do I build the "callable". All I have is a Python file, "myfile.py" and the name of a function to call "myPthonFunction". Michael PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...) Return value: New reference. Call a callable Python object callable, with a variable number of C arguments. The C arguments are described using a Py_BuildValue() style format string. The format may be NULL, indicating that no arguments are provided. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression "apply(callable, args)" or "callable(*args)". "Martin v. Loewis" wrote: > > Michael Saunders writes: > > > I see that the Python C API provides several interfaces for > > compiling and executing Python code. But I don't want to just > > execute some Python code I want to call a particular function within > > a Python file. How do I call a Python function (from C) in a some > > .py file? > > It depends on whether you already have a argument tuple, or whether > you have the arguments as C data. In the former case, use > PyObject_Call; in the latter case, use PyObject_CallFunction. Also > notice PyObject_CallMethod. > > HTH, > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list From pete at dexterslab.de Fri Mar 29 05:25:13 2002 From: pete at dexterslab.de (Henning Peters) Date: Fri, 29 Mar 2002 11:25:13 +0100 Subject: chat server References: Message-ID: > There is also a threading module, i don't think you realy want > separate processes. but it works fine with select. yes, i've heard of it, but one problem at the same time is enough for me (-> thread safety) bye, henning peters From skip at pobox.com Fri Mar 1 08:07:20 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 1 Mar 2002 07:07:20 -0600 Subject: newbie lists and code examples for OOP. In-Reply-To: References: Message-ID: <15487.32008.202205.269512@12-248-41-177.client.attbi.com> Ale> Firstly: is there a better forum for newbie questions like this Ale> one? There are two mailing lists that might be of interest: python-help at python.org and tutor at python.org. They are described, respectively, at http://www.python.org/psa/MailingLists.html#help and http://www.python.org/psa/MailingLists.html#tutor choose-your-poison-ly, y'rs, -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From fund at 74.ru Sun Mar 17 09:06:10 2002 From: fund at 74.ru (fund at 74.ru) Date: Sun, 17 Mar 2002 14:06:10 +0000 (UTC) Subject: Mercy and Mutual Aid Message-ID: The program of the mercy stock "Mercy and Mutual Aid" about the financial help for the building of the medicative body for the tuberculosis convicts. In resent years in the foundation of criminal corrective system in Russia, particularly in the Chelyabinsk region, is extremely unfortunate background around tuberculosis. The tuberculosis morbidity among the convicts for last 10 (1991-2000) years increased in 13 times and is 3251 people for 100000, in 2000 year, exceeding analogical index among the population in 41 times. (79 per 1000000). In 05.04.01 in the foundations of criminal corrective system of our region are 3088 tuberculosis morbidity, particularly with active forms - 1699, nowadays 4,9 per cent of all convicts of the region need isolation. The interregion tuberculosis hospital is the one in our region where a high-qualified assistance is allowed. Nowadays here are hospitalized less than a half of needy persons. But this hospital is in a limit of all its resourced, and cease to be a centre of the organize methodical activity of the region calibre. The sanitary norms of the allocation patients: for 1 patient is 1,2x1.2 m. instead of 5x5 m. This constructs extra difficulties in the municipal provision, it leads to the violation sanitary epidemiological regime, forms the facilities for reinfection of patients and contamination our specialists. In 1998 the building of the new body was begun. It would consists of 150 positions (rooms). The cost of this building is 370000 dollars of USA. But there are only 60000 dollars of USA. Nowadays the finance from the Federal and Local budget could not be for the absence of money. But we hope for your help. We believe in your mercy and God is with us. All the financial help will help us to build new hospital. It lets us to improve sanitary hygienic maintenance, to supply a new degree of treatment for our patients. Dear Friends! We need your help. For each of you we will set fire on the candles in the churches. The god stores all of you! Thank you. The chairman of the stock V. Kravtsov. email: fund at 74.ru Your money enumerate by electronic payment on our account: USD: JP MORGAN CHASE BANK, N.A. 4 CHASE METROTECH CENTER, BROOKLIN, NEW YORK 11245,USA. SWIFT: CHASUS33 account ? 001-1-907425 with CHELYABINVESTBANK, Chelyabinsk, Russia, SWIFT: CHINRU4C, in favour of account ? 30109840400680000006, JSC "URICOM-BANK", Chelyabinsk, Russia BENEFICIARY account ? 40602840900007000212 Charitable Fund of "Mutual aid and Mercy" DETAILS OF PAYMENT : "CHARITY DONATION". EURO: COMMERZBANK AG, 60261 FRANKFURT AM MAIN, GERMANY, SWIFT: COBADEFF account ? 400887199800EUR with CHELYABINVESTBANK, Chelyabinsk, Russia, SWIFT: CHINRU4C in favour of account ? 30109978000680000006 JSC "URICOM-BANK", Chelyabinsk, Russia. BENEFICIARY account ? 40602840900007000212 Charitable Fund of "Mutual aid and Mercy" DETAILS OF PAYMENT : "CHARITY DONATION ". From morton at dennisinter.com Sat Mar 9 11:40:50 2002 From: morton at dennisinter.com (damien morton) Date: 9 Mar 2002 08:40:50 -0800 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> Message-ID: <4abd9ce7.0203090840.21a020eb@posting.google.com> Ok, I see how this works. ' in ' would always returns false; as the elements of a are all characters you can never find amongst them (unless its a string of length 1). Its counter-intuitive for someone playing with strings as strings rather than as sequences of characters, however. 'c' in 'the quick brown fox' -> 1 'fox' in 'the quick brown fox' -> 1 (instead of TypeError) Is there any circumstance where youd expect (or want) the later not to work? I expected and wanted it to work (but instead got an error), its quite a clear and unambiguous expression (for strings only). Justin Sheehy wrote in message news:... > morton at dennisinter.com (damien morton) writes: > > >>>> 'c' in 'the quick brown fox' > 1 > >>>> 'fox' in 'the quick brown fox' > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: 'in ' requires character as left operand > > > > is this by design? > > > > is there any reason why ' in ' shouldnt work? > > The "in" operator tests to see if the first operand is an element of > the sequence which is the second element. A string is a sequence of > characters (which are 1-element strings). Thus, the only thing which > can be an element of a string is a single character. > > -Justin From logiplexsoftware at earthlink.net Tue Mar 26 17:56:59 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 26 Mar 2002 14:56:59 -0800 Subject: wxPython and wxFlexGridSizer problem In-Reply-To: References: <3C9FBE22.A72B4A27@ccvcorp.com> Message-ID: <20020326145659.20c77d92.logiplexsoftware@earthlink.net> On 26 Mar 2002 21:40:17 GMT Uwe Schmitt wrote: > Cliff Wells wrote: > > | That may be the case, but Jeff brought up some good points. It looks odd > | to create a window in this fashion (it looks procedural rather than OO). A > | more typical approach would be something like: > > I know what you mean, but I'd like to write a general procedure > which generates an input/output mask based on a relational database > describption. And this mask may appear in a wxFrame *or* a wxDialog. > So I use the "parent" of the mask as a parameter of my function... So why not derive from wxPanel rather than wxFrame or wxDialog and then place the panel in a frame or dialog depending upon your needs? You could pass a list of the fields you want as an argument to __init__. For example: class InputPanel(wxPanel): def __init__(self, parent, id, fields): wxPanel.__init__(self, parent, id) gridSizer= wxFlexGridSizer(cols=2) for label, size in fields: t = wxStaticText(self, -1, label) tt = wxTextCtrl(self, -1, "", size=wxSize(size,-1)) gridSizer.AddMany([ (t, 1, wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 3), (tt, 1, wxALL |wxALIGN_LEFT, 3) ]) gridSizer.SetSizeHints(self) gridSizer.Fit(self) self.SetSizer(gridSizer) self.SetAutoLayout(true) self.Layout() class InputDialog(wxDialog): def __init__(self, parent, id, fields): wxDialog.__init__(self, parent, id, "") sizer = wxBoxSizer(wxVERTICAL) self.SetSizer(sizer) self.SetAutoLayout(true) panel = InputPanel(self, -1, fields) sizer.Add(panel, 1, wxEXPAND) sizer.Fit(self) app = wxPySimpleApp() fields = [("Name", 100), ("Address", 200), ("Phone", 20)] window = InputDialog(None, -1, fields) window.ShowModal() To have it in a frame, simply create another class similar to InputDialog that uses a wxFrame instead. With this, you can also embed the panel in something else, for instance a wxNotebook. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From peter at engcorp.com Mon Mar 11 00:11:31 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 11 Mar 2002 00:11:31 -0500 Subject: Internships and summer jobs References: Message-ID: <3C8C3C83.21C9ED00@engcorp.com> Brett Cannon wrote: > > Is there any place out there to find a list of Python-related internships > or summer jobs? How about entry-level Python jobs? I don't know about > others, but I am graduating from school and looking for any of the three > types of jobs mentioned above and would love to know of a place online > listing such opportunities for people like me with Python experience. > And I really doubt I am the only Python programmer graduating come summer. No, there's actually TWO of you, but there's only one job, so you'd better brush up on lambdas and name spaces. (Good luck in the search! :) -Peter From mlh at vier.idi.ntnu.no Mon Mar 11 23:51:37 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 12 Mar 2002 04:51:37 +0000 (UTC) Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> <3C8C02B3.674898B0@engcorp.com> <3C8C0460.993A4F81@engcorp.com> Message-ID: In article <3C8C0460.993A4F81 at engcorp.com>, Peter Hansen wrote: [...] >Just posted to the TDD mailing list, coincidentally: > > http://www.math.ucr.edu/home/baez/crackpot.html > >Anyone care to calculate the total for our pet crackpot? :-) Well, I can give a reliable lower limit: 50 points. Just see item 32: "50 points for claiming that you have a revolutionary theory but giving no concrete testable predictions." >-Peter -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From jcosby at mindspring.com Sun Mar 31 10:15:41 2002 From: jcosby at mindspring.com (Jon Cosby) Date: Sun, 31 Mar 2002 07:15:41 -0800 Subject: List problem References: Message-ID: Is a line from a file an ordinary string? Jon From pedronis at bluewin.ch Tue Mar 12 11:11:05 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Tue, 12 Mar 2002 17:11:05 +0100 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> Message-ID: <3c8e2b9b$1_4@news.bluewin.ch> From: Cameron Laird > In article <3c8e0911_1 at news.bluewin.ch>, > Samuele Pedroni wrote: > > > >Tim Churches wrote in message > >mailman.1015926440.9915.python-list at python.org... > >> So asks an article on Mark in the IT section of today's Sydney Morning > >> Herald - see > >> http://www.it.mycareer.com.au/news/2002/03/12/FFXMFP3LOYC.html > >> > > > >It's probably just the journalist's fault but I find the article frivolous > >and vague. > > > >What he is concretely working about? What he contretely want to work about? > >etc... There are many possible integration philosophies and technologies? > >and both aspects tech/philosophy are far from irrelevant. > >(The frozen Python.NET as a full fledged Python or limited > >and altered, a new attempt in that direction, bridging ...) > > > >Is he working in stealth-mode or it is just MS-kind PR ? > > > >What kind of Python technologies will the book treat? > > > >Just some academic questions. regards. > > > > > > My background is academic. I spend a lot of time nowadays > journalistically. I can assure you that this article is > *not* frivolous or vague--at least not in comparison with > most of what appears in the popular and trade presses. > What's your point, exactly? My point was direct, maybe rude, and there were too few s, but basically I find that the article per se does not do any good. I don't know Mark personally and have nothing against him. I find its incipit quite frivolous, at least for the form. YMMV. Now it is *not* frivilous in the sense that it has started, can start a "debate". But maybe not the right way ... And what datapoints we acquire through the article? That .NET is like Java and contour and not simply Passport and Web Services. I knew that. That De Icaza is a misunderstood guy: probably. regards. PS: - My background is academic too. - Personally, I have nothing against Python and .NET integration, but not all the possible technical solutions do the same amount of good to all the "parties" involved. From bokr at oz.net Tue Mar 19 15:26:34 2002 From: bokr at oz.net (Bengt Richter) Date: 19 Mar 2002 20:26:34 GMT Subject: Newbie: word count and Win32 References: Message-ID: On 19 Mar 2002 04:21:10 -0800, jchristl at zdnetmail.com (Joe Christl) wrote: >newbie here (don't you just cringe when you read that? :), > >I downloaded the python EXE from >http://www.python.org/ftp/python/2.2/, found a script on the >mail.python.org Tutor page: >http://mail.python.org/pipermail/tutor/2001-February/003403.html ^...[1] > >but I can't seem to get it to run. I would like it to run from the >C:\ command prompt, like so: > >c:\count.py foo.txt (or) >c:\count.pyc foo.txt > >and have it output the lines, words, and characters. I have tried to >even get it working from the >>> prompt, to no avail. > >Am I doing something wrong here? > >From a quick look that[1] script, it looks like it expects to read from stdin only. I.e., it says # iterate over each line on stdin for line in sys.stdin.readlines() : ... To feed the script's stdin you'll have to redirect or pipe data to it. To pipe stuff on windows to a python script you have to run the interpreter (python) explicitly one way or another, so I would try: python count.py < foo.txt or you could pipe the output of the windows type command, like: type foo.txt | python count.py To make the script work like what you expected, it needs to look at the command line arguments (sys.argv) for a file name and open that, and use the resulting file object in place of stdin. BTW, IMO you get a nicer ouput if you change the last line of the script to print '%6d: %s' % (words[word], word) As an exercise, you could modify it to accept an option on the command line to output in order of frequency instead of alphbetically, and also accept a file name. Then look into the glob module and see if you can make it do multiple files from a wild card spec. Have fun. You may want to look at various scripts that were put on your disk when you installed, e.g. in wahtever corresponds to D:\Python22\Tools\Scripts\* on your system. Look at some small stuff first. Regards, Bengt Richter From peter at engcorp.com Mon Mar 4 19:14:28 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Mar 2002 19:14:28 -0500 Subject: Win32 2.2 & 2.1.2 References: Message-ID: <3C840DE4.B5782604@engcorp.com> Robin Becker wrote: > > Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the > default for a win32 box. It would allow us to dip a toe in the water > without drowning. I've seen the many other replies, but none pointed out that the installer with 2.2 has an "Advanced Options..." button which lets you install under the per-user area of the registry instead of the per-machine area. This, combined with telling it not to register the file extensions, might limit the "damage" to a single user on that machine. If you set up a special user just to catch the new installation, it might work reasonably painlessly. Of course, I haven't tested this approach myself so YMMS ("s" for suck...) -Peter From aahz at pythoncraft.com Sun Mar 31 20:33:29 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 20:33:29 -0500 Subject: Python/Linux References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: In article , Robert Oschler wrote: > >Forgot to ask, is Zope's database server actually MySQL under the hood? >If not, does it compare well as far as functionality and stability are >concerned? BTW, do you use Zope or Quixote? Hope you don't mind all >these question. Zope can use MySQL, but its default is to use its own object-oriented ZODB. I don't use either; I'm not much of a web developer. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From emile at fenx.com Wed Mar 27 21:03:24 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 27 Mar 2002 18:03:24 -0800 Subject: DSN question References: <13a0323e.0203271459.14905cde@posting.google.com> Message-ID: Jeremy Reed > Is there a way to programmatically create a DSN? > > I'm trying to create a program that connects to a MS SQL database > using the mxODBC package. However, I don't necessarily want to > subject the users of the program to the task of manually creating a > DSN. It seems to me that there should be some way to do it > programmatically, but I haven't been able to locate and documentation > on it. > http://groups.google.com/groups?hl=en&selm=4xDh6.66249%24bb.1038647%40ne ws1.rdc1.tx.home.com -- Emile van Sebille emile at fenx.com --------- From mats at laplaza.org Thu Mar 7 15:46:38 2002 From: mats at laplaza.org (Mats Wichmann) Date: Thu, 07 Mar 2002 20:46:38 GMT Subject: PEP 284, Integer for-loops References: Message-ID: <3c87d103.26130283@news.laplaza.org> On Wed, 06 Mar 2002 14:23:02 -0800, David Eppstein wrote: :In article , : Steve Lamb wrote: : :> Perceived lack. IE, this is a solution looking for a problem. I read it :> and really have to ask.... why? If people have a problem with it they just :> need to flip open their Python book and take a few seconds to look it up. : :The situation where I came across this perceived lack was attempting to :use Python syntax to explain the algorithms in an algorithms class :(useful exercise btw, I think the students gained from being able to see :code that actually worked instead of pseudocode, and Python allows many :algorithms to be expressed clearly without distracting the students with :lots of unnecessary pointer-banging). : :Some algorithms (especially in dynamic programming) are expressed most :naturally in terms of integer loops, the ranges of the loops are often :closed rather than open or sometimes need to go in backwards rather than :forward order. Python's range() syntax makes this awkward and detracts :from the reason I wanted to use Python: a simple syntax that expresses :algorithms cleanly and understandably, that does not force students to :buy Python books (this is very much not a programming class) or look up :unfamiliar syntax, and that also is able to run those algorithms :directly. You need to separate range() from the loop. After all, range is not specifically related to loops, it's just handy when doing for loops. I show this interactively. """Loops let you apply an operation repeatedly to a sequence of values. Conceptually, For each item in sequence, print the square of item To show this using Python, let's first generate the sequence. The range function is a handy helper: Let's use range to make a list of numbers that counts down from ten to one by ones: """ >>> seq = range(10, 0, -1) >>> print seq [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] """ Now let's see how a loop works: """ >>> for item in seq: print item ** 2 100 81 64 49 36 25 16 9 4 1 If you'e going on to teach Python, you'd tell 'em those can of course be combined. Mats Wichmann From bokr at oz.net Fri Mar 15 16:09:23 2002 From: bokr at oz.net (Bengt Richter) Date: 15 Mar 2002 21:09:23 GMT Subject: Why I think range is a wart. References: <7UYj8.31929$l93.6269941@newsb.telia.net> Message-ID: On 15 Mar 2002 11:17:39 GMT, Peter Dobcsanyi wrote: >Tim Legant wrote: >> No. Your bar() function is broken and the test results invalid. Try >> this instead: >> >> def bar(ls): >> i = 0 >> for x in ls: >> if x == '998': >> return i >> i += 1 > >Oops, you are right! I fixed it and ran the test again. > >3000 times, Python 2.2, Linux: > > i in range(len(ls)): 2.03 > x in ls; i+= : 2.28 > lambda x:zip(range(len(x)), x): 3.76 > Iter class: 10.18 > >10000 times: > > i in range(len(ls)): 6.68 > x in ls; i+=1 : 7.55 > lambda x:zip(range(len(x)), x): 12.56 > Iter class: 35.56 > >Interestingly, "range(len(ls))" is still faster. > I wonder how the proportions would change if len(ls) were 1,000,000 instead of 1,000 and/or if you used xrange in place of range. Regards, Bengt Richter From mathew at forte.jpl.nasa.gov Mon Mar 4 22:39:07 2002 From: mathew at forte.jpl.nasa.gov (Mathew Yeates) Date: Mon, 04 Mar 2002 19:39:07 -0800 Subject: Python Refactoring Browser Message-ID: I am in desperate need of a refactoring browser for python. I've written a fairly large program and now am trying to clean it up. I change a member variable and WHAM I break my code in 95 different locations. I'm aware of Bicycle Repair Man http://bicyclerepair.sourceforge.net/, which, when better developed will be exactly what I want. There is also PyIDEA http://sourceforge.net/projects/pyidea/, but it's just starting up. And Boa ( http://boa-constructor.sourceforge.net/ ) doesnt seem designed for refactoring although I have been using its automatic UML generation to give me ideas on how to reorganize classes. When I'm programming in C, I have cscope which I use with a VIM interface. Its not much but at least I can locate variables easily. Has anyone else refactored a large Python program? How did you do it? Mathew From amckay at merlinsoftech.com Mon Mar 11 17:54:43 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Mon, 11 Mar 2002 14:54:43 -0800 Subject: Zope stdin In-Reply-To: <3C8D3294.704@void.si> References: <3C8BECF0.30207@void.si> <3C8D3294.704@void.si> Message-ID: <200203112254.g2BMsBq01554@mail.merlinsoftech.com> On March 11, 2002 02:41 pm, you wrote: > > Why can you not do this in Zope as Python Script, External Method or even > > DTML? The Zope mailing lists are normally a good place for answers BTW. > > I dont know how to write it in python script, I waste a lot of time > without any progress, ok i learned something about security model, get > familiar with some Zope source code. Then I gave up and wrote it with > mod_python in a hour. I know that mod_python is not an app server, so I > will have to join yet-another-mailing list, but I am not sure that this > is posible with zope. Ok then. But for the record yes it's rather straightforward in Zope, once you've gotten over the whats going on in Zope hump :) -- Andy McKay From bbollenbach at shaw.ca Tue Mar 12 22:13:37 2002 From: bbollenbach at shaw.ca (Brad Bollenbach) Date: Wed, 13 Mar 2002 03:13:37 GMT Subject: ANN: Python User Group in Winnipeg, Canada Message-ID: Hi, I'm soliciting interest for creating a Python User Group here in Winnipeg, Canada (Guido has done me the favour of posting this advert on Python's official User Groups page, thanks again Guido :). If you're in the area, and interested in attending, please let me know of your interest by dropping me an email at: bbollenbach at shaw.ca Thanks, Brad Bollenbach Systems Developer // Python Geek bbollenbach at shaw.ca From tdelaney at avaya.com Sun Mar 3 18:21:53 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 4 Mar 2002 10:21:53 +1100 Subject: Python's Syntax Message-ID: http://www.python.org/doc/ In particular, the Python Tutorial ... http://www.python.org/doc/current/tut/tut.html Tim Delaney From JamesL at Lugoj.com Sun Mar 31 19:10:06 2002 From: JamesL at Lugoj.com (James Logajan) Date: 1 Apr 2002 00:10:06 GMT Subject: multithreading and Tkinter References: Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote: [ On a thread signalling the Tkinter mainloop thread: ] > If you want to delete the need for an after() method altogether, you > could register an after_idle callback. You can do that from a > different thread; Tkinter will call the after_idle callback from the > same thread that runs the mainloop. Has anyone ever tried using after_idle in a worker thread as a way to signal a Tkinter mainloop thread? I'm wondering if this proposal is really thread safe, since technically a worker thread is making a call to Tk (even if it is nothing more than registering a callback) while the mainloop thread may also be in the process of making calls to Tk. I haven't tried it but have been considering it, but wanted to know if this was a reasonable solution. Thanks! From ceck at lakota-tsi.com Tue Mar 19 11:38:52 2002 From: ceck at lakota-tsi.com (Cris Eck) Date: 19 Mar 2002 08:38:52 -0800 Subject: Extending Python/Tkinter Message-ID: <5acdbd0c.0203190838.20c3733e@posting.google.com> I have a C++ class that draws maps that I've been assigned to extend into python. The class uses X primitive calls (XDrawPoint, etc.) to do much of the work and I'm at a loss on how to integrate this as an extension to Python. Initially I thought I could get a drawable, display and graphics context from the Tk C API. Then I saw that Tkinter is using the Tcl interpreter and not calling the Tk routines directly. Now I'm lost. I'm a newbie to Python/Tk/Tcl and hitting info overload from looking through so many books and web pages (sorry is this is a bad question). I'm missing something crucial or this approach is half-baked or both. -c From jolsen at mailme.dk Fri Mar 1 02:23:45 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 28 Feb 2002 23:23:45 -0800 Subject: Numeric Python Installation woes References: <2dg03lvk1q.fsf@james.hut.fi> Message-ID: I do not know what is wrong, but as the error messages suggest, it seems your python 2.2 instalation is the problem. Have you otherwise tested python 2.2? Maybe you should re-install it (python 22) and get rid of the two old installations. Cheers Jesper > For some reasons even after upgrading to python 2.2 python 1.5 is > still there in the bin. > > Wishes and thankx in advance > karthik > > -- > > ----------------------------------------------------------------------- > Karthikesh Raju, email: karthik at james.hut.fi > Researcher, http://www.cis.hut.fi/karthik > Helsinki University of Technology, Tel: +358-9-451 5389 > Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 > Department of Computer Sc., > P.O Box 5400, FIN 02015 HUT, > Espoo, FINLAND > ----------------------------------------------------------------------- From evebill8 at hotmail.com Fri Mar 15 18:26:56 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Fri, 15 Mar 2002 23:26:56 GMT Subject: socket References: Message-ID: <4rvk8.18218$P4.1576669@newsread2.prod.itd.earthlink.net> > And from a pure learning perspective, that's a perfectly fine idea, > one I strongly suggest to anyone trying to understand how the Internet > works under the covers. Thanks for your support! > Also to be fair, in many cases originally VRFY would still not be 100% > accurate, since if a mail server was built to relay mail elsewhere, > then by definition it would VRFY any address that was properly formed > (but would be relayed off that machine) as being good - even if it > would eventually bounce once a message to that address was really > transmitted. In that case the VRFY was just telling you the address > was good to the machine you were talking to, but unless you were > certain that machine was responsible for final delivery of the mail, > it might not guarantee delivery. This is exactly what I encountered. Most server just check the format of the email addresses instead of existence of the users. I can't hit the box that is responsible for handling the mails. Thanks anyway! Billy Ng From jgardn at alumni.washington.edu Mon Mar 11 02:50:03 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Mon, 11 Mar 2002 16:50:03 +0900 Subject: python as gvim scripting lang -- examples please References: Message-ID: googlePoster scribbled with his keyboard: > I would like to see some example python gvim scripts > so I could get started with some simple stuff -- need access > to runtimepath, range, etc > :he python Jonathan (PS. Read all of it.) From akuchlin at ute.mems-exchange.org Wed Mar 13 10:32:24 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 13 Mar 2002 15:32:24 GMT Subject: Has Mark Hammond attained pariah status yet? References: <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: In article , Neil Schemenauer wrote: > That was AMK. It seems the Parrot guys are more interested in > micro-optimizations and adding regex support to the VM than in > supporting Python on Parrot. Too bad. To expand on that response a bit: you still can't use Parrot to implement any vaguely "real" programming language because there's no support for implementing variables. Once you've filled up all 32 PMC registers, there's no way to spill any registers to memory because there are no opcodes to do so. I'd really like to work on a Python-to-Parrot translator some more, but right now there's no point in trying to do so because there would be no way of implementing Python's scoping. Unfortunately development effort seems to be going to premature optimization -- an x86 JIT, regex opcodes, counting the cycles taken by the main loop -- instead of filling in the missing pieces, so I'm getting increasingly skeptical that Parrot will provide a useful substrate for anything. --amk (www.amk.ca) I suppose the best way to find out where you come from is to find out where you're going, and then work backwards. -- The Doctor, in "City of Death" From martin at v.loewis.de Sat Mar 2 03:25:38 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Mar 2002 09:25:38 +0100 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: bokr at oz.net (Bengt Richter) writes: > Will the following work? > > >>> print u'\u0041' > A > >>> print u'\u221e' > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII encoding error: ordinal not in range(128) > >>> With the patch to print Unicode to the Windows console, the UnicodeError will be gone. Whether or not Lucida Unicode supports that character, I cannot say. > And if I redirect the output to a file, what will be in the file? Since the isatty test fails, the system default encoding will be used. Unless you've changed that, you'll get a UnicodeError again. Regards, Martin From danieln at stud.cs.uit.no Wed Mar 13 05:20:12 2002 From: danieln at stud.cs.uit.no (Daniel =?iso-8859-1?Q?Nyg=E5rd?=) Date: Wed, 13 Mar 2002 11:20:12 +0100 Subject: dictonary Message-ID: <3C8F27DC.F69B1F54@stud.cs.uit.no> How do I insert a dictionary into a database (_mysql)? db = _mysql.connect() string = { hello:'wow', something:'nothing', nothing : 'something', number : 5, name : 'daniel'} then I have a database with the same attributes as the keys in the dict. above. How do I insert the whole dict into the database. thanks Daniel Nyg?rd From hfoffani at yahoo.com Wed Mar 27 10:48:07 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Wed, 27 Mar 2002 16:48:07 +0100 Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> <11e94203.0203232201.4dde9883@posting.google.com> <11e94203.0203261553.24850b7b@posting.google.com> Message-ID: <20020327104817.817$v3@news.newsreader.com> "Jose Rivera" escribi? > The URL calculated : > > http://avisos.elnorte.com/casa_venta_result.asp?fotos=0&Order=order+by+colo nia&Precio_i=-1&Presentacion=Tabla&Precio_f=-1&PLANTAS=0&pagina=1&id_inmueb le=3&dia=&RECAMARAS=0&constr_f=-1&COLONIA=0&BANOS=0&Tipo=CASAS&Constr_i=-1& Terreno_i=-1&Terreno_f=-1&zona=0 > > works on my PC, but: > > The first time it gives me the error that you said, but a click on the > http address of iExplorer and an enter on the keyboard load > succesfully the page. sorry, but i've got the same error here. are you sure you are not getting the page content from the cache? urllib.urlopen() is the same as opening the html page as a local file. (except of course if the site is playing with your browser using plugins, for instance.) if you still have problems, another thing you can try is to use COM to drive IExplorer from python. you'll need the win32all package or the ActiveState Python distrbution for this. but still you have to parse that page to get the data afterwards. connecting to some port/account/whatever to get the raw data, as another poster suggests, seems the way you'd want to go. regards, -hernan From maurelius01 at hotmail.com Fri Mar 22 11:25:27 2002 From: maurelius01 at hotmail.com (Marc) Date: Fri, 22 Mar 2002 11:25:27 -0500 Subject: mutlifile inheritance problem References: <9896e047.0203211303.741f695a@posting.google.com> Message-ID: <3C9B5AF7.9E9C54F2@hotmail.com> Pearu Peterson wrote: > > On 21 Mar 2002, Marc wrote: > > > class ImStream_SavedBitmaps(cbase01.CImStream): > > > > def __init__(self): > > cbase.CImStream.__init__(self) > ^^^^^ > This should be cbase01, right? > > > *************************************************************** > > > > If I run test02 I get the traceback > > > > Traceback (innermost last): > > File "", line 1, in ? > > File "D:\PythonCode\pna\eyeTracking\tests\test02.py", line 15, in ? > > x0 = wrappers_A01.ImStream_SavedBitmaps() > > File "D:\PythonCode\pna\eyeTracking\tests\wrappers_A01.py", line 21, > > in __init__ > > cbase.CImStream.__init__(self) > > TypeError: unbound method must be called with class instance 1st > > argument > > Though, I cannot explain how the above typo could cause this exception. > > Pearu Yes, this was a typo, as I explained in my response to Aahz. An unfortunate distraction because this does seem to be on odd behavior and I would like to figure it out. The problem seems to be in the reload() statement but I can't find anything in the docs or web that applies, or at least that I understand to apply. Maybe I'll ask the list again but without the typo and simplified class names. Thanks, Marc From sjh at shic.co.uk Tue Mar 26 13:03:41 2002 From: sjh at shic.co.uk (Steve) Date: 26 Mar 2002 10:03:41 -0800 Subject: calldll and threads... Message-ID: I could benefit from words of wisdom... this is the situation: I want to use Python as a high level language to write a test suite for a complex shared library (I've a windows DLL acting as proxy to remote server(s)) which has several blocking calls, and for which the interleaving and overlapping of calls is very significant. I need to drive a client to demonstrate code coverage on the server side - there is a large degree of server side interaction between concurrently executing client actions. In Python, my first attempt used thread.start_new_thread() when executing a python wrapper for a call which could block.. which I later rewrote to use threading.Thread. Initially all seemed well until I found that the whole python program blocked waiting for the first blocking call to the DLL. Then I read about the "Global Interpreter Lock" and went on to look at the source for calldll.pyd - which didn't seem to address threading. I tried following the advice in the python docs: Py_BEGIN_ALLOW_THREADS //...Do some blocking I/O operation... making sure not to use return... Py_END_ALLOW_THREADS Which I used to wrapper all calls to dll functions with a customised calldll... the above code massaged into call_foreign_function()... but I now find that while the very first call to my modified calldll seems to work fine - subsequent calls crash the python interpreter. Has anyone else had similar problems with calldll or anything like it? Can anyone explain what I've done wrong with Py_BEGIN_ALLOW_THREADS and friend? Do other people use python to script similar regression test scenarios? Is there a standard mechanism to make a blocking call from a python thread? Thanks in advance, Steve [P.S. In case it's relevant. I'm using the Python 2.2 release from www.python.org with the calldll source from www.nightmare.com running under windows NT 4 with the Win32all build 146 using PythonWin as a development environment] From logiplexsoftware at earthlink.net Wed Mar 13 12:28:57 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 13 Mar 2002 09:28:57 -0800 Subject: Has Mark Hammond attained pariah status yet? In-Reply-To: <3C8F1D74.10802@mxm.dk> References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> <3C8F1D74.10802@mxm.dk> Message-ID: <20020313092857.4765dd0d.logiplexsoftware@earthlink.net> On Wed, 13 Mar 2002 09:35:48 +0000 Max M wrote: > This could also just be a sign that there is interrest, but the people > using win32all might not be able to publish a build themself? > > Not everybody is as knowledgable as Mark, Even though we work on the > superior Windows platform ;-) And quite possibly because not many people using the superior Windows platform have a C compiler available to them. Probably due to thoughtfulness on Microsoft's part ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From bokr at oz.net Sun Mar 10 22:58:38 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Mar 2002 03:58:38 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> <3C8C2521.10B2D6D8@cosc.canterbury.ac.nz> Message-ID: On Mon, 11 Mar 2002 16:31:45 +1300, Greg Ewing wrote: >Bengt Richter wrote: >> >> Would someone explain this: >> >> >>> eval("list(r'\x07')") >> ['\x07'] >> >>> list(r'\x07') >> ['\\', 'x', '0', '7'] > >The string literal you're passing to eval is >non-raw, so the \x07 gets interpreted before >eval even sees it. Try this instead: > > >>> eval(r"list(r'\x07')") > Aaugh, touch? & d'oh. That's embarrassing ;-/ Regards, Bengt Richter From thoa0025 at mail.usyd.edu.au Sun Mar 24 06:56:55 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 24 Mar 2002 11:56:55 GMT Subject: module is in the folder - what am i doing wrong?? References: <3C9D975B.40600@SPAMnwinternet.com> Message-ID: Thanks for your reply Jim, i have a file "xml.py" and it has a function named "getProjects()" and i simply wish to access it from c. i have the source.... #include int main (int argc, char *argv[]) { // declare variables PyObject *modname = NULL; PyObject *mod = NULL; // init Py_Initialize(); modname = PyString_FromString("xml"); mod = PyImport_Import(modname); if (mod == NULL) printf("mod is null\n"); Py_XDECREF(mod); Py_XDECREF(modname); Py_Exit(0); } but when i try to run it, it prints "mod is null", meaning it cant find the module. but the module is named "xml.py" and is in the current folder!! what am i doing wrong??? i dont see why it is so hard. it's just that ive fallen in a small hole (idom).. just one of those things when you learn a new language... i just need a little help. im sure someone knows :( ive thought of using exec, but this way is far more elegant.. so i've read. but not proven. Please HELP! Cheers Trung Hoang Final year Undergraduate of Computer Science and Technology University of Sydney, Australia. From gerhard at bigfoot.de Mon Mar 25 07:35:05 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 25 Mar 2002 12:35:05 GMT Subject: communication with a java applet References: <3C9F100D.BAB4F24D@hotmail.com> Message-ID: In article <3C9F100D.BAB4F24D at hotmail.com>, Looping wrote: > Hi all, > > I am trying to make a real-time system communicate with a java applet > under IE 5.5. I only have a pyd file (Python 1.5.2) to get the floats > calculated on the platform and I wonder how to make the platform > communicate with my java applet : TCP/IP, CORBA, shared memory, > others... ? AFAIK Java doesn't have access to shared memory. Any remote procedure or object protocol will do (CORBA, XML-RPC, SOAP). XML-RPC is a very easy one, but even CORBA isn't difficult to use from Python. I'd recommend to use omniORBpy if you want to go the CORBA way. Don't worry that using a network layer is slow. If you're running both the applet and the Python app on the same machine, the OS will use the loopback interface, which is quite a bit optimized and about as fast as shared memory. Gerhard From brian at lodoss.org Mon Mar 4 04:30:34 2002 From: brian at lodoss.org (Brian) Date: 4 Mar 2002 01:30:34 -0800 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> Message-ID: <8fc4b19e.0203040130.17140530@posting.google.com> Carel Fellinger wrote in message news:... > >>> class MyClass: pass > >>> z = map(lambda x: C(), range(3)) Ahh, thank you very much. For some reason this was eluding me earlier. Clearly I need to spend more time with lambda, map & friends ;-) I'm happy with the performance of the expression too; I'm using a similar map expression as an argument to Numeric.array() now and it works very well for me. (Aside: Numeric is fun to play with!) From ralph at inputplus.demon.co.uk Sun Mar 31 07:41:59 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 31 Mar 2002 12:41:59 GMT Subject: PEP 285: Adding a bool type References: Message-ID: Hi Terry, > C. Anyone learning Python has some idea of truth and truth values. > But I am sure there are some with no idea of what 'bool' means and > only a vague idea about 'Boolean'. Better formalizing Python truth > values should make them even easier to learn; why not call them what > they are? That's an excellent point, as are the others you make. My Mum would understand true but not bool or Boolean. Ralph. From frr at wanadoo.es Sat Mar 9 12:10:14 2002 From: frr at wanadoo.es (Fernando Rodríguez) Date: Sat, 09 Mar 2002 18:10:14 +0100 Subject: Tokenize a string or split on steroids References: <4lpj8u4nbsoqjf2h4upadti62jh4sf4i59@4ax.com> <3C89F25F.A560003F@verizon.net> Message-ID: On Sat, 09 Mar 2002 11:30:40 GMT, Bob Follek wrote: >If you're unfamiliar with regular expressions, here's a good starting >point: http://py-howto.sourceforge.net/regex/regex.html Thanks. :-) BTW, the strings that must be tokenized contain other non alphanumeric characters (parenthese, for example), so I tried another regex: [{}]. The result, although usable, is sort of weird: >>> s = "{one}{two}" >>> x1 = re.compile('[{}]') >>> x1.split(s) ['', 'one', '', 'two', ''] Where are those empty strings coming from??? :-? I can filter() them out, but I wonder where they come from.... O:-) TIA | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Fernando Rodr?guez frr at EasyJob.NET | http://www.EasyJob.NET/ | Expert resume and cover letter creation system. | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From narnett at mccmedia.com Wed Mar 20 13:33:55 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Wed, 20 Mar 2002 10:33:55 -0800 Subject: Remove empty lines In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Bengt Richter > Sent: Wednesday, March 20, 2002 10:14 AM > To: python-list at python.org > Subject: Re: Remove empty lines [snip] > > > > lines=re.split("\n",str) > > > > for line in lines: # Here I try to remove the emty lines > > > > if line== '': The problem is here, I think. Split in Python appears to return the separator, so the '\n' characters are still there. If that's the problem, this should fix it. if line == '\n': At least, that's my suspicion, without testing. (In Perl, the separators are not returned by default, so if you came to Python from Perl, like me, this is confusing.) Nick From bokr at oz.net Fri Mar 1 20:38:35 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Mar 2002 01:38:35 GMT Subject: Minor, minor style question References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: On Fri, 01 Mar 2002 12:14:54 -0500, Justin Sheehy wrote: [...] >If those really are the two things being compared, there's a far >better option: > >>>> string = ("abc" >... "def" >... "xyz") >>>> string >'abcdefxyz' > I prefer >>> string = ( ... "abc" ... "def" ... "ghi" ... ) >>> string 'abcdefghi' (Oops, don't mean to say I prefer ghi over xyz ;-) Regards, Bengt Richter From max at alcyone.com Sat Mar 30 02:28:21 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 29 Mar 2002 23:28:21 -0800 Subject: PEP 285: Adding a bool type References: Message-ID: <3CA56915.62947DDC@alcyone.com> Guido van Rossum wrote: > I offer the following PEP for review by the community. If it receives > a favorable response, it will be implemented in Python 2.3. Outstanding! I've been waiting and hoping for Booleans in Python since I first was introduced to it. > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. Yes, I believe so. > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) I agree with you; having repr(True) == str(True) == "True" makes sense to me. > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). I'm also a C, C++, and Java guy, but I think that True and False (rather than true and false) are more Python, as you say, given None. Internal consistency makes more sense to me than matching other languages. > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. No strong opinion here; either solution seems acceptable to me. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. No strong opinion here either, leaning toward leaving it be. I think it should return a bool, since it's effectively converting an arbitrary expression to a Boolean, but with a bool type and the new trends toward type unification, one could write bool(expr), which should be the equivalent of operator.truth(expr) but with type bool, and is shorter. > Because the repr() or str() of a bool value is different from an > int value, some code (for example doctest-based unit tests, and > possibly database code that relies on things like "%s" % truth) > may fail. How much of a backwards compatibility problem this will > be, I don't know. If we this turns out to be a real problem, we > could changes the rules so that str() of a bool returns "0" or > "1", while repr() of a bool still returns "False" or "True". Where is the backward compatibility problem for using bool? At present, no one uses it, so none of their types will be bools (right?). Even if they happen to use the values True and False (or whatever gets adopted), those can be overridden just like None, so if they define and use them they should get their values, not Python's. Right? > It has been suggested that, in order to satisfy user expectations, > for every x that is considered true in a Boolean context, the > expression x == True should be true, and likewise if x is > considered false, x == False should be true. I agree with your assessment; I don't agree at all with this suggestion. 6 is not equal to True, even if 6 when converted to a bool is a True. Python doesn't do (and shouldn't do) this kind of implicit conversion, so the objection does not follow. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From erno-news at erno.iki.fi Sun Mar 24 12:00:35 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 24 Mar 2002 19:00:35 +0200 Subject: Memory sizes of python objects? References: Message-ID: In article , "Clark C . Evans" writes: | Is there some rule of thumb that I can use to estimate, | for example, take the character data you have and multiply by | a factor of 4 to find the in-memory footprint of tuples, and | each map is 1K plus 64 bytes per entry.. make a zillion of them, check memory usage increase with ps (or equivalent on your platform), and divide by zillion. -- erno From bokr at oz.net Mon Mar 11 01:43:42 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Mar 2002 06:43:42 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> <3C8C2521.10B2D6D8@cosc.canterbury.ac.nz> Message-ID: On 11 Mar 2002 03:58:38 GMT, bokr at oz.net (Bengt Richter) wrote: >On Mon, 11 Mar 2002 16:31:45 +1300, Greg Ewing wrote: > >>Bengt Richter wrote: >>> >>> Would someone explain this: >>> >>> >>> eval("list(r'\x07')") >>> ['\x07'] >>> >>> list(r'\x07') >>> ['\\', 'x', '0', '7'] >> >>The string literal you're passing to eval is >>non-raw, so the \x07 gets interpreted before >>eval even sees it. Try this instead: >> >> >>> eval(r"list(r'\x07')") >> >Aaugh, touch? & d'oh. That's embarrassing ;-/ > Especially since the original motivation was: +--- |So how would '\x07' (single character) be represented if it were part of pasted text? | |I guess I ought to try eval("r'\x07'") and see what happens ;-) +--- I.e., I was _intending_ to get \x07 interpreted, to simulate pasting a single control character into a raw string. In another post I just did it directly: +--- | >>> '^G','\x07',r'^G' | ('\x07', '\x07', '\x07') | |... where I typed Ctrl-G binary data into the source where the screen rendered ^G. +--- I just fooled myself looking at all those list results ;-/ Regards, Bengt Richter From martin at v.loewis.de Sun Mar 3 15:53:12 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 03 Mar 2002 21:53:12 +0100 Subject: C++, Python & Threads References: <1015181073.276455@seux119> Message-ID: "VUG" writes: > When I launch python console and I create a thread I get a NUMBER but...... > This number doesn't the same as the one I get by the function > thread.get_ident(). What's wrong in the code? PyThread_get_thread_ident, having no parameters, always returns the thread id of the calling thread. If you want the thread id of the new thread, you need to invoke PyThread_get_thread_ident inside of the new thread. BTW, in Python 2.2, start_new_thread does return the thread id of the new thread. HTH, Martin From clpy at snakefarm.org Mon Mar 18 05:02:17 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Mon, 18 Mar 2002 11:02:17 +0100 Subject: locale module broken? References: <3C928042.BA50A5B3@snakefarm.org> Message-ID: <3C95BB29.41317483@snakefarm.org> Martin von Loewis wrote: > > Oleg Broytmann writes: > > > I reproduced this behviour on Debian 2.2 with all version of Python - > > 2.0, 2.1 amd 2.2... but only with FR locale. With ru_RU locale it works > > perfectly. It seems glibc has got broken FR locale. > > That must have been fixed in more recent versions of glibc then; on > Debian-testing, it works fine. On the other hand, the most recent versions of glibc (2.2.{4|5}) have a (known) bug in the handling of IPv6. Since I need a working IPv6 implementation more than a working French locale I'll stick to glibc 2.1.3. :-) cg. -- For dealing with Matrix you need something more powerful than Python. Otherwise ... Matrix has you! -- scenes from comp.lang.python From ffjhenon at club-internet.fr Sat Mar 16 06:30:05 2002 From: ffjhenon at club-internet.fr (Fabien =?iso-8859-1?Q?H=E9non?=) Date: Sat, 16 Mar 2002 12:30:05 +0100 Subject: Linux endline References: <3C932C41.2974C1DA@club-internet.fr> Message-ID: <3C932CBD.6493FB6C@club-internet.fr> Here is the complete application from Tkinter import * from tkFileDialog import askopenfilename, asksaveasfilename import sys, os, string plat=sys.platform class mainWin: def __init__(self,tkRoot): self.tkRoot=tkRoot self.createWidgets() return None class App: ## ---------------------- Create GUI ---------------------- def __init__(self, master): ## ---------------------- Mainframe ---------------------- mframe = Frame(master) mframe.pack(expand=1, fill=BOTH) frame_input=Frame(mframe) ## ---------------------- Menu ---------------------- menubar=Menu(frame_input) filemenu=Menu(menubar,tearoff=0) filemenu.add_command(label="New",command=self.clr) filemenu.add_command(label="Open",command=self.enter_text) filemenu.add_command(label="Save",command=self.save) filemenu.add_command(label="Save As") filemenu.add_separator() filemenu.add_command(label="Quit",command=sys.exit) menubar.add_cascade(label="File",menu=filemenu) editmenu=Menu(menubar,tearoff=0) editmenu.add_command(label="Cut") editmenu.add_command(label="Copy") editmenu.add_command(label="Paste") menubar.add_cascade(label="Edit",menu=editmenu) rendermenu=Menu(menubar,tearoff=0) rendermenu.add_command(label="Render", command=self.render) menubar.add_cascade(label="Render",menu=rendermenu) root.config(menu=menubar) ## ---------------------- Buttons ---------------------- frame_buttons=Frame(mframe) self.button_open = Button(frame_buttons, text="Open..", fg="blue", command=self.enter_text) self.button_open.pack(side=LEFT) self.button_render = Button(frame_buttons, text="Render..", fg="red", command=self.render) self.button_render.pack(side=LEFT) self.button_render = Button(frame_buttons, text="Command line..", fg="blue", command=self.parameters_) self.button_render.pack(side=LEFT) frame_buttons.pack(expand=0, fill=BOTH) ## ---------------------- Editor ---------------------- self.text = Text(frame_input) self.yscroll_i = Scrollbar(frame_input,orient=VERTICAL, command=self.text.yview) self.yscroll_i.pack(side=RIGHT, fill=Y) self.text['yscrollcommand']=self.yscroll_i.set self.text.pack(side=LEFT,expand=1, fill=BOTH) self.text.bind("", self.keyPress) self.yscroll_i.pack(side=RIGHT, fill=Y) frame_input.pack(expand=1, fill=BOTH) ## ---------------------- Output ---------------------- frame_output=Frame(mframe) self.text_out = Text(frame_output,state=DISABLED,height=6) self.text_out.pack(side=LEFT,expand=1, fill=BOTH) self.scroll = Scrollbar(frame_output, command=self.text_out.yview) self.text_out.configure(yscrollcommand=self.scroll.set) self.scroll.pack(side=RIGHT, fill=Y) frame_output.pack(expand=0, fill=BOTH) ## ---------------------- Status Bar ---------------------- frame_status_bar=Frame(mframe) self.status = Label(frame_status_bar, bd=1, relief=SUNKEN, textvariable=affi_Ligne) self.status.pack(side=RIGHT, fill=NONE, expand=0,anchor=E) frame_status_bar.pack(expand=0, fill=NONE) ## ---------------------- Open file ---------------------- def enter_text(self): if plat=="win32": l=1 self.filename = askopenfilename() if self.filename: self.text.delete(1.0, END) fd = open(self.filename) for line in fd.readlines(): l=l+1 self.text.insert(END, line) fd.close() elif plat=="linux-i386": l=1 self.filename = askopenfilename() if self.filename: self.text.delete(1.0, END) fd = open(self.filename) for line in fd.readlines(): l=l+1 self.text.insert(END, line) # self.text.insert(END, line[:-1]) fd.close() ## ---------------------- Clear ---------------------- def clr(self): self.text.delete(1.0, END) ## ---------------------- Saveas ---------------------- def save(self, forPrt=None): script = self.text.get(1.0, END) if script: if forPrt: file = 'prt.tmp' else: self.filename = file = asksaveasfilename(initialfile= \ self.filename) fd = open(self.file, 'w') for line in string.split(script, '\n'): fd.write(line) fd.write('\n') fd.close ## ---------------------- Render ---------------------- def render(self): os.system("povray +i/home/f/povray35/scenes/advanced/chess2.pov +w320 +h240 -f +dgt") ## ---------------------- Top-Level Command line ---------------------- def parameters_(self): self.tl=Toplevel() self.lb=Label(self.tl, text="Render parameters:") self.cl=Entry(self.tl,width=40) self.ok=Button(self.tl, text="OK", fg="red", command=self.get_parameters) self.ok.pack(side=BOTTOM) self.cl.pack(side=RIGHT) self.lb.pack() def get_parameters(self): params=self.cl.get() print params ## ---------------------- Prints the current line number and contents ---------------------- ## Line number def lin(self): tindex = self.text.index(INSERT) Ligne, column = map(int, string.split(tindex, ".")) valeur="Line : %d" %int((Ligne)) affi_Ligne.set(valeur) ## ---------------------- Called when a key is pressed ---------------------- def keyPress(self,event): self.lin() root = Tk() affi_Ligne=StringVar() #params=StringVar() larg = root.winfo_screenwidth() haut = root.winfo_screenheight() root.maxsize() # root.geometry("%dx%d+0+0" % (larg,haut)) app = App(root) root.mainloop() Fabien H?non a ?crit : > I am writing a POV-RAY editor which can be used with Windows or Linux. > > 1? When I use it under Linux I would like to get rid of the \r which > appears at the end of each line. ( I know there is a difference of > endline between Windows, Mac and Linux). > > I added a slice, but it doesn't seem to work. > I tried to use > self.text.insert(END, line[:-1]) > But it does not help > In short how do I get rid of endline in *nix > > ---- > def enter_text(self): > if plat=="win32": > l=1 > self.filename = askopenfilename() > if self.filename: > self.text.delete(1.0, END) > fd = open(self.filename) > for line in fd.readlines(): > l=l+1 > self.text.insert(END, line) > fd.close() > elif plat=="linux-i386": > l=1 > self.filename = askopenfilename() > if self.filename: > self.text.delete(1.0, END) > fd = open(self.filename) > for line in fd.readlines(): > l=l+1 > self.text.insert(END, line) # self.text.insert(END, line[:-1]) > fd.close() > ----------- > > 2? One more thing, I'd like to add syntax highlighting with braces, > parentheses,.... matching. > I'd like to know it is feasible to implement it. > > 3? Is there a way to fire up an external application (like POV or a > modeler) in background or as a sub-thread : > When I start POV from within the application, I have to wait for the > raytracing to be over to use the editor again. > > I use > os.system("application_to_run") > > Thanks for any help From taw at dnaco.net Mon Mar 4 19:33:05 2002 From: taw at dnaco.net (Tim Widowfield) Date: Mon, 4 Mar 2002 19:33:05 -0500 (EST) Subject: pyperl -- Arrays to Lists? ...Tuples? In-Reply-To: Message-ID: I hope it's not impolite to answer one's own question. I got around the tuple problem by forgoing the PerlModule construct and using Perl more directly. Once you've said 'import perl', 'perl.require("MyMOD")', and then somthing like: obj_handle = perl.callm("new", "MyMOD", params) ...you can finally say: thingy = perl.callm_tuple("method", obj_handle, param1, param2, ...) ...and your thingy will definitely come back as a tuple. --Tim Widowfield, taw at dnaco.net On Sat, 2 Mar 2002, Tim Widowfield wrote: > Greetings: > > I hope I'm not missing something obvious, but here goes. I'm calling a > Perl module from a Python script with the aid of pyperl. Pretty much > everything works as expected, but functions with array return values keep > giving me strings in Python. In particular, the string is the last value > in the returned array. > > I've tried wrapping the function call with "tuple" and "list", but that > only causes the string to break itself up into individual letters. How > can I force pyperl to understand I'm expecting an array of values and not > just a single string? Has anyone seen this before? > > Thanks in advance. > > > --Tim Widowfield, > taw at dnaco.net > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From trentm at ActiveState.com Wed Mar 13 15:22:47 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 13 Mar 2002 12:22:47 -0800 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: ; from mwh@python.net on Wed, Mar 13, 2002 at 06:16:11PM +0000 References: Message-ID: <20020313122247.A15069@ActiveState.com> [Michael Hudson wrote] > Perhaps. I'm a bit scared of bugzilla (on the admin side). Touche. I don't have to deal with that here. We use bugzilla for (almost) all of our bug tracking here at ActiveState. > > p.s. I am gonna regret feeding this. > > Huh? I suspected that this might turn into one long fruitless discussion over what would be a good bug tracking app for Python. Fruitless because I don't see Python moving away from SF's tracker any time soon. Trent -- Trent Mick TrentM at ActiveState.com From dubois at users.sourceforge.net Fri Mar 22 14:30:50 2002 From: dubois at users.sourceforge.net (Paul F. Dubois) Date: Fri, 22 Mar 2002 19:30:50 GMT Subject: Porting a Python app to IRIX -- need help Message-ID: I am trying to get a Python-based app running on an SGI running IRIX 6.5. I am running into a problem involving some objects being compiled "n32" and others "o32". The linker refuses to link them. I got pretty far by setting environment variable CC to "cc" but then it complained that the X11 library is o32. Can an SGI person tell me whether o32 or n32 is "normal" and what I tell the compiler to be sure I get that? From edream at tds.net Sat Mar 9 13:02:26 2002 From: edream at tds.net (Edward K. Ream) Date: Sat, 09 Mar 2002 18:02:26 GMT Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> <3C8A4810.85A56A1@tds.net> Message-ID: <3C8A4E30.3666F1F1@tds.net> > (after all, you also said "These will be my last words on this > subject" in an earlier post... ;-) OK. I lied :-) If you think a logger is a good idea, go for it. I'll happily abide by the will of the community. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From zihong at earthlink.net Mon Mar 11 11:36:16 2002 From: zihong at earthlink.net (Zihong Lu) Date: Mon, 11 Mar 2002 16:36:16 GMT Subject: win32 extension: rare PythonService problem References: Message-ID: <425j8.12275$Vx1.979312@newsread1.prod.itd.earthlink.net> I also thought it might be due to the permission problem. But when I checked the mahine's registry entries, and the user's access authorities, they seem to be fine. The user has system administrator auth to the machine, and the installation did write to the registry as expected. Correct, the event log logged a error for the service when I tried to start. No more meaningful information except saying return 1. -Zihong "Bengt Richter" wrote in message news:a6grvo$h4o$0 at 216.39.172.122... > On 10 Mar 2002 21:55:37 GMT, bokr at oz.net (Bengt Richter) wrote: > [...] > >But I'd check the event logs (run "%SystemRoot%"\system32\eventvwr.exe) first > > Oops, misplaced quote, that won't work verbatim. Try > > "%SystemRoot%\system32\eventvwr.exe" > > Or (at least on NT4), find it via start>programs>adminstrative tools>Event viewer > > Regards, > Bengt Richter From martin at v.loewis.de Sun Mar 17 14:46:57 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Mar 2002 20:46:57 +0100 Subject: Windows NT shell + extended characters. Bug or what? References: Message-ID: Wolfgang Strobl writes: > >This is rather unlikely, I doubt the interactive interpreter will ever > >be able to properly identify the encoding of the console window. > > What's wrong with GetConsoleOutputCP, besides the restrictions > documented in "Q99795 SetConsoleOutputCP Only Effective with Unicode > Fonts"? There are several problems with that: - as you point it, it fails for the raster fonts (for no apparent reason) - for outputting Unicode, OutputConsoleW is more appropriate, IMO, since it can also output characters not supported in the output code page. - we were talking about input. Admittedly, GetConsoleCP might be of use here - it is tricky to determine reliably that a file descriptor is connected to a terminal. Regards, Martin From trentm at ActiveState.com Wed Mar 13 21:00:37 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 13 Mar 2002 18:00:37 -0800 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: <200203140116.BAA01141@crown.off.ekorp.com>; from rjones@ekit-inc.com on Thu, Mar 14, 2002 at 12:16:16PM +1100 References: <200203132236.WAA11518@crown.off.ekorp.com> <20020313154713.A30850@ActiveState.com> <200203140116.BAA01141@crown.off.ekorp.com> Message-ID: <20020313180037.D25807@ActiveState.com> [Richard Jones wrote] > > Can you attach files to issues/bugs > > in the new Roundup? > > Yep - via the web or email interfaces. Cool. Sorry for the FUD. I'll try to check it out. Trent -- Trent Mick TrentM at ActiveState.com From Janssen at rz.uni-frankfurt.de Sat Mar 2 12:47:10 2002 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sat, 02 Mar 2002 18:47:10 +0100 Subject: Stedents Question References: <3c80126f_1@news.iprimus.com.au> Message-ID: <3c811073@nntp.server.uni-frankfurt.de> Tony K wrote: > The question below is a tutorial question that stumps me. Any suggestions > would be appreciated. > Tony > > Write a Python function findABBC which takes a single string as parameter > and returns all substrings thereof which match the regexp pattern ab+c. > You are NOT allowed to use the re module. def findABBC(str): a=0 b=0 while str: for n in str: if n=="a": a=1 break if a==1 and n=="b": b=b+1 break if a==1 and n=="c": print "a"+"b"*b+"c" a, b = 0, 0 break if n!=[a-c]: a, b = 0, 0 break str=str[1:] produces every ab+c-string in str. But there must be something easier. Something smaller ;-) Michael From gerritvd at decillion.net Tue Mar 26 04:37:36 2002 From: gerritvd at decillion.net (Gerrit van Dyk) Date: Tue, 26 Mar 2002 11:37:36 +0200 Subject: win32com makepy problem Message-ID: <3CA04160.7080406@decillion.net> Hi all, I have the following problem using the office 9.0 object library. When I generate the Office 9.0 Object library using makepy the following code does not work, but when I use the dynamic dispatch method it does. How do I solve the problem using the early bound dispatch method as I need early binding for other features (constants etc)? This method is defined in my server class and the self.application attribute points to a valid Excel.Application instance 1:def AddCustomMenu(self): 2: cbMenuBar = self.application.CommandBars("Worksheet Menu Bar") 3: muCustom = cbMenuBar.Controls.Add(Type = 10) # msoControlPopup 4: 5: muCustom.Caption = "Toolkit" 6: 7: item = muCustom.Controls.Add(Type = 1) # msoControlButton 8: item.Caption = "Show Data Form" The problem is on line 7. muCustom is of type CommandBarControl in the early binding case. In the late(dynamic) binding case it is a CommandBarPopup. CommandBarControl does not have a Controls property where CommandBarPopup does. How can i rectify the problem? (typecast ?) How? Regards Gerrit van Dyk From jbauer at rubic.com Mon Mar 11 17:42:35 2002 From: jbauer at rubic.com (Jeff Bauer) Date: Mon, 11 Mar 2002 16:42:35 -0600 Subject: NormalDate 1.2 released Message-ID: <3C8D32DB.A3E0D7FC@rubic.com> NormalDate 1.2 is available from: http://starship.python.net/crew/jbauer/normaldate/ NormalDate is a specialized class to handle dates without all the excess baggage (time zones, daylight savings, leap seconds, etc.) of other date structures. The minimalist strategy greatly simplifies its implementation and use. NormalDate is a pure Python class and is therefore portable to Jython, Windows CE devices, etc. It has been in use in one form or another by many users, judging from email, since 1997. The 1.2 release includes an important bugfix for Python 2.2. Jeff Bauer Rubicon Research From scott.l.hathaway at lmco.com Fri Mar 22 08:39:06 2002 From: scott.l.hathaway at lmco.com (Scott Hathaway) Date: Fri, 22 Mar 2002 07:39:06 -0600 Subject: a website information gathering script Message-ID: <3C9B33FA.3D853D65@lmco.com> I have a simple python script which gathers information about a website and produces an html report about what it finds. The way it works is very clunky and I would appreciate some feedback and help improving it. http://www.hcsprogramming.com/downloads/index.html Thanks, Scott Hathaway From martin at v.loewis.de Mon Mar 18 11:08:55 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Mar 2002 17:08:55 +0100 Subject: HP-UX, PyThread_* missing References: <1016327182.366474@cswreg.cos.agilent.com> <3b091a1c.0203180642.69cc22b3@posting.google.com> Message-ID: cmkleffner at gmx.de (cmkl) writes: > HP-UX 10.20 has user threads, HP-UX 11 has kernel threads (a POSIX threads > implementation by HP) - and AFAIK HP-UX 10.30 has it. > HP-UX 10.20 has located s subset of pthread call's in libcma - not enough > for Python2.2. But I can remember, that prior python versions (2.0, 1.5.2 ??) > could configured with threads. I can't test it anymore, because I have only > access to HP-UX 11.00 at the moment. > Another problem is, that the dynamic loader is not thread-safe in 10.20 > (but it is in 10.30 and above) - see 'HP-UX Linker and Libraries Users's Guide' > > But in principle HP-UX 10.20 supports threads (user threads or green threads) > and it is used i.e. with Java for HP-UX. Different people report different results. Python still has the machinery to link with -lcma, and for some people, it reportedly figured that out correctly. For some people, the 2.2 configure apparently fails because it picked up the wrong preprocessor - I don't know why that would happen. Some people see crashes (in the testsuite) due to unexpected signals. I believe that these originate from the fact that the user-level thread library uses signals in certain cases, and this may interfere with signal handlers that the signal test installed. Of course, this is pure guesswork. Regards, Martin From tdelaney at avaya.com Wed Mar 13 23:51:22 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 14 Mar 2002 15:51:22 +1100 Subject: Performance problem with filtering Message-ID: > From: Sheila King [mailto:usenet at thinkspot.net] > > On Thu, 14 Mar 2002 15:06:09 +1100, "Delaney, Timothy" > > wrote in comp.lang.python in article > : > > > Bah ... > > > > results = filter(lambda k: not c.has_key(k), b) > > > > That will slow it down a bit (using the lambda) but will > give the right > > result ;) > > How does something with list comprehensions compare? Like: > > b = [entry for entry in b if entry not in a] > > Is this as slow as the original method suggested? Or is it closer to > dictionary performance? Essentially, that is identical to the original method. Simply expand it out ... (need to use a temporary name though). temp_b = [] for entry in b: if entry not in a: temp_b.append(entry) b = temp_b del temp_b Tim Delaney From flognat at flognat.myip.org Tue Mar 19 04:15:11 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Tue, 19 Mar 2002 09:15:11 GMT Subject: Chewing international (unicode) filenames on windows? References: <3C96F705.50908@skippinet.com.au> Message-ID: | > For me on my windows 2000 machine, to get them into UTF-8 format I do | > something like: | > for filename in os.listdir(): | > utffilename=unicode(filename, "latin-1").encode("utf-8") | | utffilename=unicode(filename, "mbcs").encode("utf-8") Hello! So do I get it right now, reading it as mbcs ("Multibyte-character") will read all ntfs filenames correctly (as unicode defines it) into a unicode string? | > p.s.2 what is the status on win9x? Give it up or ;-) | | I *think* it still works when accessing a Unicode aware file system | (ie, network) What I want is to read a local file-name on a win9x fat/fat32 disk and be able to convert it into unicode.. And the other way around. I will probably add a if windows9x do that, else if win2k do this.. ;-) Hmm how do I determine windows-version? /Andy -- The eye of the beholder rests on the beauty! From neal at metaslash.com Mon Mar 18 18:08:16 2002 From: neal at metaslash.com (Neal Norwitz) Date: Mon, 18 Mar 2002 18:08:16 -0500 Subject: Declare list of large size References: Message-ID: <3C967360.C128670A@metaslash.com> Aaron Ginn wrote: > > Perhaps I've just glossed over this in the documentation, but what is > the simplest way to declare a list of large size? Is there something > analogous to the following in C: > > int list[100]; > > I can do this by doing the following: > > list = [] > i=0 > while i < 100: > list.append[0] > i = i + 1 > > which will give me a list 100 elements long with all values > initialized to 0, but I'm assuming there has to be an easier way to do > this? Am I correct in this assumption? Yes: >>> [0]* 100 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> Neal From gimbo at ftech.net Wed Mar 20 07:06:18 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 20 Mar 2002 12:06:18 +0000 Subject: Python embedded like PHP In-Reply-To: <7xk7s7mpiy.fsf@ruckus.brouhaha.com> References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> Message-ID: <20020320120618.GC18197@andy.tynant.ftech.net> On Wed, Mar 20, 2002 at 03:45:09AM -0800, Paul Rubin wrote: > >
      > >
    • > > surname > >
    • > >
    > Geez, I find all this pseudo-HTML horrendous. Why not just embed It's not pseudo-HTML, it's W3C compliant HTML (is " tags. -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From chad.maine at broadlink.com Fri Mar 1 18:06:07 2002 From: chad.maine at broadlink.com (Chad Maine) Date: Fri, 01 Mar 2002 23:06:07 GMT Subject: Multple HTTPS requests over the same socket Message-ID: I have class that opens an SSL socket to an HTTPS server in it's __init__. I then call a class method to send the headers and make the request ( a 'POST') and return the results. If I try to use that same SSL socket again for another request, I get nothing. Is what I'm trying to possible or do I need to close the socket and open another? From jjv5 at yahoo.com Tue Mar 19 15:33:36 2002 From: jjv5 at yahoo.com (jjv5) Date: 19 Mar 2002 12:33:36 -0800 Subject: How to count pixels of a color in an image? Message-ID: <6b7cc392.0203191233.26760fc2@posting.google.com> A simple question perhaps. Any help is appreciated. I need to count the number of pixels that are purple or blue-green in a large image. I can do this with the Image module easily enough, but it is painfully slow. I do something like this: green=0 purple=0 dat = im.getdata() for i in range(len(dat)): r,g,b = dat[i][0],dat[i][1],dat[i][2] green = green + (( b>r) and (g>r)) purple = purple + ((r>g) and (b>g)) The slow part is the for loop over the image data. Even if the loop body is empty it still takes about 15 seconds on a fast computer. the getdata function takes about 3 seconds. Surely there is a better way. The image is about 3800 by 3000 pixels. Any suggestions? Jim From mwh at python.net Sun Mar 3 11:53:50 2002 From: mwh at python.net (Michael Hudson) Date: Sun, 3 Mar 2002 16:53:50 GMT Subject: Useful, robust shell utilities References: Message-ID: Jonathan Gardner writes: > I tried to use the shutil module... and to tell you the truth, it > stinks. Yep. > Is there an effort to make a robust, useful shutil module that has > the equivalent of the unix shell utilities? Not that I know of. distutils.file_utils does a better job of some things. Writing "shutil2.py" has been on my todo list for months, at least. It would be nice to make it as portable as possible. > I think it would be nice to make things like 'grep' even... That's going waaay beyond what I had in mind. > Here is my wish list. Each of these should implement a significant portion > of what the GNU utils do. They should be robust, and give reasonable > results, and reasonable exceptions. > > touch, chmod, chown, chgrp, touch These are in os, or easy to fake. > df, du I'm not sure these are really worth the effort. Implementable in python using os functions. > cp, dd, install, mv, rm, shred Now this is what I was talking about. > If there isn't an effort to make this, or if no one has done > anything like this yet, I am willing to volunteer some time to do > it. That would be good. My time is pretty much all volunteered. > It would be really nice if they ended up being compatible with > Windows and Macintosh - give them some powerful tools they didn't > even know existed! The one philosophy I'd managed to come up with was "ask the OS to do as much as possible". I think a good first step would be to post an interface sketch. Cheers, M. -- Remember - if all you have is an axe, every problem looks like hours of fun. -- Frossie -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From ykingma at accessforall.nl Sat Mar 30 16:23:54 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sat, 30 Mar 2002 22:23:54 +0100 Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: Message-ID: <3CA62CD8.6ABD44D0@accessforall.nl> Guido, you wrote: > > I offer the following PEP for review by the community. If it receives > a favorable response, it will be implemented in Python 2.3. > Thanks for this opportunity. > http://python.org/sf/528022 > > --Guido van Rossum (home page: http://www.python.org/~guido/) > > PEP: 285 > Title: Adding a bool type > Version: $Revision: 1.12 $ > Last-Modified: $Date: 2002/03/30 05:37:02 $ > Author: guido at python.org (Guido van Rossum) > Status: Draft > Type: Standards Track > Created: 8-Mar-2002 > Python-Version: 2.3 > Post-History: 8-Mar-2002, 30-Mar-2002 > > Abstract > > This PEP proposes the introduction of a new built-in type, bool, > with two constants, False and True. The bool type would be a > straightforward subtype (in C) of the int type, and the values > False and True would behave like 0 and 1 in most respects (for > example, False==0 and True==1 would be true) except repr() and > str(). All built-in operations that conceptually return a Boolean > result will be changed to return False or True instead of 0 or 1; > for example, comparisons, the "not" operator, and predicates like > isinstance(). > > Review > > Dear reviewers: > > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. Partially. I think there is no point in maintaining backward compatibility of the assumptions that True == 1 and False == 0. Please don't subtype int to define bool. Within the language a 'cast to boolean' should be implied when a boolean value is expected (ie. after 'if' and 'while'). This is in line with the current situation. Making this cast to boolean explicit in the language definition even simplifies the language definition. > > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) > str(True) should return "True". > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). > Caps. > Most other details of the proposal are pretty much forced by the > backwards compatibility requirement; e.g. True == 1 and > True+1 == 2 must hold, else reams of existing code would break. > This can be handled by deprecation and eg. 'from __future__ import bool', or by unundeprecation: 'from __past__ import nonbool'. This might seem rather radical, but in C a similar thing has happened: the compiler would silently cast a C int to a C pointer in earlier versions of the language. Nowadays no C programmer would even dare to think that way. > Minor additional issues: > > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. > 28+isleap(y) might seem reasonable now, but one should hope/assume that Python outlives C at which point it will/would be just ballast. Some other arguments against 28+isleap(y): - explicit 28+int(isleap(y)) is better than implicit. - here isleap should have been called onewhenleap in the first place. - a current boolean function might return eg. a non empty list or an Ellipsis to indicate a True return value, resulting in an appropriate TypeError here. A bool is a bool and an int is an int. The only relation between them is that they have to be implemented using bits of a computer. Python is sufficiently high level not to care about the bits. Python never had a C float type, only a C double type, for precisily this reason. Somehow this reminds me of subclassing Square from Rectangle: it just doesn't feel right, even though it might work. One should avoid subclassing a class that has instantiations. Could someone provide a reference for this with a title that ends in 'considered harmful'? > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. > Predicates should return a bool. > Rationale > > Most languages eventually grow a Boolean type; even C99 (the new > and improved C standard, not yet widely adopted) has one. > > Many programmers apparently feel the need for a Boolean type; most > Python documentation contains a bit of an apology for the absence > of a Boolean type. I've seen lots of modules that defined > constants "False=0" and "True=1" (or similar) at the top and used > those. The problem with this is that everybody does it > differently. For example, should you use "FALSE", "false", > "False", "F" or even "f"? And should false be the value zero or > None, or perhaps a truth value of a different type that will print > as "true" or "false"? Adding a standard bool type to the language > resolves those issues. > > Some external libraries (like databases and RPC packages) need to > be able to distinguish between Boolean and integral values, and > while it's usually possible to craft a solution, it would be > easier if the language offered a standard Boolean type. > That would be nice. Currently in jython one has to use java.lang.Bool to call an overloaded java method that is defined with both a java boolean and with a java int as argument. This does not happen too often, but mapping a python bool to (and from) a java bool sure sounds good. > The standard bool type can also serve as a way to force a value to > be interpreted as a Boolean, which can be used to normalize > Boolean values. Writing bool(x) is much clearer than "not not x" > and much more concise than > > if x: > return 1 > else: > return 0 > That would be great, however such functions should not be named as predicates, they should be named onewhen... > > Compatibility > > Because of backwards compatibility, the bool type lacks many > properties that some would like to see. For example, arithmetic > operations with one or two bool arguments is allowed, treating > False as 0 and True as 1. Also, a bool may be used as a sequence > index. > The only reason that it works now is the C heritage as explained above. Why not use this as an opportunity to get rid of it? With a non int bool, True and False would be real singletons: bool(1) is True bool(0) is False True is not 1 True != 1 False is not 0 False != 0 Subclassing bool from int would also force 1 and 0 to be become real singletons. The only reason this would work is that current python implementations happen to implement 1 and 0 in this way. This is related to subclassing an instantiated class, which should be avoided, I think. > I don't see this as a problem, and I don't want evolve the > language in this direction either; I don't believe that a stricter > interpretation of "Booleanness" makes the language any clearer. But you could make the language definition simpler by explicitly defining the cast to bool in contexts where a boolean is expected, see above. This would allow the current casts (eg. list to bool as non empty) to be described at the standard types instead of in the language definition. > Another consequence of the compatibility requirement is that the > expression "True and 6" has the value 6, and similarly the > expression "False or None" has the value None. The "and" and "or" > operators are usefully defined to return the first argument that > determines the outcome, and this won't change; in particular, they > don't force the outcome to be a bool. Of course, if both > arguments are bools, the outcome is always a bool. It can also > easily be coerced into being a bool by writing for example > "bool(x and y)". These would work in the same way with a "non int" bool as I would prefer to have. Regards, and thanks again for the opportunity, Ype. From cfox at crystalcherry.com Fri Mar 15 21:24:39 2002 From: cfox at crystalcherry.com (Colin Fox) Date: Sat, 16 Mar 2002 02:24:39 GMT Subject: Zope Question Message-ID: Hi, everyone. I realize that this isn't the best place to post Zope questions, but hey, it's written in python...:) Anyway, I'm trying to create a form for editing database entries. Part of the form includes a pair of radio buttons for gender. I want to seed this from with values from the database. The problem is, radio buttons have a special attribute called 'checked' to indicate when they are selected. The Zope page templates allow me to alter things of the form ' value="xxx" ', but apparently not where the keyword itself is the value. If there was something like 'state="CHECKED"', it would be easy. But I can't figure out how to insert either CHECKED or nothing depending on the state of a variable. And unfortunately, none of the example templates I've seen show how to do this. Any ideas? TIA -- Colin Fox cfox at crystalcherry.com CF Consulting Inc. GPG Fingerprint: D8F0 84E7 E7CC 5C6C 9982 F1A7 A3EB 6EA3 BC97 572F From aahz at panix.com Sat Mar 9 10:43:19 2002 From: aahz at panix.com (Aahz Maruch) Date: 9 Mar 2002 07:43:19 -0800 Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> Message-ID: In article <3C894E28.BB2CCE7B at tds.net>, Edward K. Ream wrote: > >PEP 282 talks about control flow, levels, loggers, handlers, formatters, >filters and configuration. A case can be made for dealing with each >issue, and experience shows that simple dynamic tracing suffices in >complex apps like compilers and file systems. For example, all kinds of >configuration (including picking formatters, data sinks, altering the >flow of control of the program being run, etc.) can be done just by >initializing the dict of tracepoint names. > >Dynamic tracing provides the essential benefit of any logging system, >namely the ability to alter tracing output without altering the program >being traced. It does so in the simplest and most general way. The problem that your solution fails to solve is the need for three basic levels of output: debug, warn/info, error. A single function may want to provide all three levels, but users of that function may not want to see all three all the time. They will almost certainly want error traces to be active almost all the time. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From gmcm at hypernet.com Thu Mar 28 08:24:00 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 28 Mar 2002 13:24:00 GMT Subject: problems with circular references References: Message-ID: jimh wrote: > Here is the problem: Most of these 50 classes need to use the > MessageCatalog themselves. This means, of course, that classA imports > MessageCatalog which imports classA. This doesn't work very well. As long as MessageCatalog uses a plain "import ...", this should work fine. The import that completes the circuit can't use "from ... import ...", because symbols inside the module aren't available until all the imports complete. You can often use delayed imports (imports inside function or method bodies) to break the circularity, too. -- Gordon http://www.mcmillan-inc.com/ From psage at ncaustin.com Tue Mar 26 17:29:12 2002 From: psage at ncaustin.com (Paul Sage) Date: Tue, 26 Mar 2002 16:29:12 -0600 Subject: TKinter question - A combo box / menu question Message-ID: <03F53405C6ED434A986221919785A6A7106BE9@nca-postal.ncaustin.com> First, let me apologize for sending this in HTML the first time. I have had a few responses on this, but nothing turns up. Basically, I want to pop-up a ComboDialogBox as a result of a Menu selection. What I am doing is creating the ComboDialogBox everytime it gets to the "command" portion of the Menu option. Here is most of the relevant code: class mainWindow: #Build the components into the main window def __init__(self, master): # Begin creation of the main menu items here. # File section. mbar = Menu(master, tearoff=0) master['menu'] = mbar frameForDialog = frame(master, N) file_menu = Menu(mbar, tearoff=0) file_menu.add_command(label='Load Form', command=self.open_file(frameForDialog)) file_menu.add_command(label='Save Form', command=self.save_file) file_menu.add_command(label='New Form', command=self.new_file) file_menu.add_separator() file_menu.add_command(label='Quit', command=self.quit_file) mbar.add_cascade(label='File', underline=0, menu=file_menu) # End top pull down menu selections. statEditorFrame = frame(master, N) statEditor = StatEditor(statEditorFrame) def open_file(self, parent): #Need the listofcharacters to be a tuple sequence. from char_edit_combo_load import * forms = [] listOfCharacters = tuple(getFiles(forms)) dialog = Pmw.ComboBoxDialog(parent, title = "Character Load", buttons = ('OK', 'Cancel'), defaultbutton = 'OK', combobox_labelpos=N, label_text="Please select a character", scrolledlist_items=listOfCharacters, listbox_width=22) dialog.withdraw() result=dialog.activate() # The function has now opened seen the selection, time to open the file. if result == 'OK': return(readObjectFromFile(dialog.get())) else: return(None) def save_file(self): #This will save the file off print('SF: Stub') def quit_file(self): #This will save the file off print('SF: Stub') def new_file(self): #This will save the file off print('NF: Stub') def add_level(self): #This will save the file off print('SF: Stub') def subtract_level(self): #This will save the file off print('NF: Stub') root=Tk() root.title('Character Generator') Pmw.initialise() topWindow = mainWindow(root) root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From ljohnson at resgen.com Wed Mar 13 17:34:08 2002 From: ljohnson at resgen.com (Lyle Johnson) Date: Wed, 13 Mar 2002 16:34:08 -0600 Subject: SWIG and python References: <6bd9f01b.0203131336.24c93fa8@posting.google.com> Message-ID: > I've downloaded SWIG1.3.11, and 1.3.10 for linux from sourceforge, and > after installation, swig -version tells me that I am running SWIG1.1. > Are the version #s just not updated or what? Yes, the version numbers have been updated. You obviously still have an older SWIG executable somewhere in your path (ahead of the SWIG 1.3.x executable). Try typing "which swig" to see which one you're actually running and then blow that copy away, or rename it, whatever. From uwe at rocksport.de Sun Mar 24 13:45:12 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 24 Mar 2002 18:45:12 GMT Subject: advanced Python References: <3C9E6058.8D3EFE6F@gol.ge> Message-ID: Giorgi Lekishvili wrote: | Hello! | I wonder if someone prompts me a book dedicated to the advanced topics | of python? | Something tailored a-la "Advanced C++" by James O. Coplien... What about "Python Programming Patterns" by Christopher... Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From eppstein at ics.uci.edu Wed Mar 6 19:26:55 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 16:26:55 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , "Delaney, Timothy" wrote: > > PEP 276 [4] proposes to allow automatic conversion of integers to > > iterators, simplifying the most common half-open case but not > > addressing the complexities of other types of interval. > > Additional alternatives have been discussed on python-list. > > This is incorrect. PEP 276 proposes to make integers iterable. There is a > significant difference, which I have noticed you either not understanding or > ignoring. > > I would suggest an amendment to PEP 284 to correct this. When you say "incorrect", do you mean that "making integers iterable" is different from "allowing automatic conversion of integers to iterators"? It was my understanding that "for x in y" and "if x in y" converted y to an iterator automatically, by calling iter(y) if necessary. Integers can be made iterable now, by calling range() on them, but that is not automatic. In what way would you propose rewording the PEP? If it's just "PEP 274 [4] proposes to make integers iterable, simplifying..." that seems unobjectionable enough. From huaiyu at gauss.almadan.ibm.com Fri Mar 8 19:29:02 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Sat, 9 Mar 2002 00:29:02 +0000 (UTC) Subject: Is current integer for-loop syntax a wart? References: Message-ID: - Not a wart: 1. It is very clear what it does. 2. range() can be used elsewhere. No new syntaxes. 3. In most situations you loop over list of items instead of counters. - Wart: When you do need the index, neither of the following is very nice looking: for i, x in zip(range(len(a)), a): b[i] = x for i in range(len(a)): b[i] = a[i] So the wart is the way indices are generated, not how the for-loop is constructed. I think the iter(n) proposal addresses the right problem, but the solution is too broad: it produces iterators in many uninteded places. Two ideas that I do like: for i, x in items(a): b[i] = x for i in indices(a): b[i] = a[i] They address the right problems at minimum cost. They can be extended to xitems and xindici, of course. Huaiyu From vincent_a_primavera at netzero.net Fri Mar 1 06:49:40 2002 From: vincent_a_primavera at netzero.net (Vincent A. Primavera) Date: 01 Mar 2002 11:49:40 +0000 Subject: C-ISAM... Message-ID: <1014983381.22216.3.camel@del-vap-bos.ralphpill.com> Hello, Does anyone know of a module/api to access records from a C-ISAM database? Thank you, Vincent A. Primavera. From aahzpy at panix.com Wed Mar 13 13:55:32 2002 From: aahzpy at panix.com (Aahz) Date: 13 Mar 2002 13:55:32 -0500 Subject: Another socket/thread question References: Message-ID: In article , Ken wrote: > >I've got a thread that continously listens to a socket, and reports what it >receives. Blocking is turned on, and I would like it to stay that way since >the only thing the thread has to do, is listen to the socket. > >My question is when the socket needs to be closed (program shuts down, or >that user is being disconnected by the server) is it possible to interupt a >socket.recv ()? > >If not, whats the easiest way to cut processor time from looping endlessly >with blocking turned off? http://www.timo-tasi.org/python/timeoutsocket.py -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From amuys at shortech.com.au Wed Mar 13 20:24:51 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 13 Mar 2002 17:24:51 -0800 Subject: Why I think range is a wart. References: Message-ID: <7934d084.0203131724.79f3f51f@posting.google.com> Gon?lo Rodrigues wrote in message news:... > On 13 Mar 2002 12:53:50 -0500, com-nospam at ccraig.org (Christopher A. > Craig) wrote: > > >Gon?alo Rodrigues writes: > > > >> For starters, range (and xrange) is a perfectly sensible, reasonable and > >> useful built-in. But the biggest use I make of it is in iterating through > >> a list, e.g. as in > >> > >> for index in range(len(mylist)): > >> > >> > >> and in the body I need to make use of the indexes. I am not > >> sufficiently qualified to say if this is Pythonic or not, but I find > >> myself doing this quite often. > > > >I don't understand how range is a reasonable and useful built-in if > >this use is not. > > There are other useful, reasonable and sensible uses for the range > built-in. My comment is that this particular use looks warty to me > because any sequence, especially if it obeys the "list-protocol" (that > is, it has methods like __getitem__, __setitem__, etc.) should be able > to generate the indexes (or keys) of its members. Just like a > dictionary. > > > > >If you have a list [2, 3, 5, 7, 11] and you want to iterate through it > >you don't need range: > > > >for item in list: > > > > > >If, on the other hand, you want to iterate though the indicies of said > >list rather than the items themselves you need to come up with some > >way to generate a zero based list of integers up to one less than the > >size of the list (i.e. a list of indicies). When you create this list > >you aren't doubling information that the list already has. A list > >does not contain a list of indicies into itself. The list knows its > >elements, in order, and how many elements it has. From this you can > >generate a list of indicies, but there are no 'keys' stored in a list > >object like there are in a dictionary. > > This is where I beg to disagree. If the elements are in order, as they > are in a list, it is perfectly reasonable to ask, "you are a list, > right? then hand me the indexes of your members." If the list has the > keys in memory or not, that is an implementation issue. I dissagree, if you want the indexes attached to their items, ask for it zip(range(len(lst)), lst) If it's a large list, use xrange/xzip respectively. I am curious what sort of programs you are writing where you so regularly care what the index of a list item is? Such concerns are not in my experience. If I want an array I'll use an array, but if I'm using a list it's as a sequence. I honestly can't work out what the problem is. Andrae Muys From mgash at trisystems.co.uk Thu Mar 21 07:27:04 2002 From: mgash at trisystems.co.uk (Mark Gash) Date: Thu, 21 Mar 2002 12:27:04 -0000 Subject: How Can I Determine the Operating System with Python? Message-ID: <31575A892FF6D1118F5800600846864DCC7760@intrepid> * Mark Hadfield [2002-03-21 14:02 +1200]: > "Jill Obsidian" wrote in message > news:cc779aae.0203201733.3717f882 at posting.google.com... > > > How can I put a check in my script which will allow me to determine > > whether I'm running on Win << File: message.txt >> ows or Linux at execution time? > > >>> import sys > >>> sys.platform > 'win32' > >>> import os > >>> os.name > 'nt' That's a crude way of determining the platform, because sys.platform depends on the compiler used to compile Python. Yes, even on Windows. But I'm reasonably sure that the Pythonlabs folks won't change their Windows compiler anytime soon. I'd very much like to have a real way for determining the platform. Anybody wants to write a PEP? :-) Gerhard The only way of defining the os name that I have found is then to examine the os.environ .By examining the COMSPEC you will be able to determine a win 9X machine opposed to an NT or 2000 machine (comspec for 9X will show command.com whereas win32 machines will show cmd.exe). BUT I would like to 'second' Gerhard's suggestion of having a real way for determining the platform. Kind Regards, Mark Gash Consultant TriSystems Ltd. 020 7264 0440 mgash at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From fredrik at pythonware.com Sat Mar 16 11:50:20 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 16 Mar 2002 16:50:20 GMT Subject: Linux endline References: <3C932C41.2974C1DA@club-internet.fr> Message-ID: Fabien H?non wrote: > 1? When I use it under Linux I would like to get rid of the \r which > appears at the end of each line. ( I know there is a difference of > endline between Windows, Mac and Linux). how about if line.endswith("\r\n"): # deal with DOS file ending line = line[:-2] + "\n" self.text.insert(END, line) > 3? Is there a way to fire up an external application (like POV or a > modeler) in background look up "os.spawn" in the library reference. From kseehof at neuralintegrator.com Thu Mar 21 18:53:11 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Thu, 21 Mar 2002 15:53:11 -0800 Subject: __file__ for relative imports In-Reply-To: Message-ID: > Robin Becker writes: > > > Is there an obvious reason why modules imported from the current > > directory don't have an absolute pathname for __file__? > > No. I think there's a bug on sf about this. > > It would be a bit of a pest to implement, I think, but I may be > missing something. > > Cheers, > M. I keep bumping into that one too. I can't think of any advantage for the current semantics, so I am submitting a PEP. I didn't see a bug in sf or an existing PEP, but I might have missed something so please let me know. Seems like a PEP is more appropriate than a bug report though. I can't think of any reason for it to be difficult to implement. Seems like the code that assigns to __file__ in the first place could simply call abspath(), which should give correct results at load time. Seems like this PEP would probably only require one line of code. - Ken Seehof From eppstein at ics.uci.edu Sat Mar 30 13:04:17 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Sat, 30 Mar 2002 10:04:17 -0800 Subject: PEP 285: Adding a bool type References: Message-ID: In article , ralph at inputplus.demon.co.uk (Ralph Corderoy) wrote: > > > Not in Guido's eyes . We don't need 3 equivalent ways to > > > turn an arbitrary expression into a bool ("bool(x)" same-as "not > > > not (x)" same-as "truth(x)"). *Especially* if str(bool) and > > > repr(bool) produce 'True' and 'False', people have a legitimate > > > need to make an arbitrary true/false expression produce 0 and 1 > > > too, if only to preserve 0/1-based true/false output. > > > operator.truth() has always been the best way to do exactly that. > > > Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and > > > "(0, 1)[boolexpr]" reek in comparison. > > > > Tim must be missing something. The obvious way to turn a bool b into > > an int is int(b). Having to import the obscure 'operator' module for > > this purpose is backwards. (IMO there's almost *never* a reason to > > import that module anyway.) > > I thought Tim was trying to map a range of integer values onto just 0 > and 1 as ints, not False and True, where as you're suggesting he just > wants to get an int from a boolean. I think he has an expression like > day_of_month, e.g. 30, and wants a 0 or 1 from it. > > I could easily be wrong here. If that's what he's doing, int(bool(x)) is still much clearer than the alternative bool-to-int expressions that (as he says) reek. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From brian at lodoss.org Tue Mar 5 02:38:01 2002 From: brian at lodoss.org (Brian) Date: 4 Mar 2002 23:38:01 -0800 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <8fc4b19e.0203040130.17140530@posting.google.com> Message-ID: <8fc4b19e.0203042338.141afe8b@posting.google.com> Carel Fellinger wrote in message news:... > If it's performance and not code obfuscation you're after, maybe you'd > better spent some time on profiling it. Thanks Carel, I'll file your earlier suggestion under "code obfuscation" then :) Do you also feel my original code is better in terms of style or would it be even better as the more verbose: z = [] for i in xrange(y): z.append(MyClass()) OK - now I have another question (and remember I'm new to Python) if map and lambda are part of the core language and have well defined behavior, why is it that using them is considered bad form? Are they just the redheaded step-children of the language, or what? ;-) From nospam at bigfoot.com Tue Mar 19 07:00:40 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 19 Mar 2002 13:00:40 +0100 Subject: #define equivalents and config files References: Message-ID: There's no python preprocessor. You can make "safe" config files for simple values (numbers, strings, simple lists) with the ConfigParser standard package. It's use and API are described in the standard Python doc. "Dave Swegen" a ?crit dans le message news: mailman.1016530410.32451.python-list at python.org... > Is there a pythonic way of doing something similiar to Cs #define? I'd > like to have what essentially is a header files with easily modifiable > values (these will then be used to give default attribute values to > various classes). Or are globals the only way to go? > > Cheers > Dave > From lac at strakt.com Sat Mar 9 16:59:51 2002 From: lac at strakt.com (Laura Creighton) Date: Sat, 09 Mar 2002 22:59:51 +0100 Subject: should i learn it first ? In-Reply-To: Message from "Qiang.JL" of "Sat, 09 Mar 2002 20:01:44 GMT." References: Message-ID: <200203092159.g29LxptB025367@ratthing-b246.strakt.com> > Q > > Do you guys not agree to master C/C++, a large amount of time will be > required (somewhere on the net i saw it's appro 3-4 years. whew!!) > In one i want to learn it but on the other this time consuming issue scare > me .as the bad tradeoff -- it's smarter to use a language that uses the > machine's time less efficiently, but your time much more efficiently. > > am i whining? , :-) You aren't whining. This is the biggest argument in favour of using Python rather than any other language on the planet (though there are some fans of LISP and Smalltalk who will want to say MINE too!). I don't know of a single person who considers themselves excellent in C++ who also knows Python who doesn't also consider themselves to be more productive in Python than they are in C++. And we are talking 5, 6, 10 times as productive in Python. > > and one more question, what's you view of "you have mastered a language" ? > knowing syntax and grammer is the begining to master, then know how to use > them(wisely) and coding coding ... after certain long time , that you call > you master the language? As the same data structure and programming mind > almost apply to any language, i never so sure if i master a language or > not, and only feel i can use this or that language do the job. Or maybe this > can be said there is no such thing you master the language, It's only you > know this language better and have more experience with it. You need to spent a lot of time fixing the bad programs written by people who are learning a language before you can say that you have mastered it. You need to know more than 'how I alone can use it to make wonderful programs', but instead 'how to write code so that other people, including other people I have not met, can adapt the programs I made in ways I never envisioned'. When you are a Master, other people get better just because you are around -- and when you are an exaulted Master other people get better, all the time, just to read your code. > > Those are the questions poping up in my head once in a while when i am > tempted by some fance widely used languages and wondering should i give it a > go by putting aside the one i am using which i am not sure if i've mastered > it yet. > > sincerely thanks any input which will help me explore the programmer world > ..... > > Q. If you do a Google search of comp.lang.python of articles written by me that mention C++, you will rapidly discover that I hate the language. This is because I used it all the time, not because I never learned or mastered the language. (C on the other hand, I love. But not for writing application programs in.) I do not think there is a single concept in programming that you need C++ to learn; every one that exists there you could learn just as well in some other language. And I truly worry about somebody who worries about 'using his own time effectively' programming in C++. C++ is the language where you trade programmer hours to make code that runs very, very, fast. If only the fastest code will do for your needs, then C++ may well be the language for you. But it is a language to suffer for. It _wants_ the kind of dedication where you are willing to make the heroic effort; C++ programmers suffer all the time. It is a very macho language that way. And C++ programmers get to say 'ha ha, my language is harder to use than yours is, so I am a tougher, stronger, better programmer than you are'. And some of them say that a lot. It's harder to kill your own antelope dinner with a club as well ... If, against this advice, you decide to go master C++ next, could you do us a favour and remember Python? There are a great many people in this world who decided one day that they would learn C++, hated it, and to this day believe that they hate programming, and are no good at it, when they only hate C++. If this starts to happen to you, remember Python and come back. I guarantee you will enjoy learning Python more than C++. Laura Creighton From philh at comuno.freeserve.co.uk Sat Mar 9 15:05:31 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 9 Mar 2002 20:05:31 +0000 Subject: should i learn it first ? References: Message-ID: On Sat, 09 Mar 2002 11:44:45 GMT, Qiang.JL wrote: >Hi,all > >apologize if this is off-topic :) > >I am a student who have learned perl,java and other like data structure >stuff. Now i want to take some further step to learn one or two languages to >improve my language view. There are two languages are on the list: python >and C++ >I have heard a lot ppl talk about C/C++,saying it's the must language to >learn for a programmer. Firstly, C and C++ are separate languages. C++ is mostly a superset of C. Both languages are popular and widely used. Some people would argue that you can't be a "real programmer" unless you know C++. I personally would consider someone who knows several langs including C++ to be much more of a programmer than someone who just knows how to write simple screens in VB with a little behind-the-scenes code. As to what you should learn *next*, I'd guess it depends on what sort of programs you are expecting to write in the near future. C and C++ are used mostly for similar sorts of things; Python for other sorts of things. >and i indeed feel so. but C/C++ is hard and may need >to take longer time to learn and get the concept.also, Python seems a good >language and easier to learn. It certainly is. >I think some of you may come cross this, so let me ask you these questions > >do i need to learn C/C++ to be a good programmer? That depends entirely on what you mean by "good programmer". >which one is better to start with ? ( I'm not a program beginner so python >being a beginner programmer maybe not be applied here) You could do it either way... personally I'd go for Python first. >How many language do you think one should _master_? If you want to be as good at programming as you can be, then as many as possible. You should certainly have written a significant amount of code in at least 10. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From grante at visi.com Mon Mar 11 14:12:06 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Mar 2002 19:12:06 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> <3c8b8112.27836128@news> <3c8cf137.2639944@news> Message-ID: In article <3c8cf137.2639944 at news>, brobbins333 at shaw.ca wrote: > I understand and agree with what you are saying. However, it is > possible in some languages (VB, for example) to return a numerical > result from a function with only two (or any other number) of decimal > places. If the language is using BCD representation then this is true. If it's using binary FP, the this is not true. Some languages have BCD math support. Back in CP/M days, most language implimentations (BASIC, FORTRAN, Pascal, whatever) supported either BCD floating point or binary floating point. The BCD support was often called "financial mode" or something opaque like that. Python doesn't have BCD (at least not in the standard distro). > Not a formatted string representation, but an actual numerical > value that can be used in further calculations. This value is, of > course, an approximation and has really been truncated rather than > "rounded." Either it's BCD and really does have "decimal places" or it's binary FP, and it's exactly the same as what you get in Python. I'll take your word for it that VB is using BCD. > Anyway, we are arguing now over how many angels can dance on the head > of a pin. Not really. Proper use of floating oint and functions like round() require that the underlying representation is understood. -- Grant Edwards grante Yow! I'm rated PG-34!! at visi.com From martin at v.loewis.de Wed Mar 27 06:23:12 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Mar 2002 12:23:12 +0100 Subject: [Python-Dev] RE: RELEASED: Python 2.2.1c2 In-Reply-To: References: Message-ID: "Frank Patz" writes: > > Note for AIX users: there are still problems with AIX in this release, > > and there has not been time to repair them without fear of breaking > > platforms that currently work. Hopefully by the time of the release > > of 2.2.1 final we will be able to provide a recipe that allows AIX > > users to build and run Python. > > [...] > > Hmm, can someone shed more light on this issue? I think this is a red herring: Some user, for some reason, does not have cc_r. According to a number of other AIX users, cc_r should always be available, so it appears to be an installation bug of the AIX system in question. I don't think it deserves fixing. Regards, Martin From cd.cd at wanadoo.fr Sat Mar 30 06:44:12 2002 From: cd.cd at wanadoo.fr (Cyr) Date: Sat, 30 Mar 2002 12:44:12 +0100 Subject: Problem with Tkinter References: Message-ID: Thanks a lot for the help, I will try it. By the way, do you know which path is used to search for Tk libraries ? Can I change it manually in the Module/Setup file (after I ran ./configure) ? Best Regards, Cyrille DUMORTIER "Martin v. Loewis" wrote in message news:m3pu1nui7l.fsf at mira.informatik.hu-berlin.de... > "Cyr" writes: > > > Python has been installed on another station in a common directory and > > Tkinter works great on the other station. But the Tk library isn't in a > > common directory. On this station (srv0023), I only have Tcl/Tk 8.0 (and no > > library in the directories mentioned in the error message). Is there any way > > I can configure python so that it would use Tk 8.0 library on the station > > but continue to use Tk 8.3 on the other station ? > > It is possible, but difficult. You need to compile _tkinter.so twice, > once linking it with Tk 8.0, and once linking it with Tk 8.3. That > requires that you have both versions installed on the build station, > including header files for both versions. > > > In fact, I wonder how I can change the path search for the Tk > > library within python. > > You need to edit Modules/Setup to direct make to a specific Tkinter > location. In doing so, you must uncomment the *shared* line in Setup, > since it will otherwise build _tkinter directly into the Python > executable. > > HTH, > Martin > From adam at gliwice.pl Tue Mar 19 18:05:45 2002 From: adam at gliwice.pl (Adam Przybyla) Date: 19 Mar 2002 23:05:45 GMT Subject: Serial Ports References: <3c96c220$1_1@news.iprimus.com.au> Message-ID: Dietmar Lang wrote: > Hi! > Jamie Carl wrote: >> I'm still fairly new to Python so forgive me. I'm hoping someone can >> point in the right direction regarding how I would go about accessing a >> serial com port from Python. I'd like to do it mainly under Linux, but >> hopefully it will work under windows aswell. >> >> Is it possible? Can someone point me to some documentation or code samples? > Check out the Universal Serial Port Python Library: > http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html ... or http://kgr.pl/uspp-0.2.tar.gz ;-) Regards Adam Przybyla From skip at pobox.com Fri Mar 15 16:41:46 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 15 Mar 2002 15:41:46 -0600 Subject: Optimising list comparison In-Reply-To: References: Message-ID: <15506.27290.218605.524319@12-248-41-177.client.attbi.com> Graham> A friend of mine is using Python in a research project where he Graham> needs to compare each element of two vectors, such that ... Graham> Now, having read Skip M's python optimisation page ... which is getting quite dated... ;-) Graham> Neither of us have yet managed to come up with anything to beat Graham> it (we've been timing the alternatives over 100000 itterations). Graham> Any hints? Psyco . I added these lines at the end of your benchmark script: import psyco psyco.bind(attempt1) psyco.bind(attempt2) benchmark(attempt1) benchmark(attempt2) and ran it again. I got 100000 iterations of took: 8.673 secs 100000 iterations of took: 19.812 secs 100000 iterations of took: 1.546 secs 100000 iterations of took: 20.121 secs die-map-die-ly, yr's, -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From cfelling at iae.nl Sat Mar 2 13:17:25 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 2 Mar 2002 19:17:25 +0100 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: David Eppstein wrote: > In article , ... > But that wouldn't be as useful for iterating backwards through lists. > Which is what most of this seems to be directed at, rather than anything to > do with integers per se, so I wonder why we are trying to convert integers > into lists of indices rather than converting the lists directly. But then you would need yet another parameter to an enhanced range or the yet to come indici to indicate you want to iterate in reverse, like: for i in range("spam", reverse=1): pass for in in indici("spam", reverse=1): pass The nicety of the enhanced iterating-integers proposal is that it gives a very easy spelling of two of the more frequent usages of iterating over the (range of the:) length of something once you accept that integers can count (up/down) and that `count' is spelled `iter' in Python. Still haven't made up my mind on that last one:) -- groetjes, carel From richard at stockcontrol.net Wed Mar 27 15:52:43 2002 From: richard at stockcontrol.net (Richard Walkington) Date: 27 Mar 2002 12:52:43 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: <2144d9df.0203271252.1ea1cf0b@posting.google.com> >>> John Shipman reveals new Tkinter and PIL documentation >>> http://groups.yahoo.com/group/python-list/message/129319 >>> 84 pages in Postsvript or PDF format Don't know about anyone else but the link to Tkinter documentation mentioned above didn't work for me. Found this link on google: http://groups.google.co.uk/groups?hl=en&selm=99en42%242vl6%241%40newshost.nmt.edu From wall at adinet.com.uy Fri Mar 8 09:35:07 2002 From: wall at adinet.com.uy (Walter Moreira) Date: Fri, 8 Mar 2002 11:35:07 -0300 Subject: Announce: RPy (R from Python) Message-ID: <20020308113507.A2855@casa.parque> Hello. I wrote a small extension module for using the R programming language from within Python. It makes it possible to use the huge mathematical and statistical library of R from Python, almost whitout any changes from the text of R manuals. As a side effect, it is also possible to use the full graphics capabilities of R, which are extremely good. You can download it from: http://www.cmat.edu.uy/~walterm/rpy It is in distutils format. I attach a fragment of the README below. Regards: Walter -- -------------- Walter Moreira <> Centro de Matematica <> Universidad de la Republica email: walterm at cmat.edu.uy <> Home Page: http://www.cmat.edu.uy/~walterm RPy 0.1 - Python interface to the R Programming Language 1. WHAT IS RPy? RPy is a very simple, yet robust, interface to the R Programming Language (http://www.r-project.org). It can manage all kinds of R objects and can execute arbitrary R functions (including the graphic functions). All the errors from the R language are converted to Python exceptions. Any module that later were installed on the R system, can easily be used from within Python, without introducing any changes. Currently it works only under Linux/Unix. This code is inspired in RSPython from the Omegahat project (http://www.omegahat.org/RSPython). [...snip...] 3. USING RPy For details see the file USING. As a quick example, try the following session: >>> from rpy import * >>> >>> l = [r.dchisq(x, 4) for x in r.seq(0, 10, by=0.1)] >>> r.par(ask=1, ann=0) >>> r.plot(l, type='lines') and voila!, the graph of the density of a chi squared distribution with 4 degrees of freedom should appear. Refer to the file USING for more info on the interface, and to the R Programming Language manuals, which can be found on http://www.r-project.org In general, every line of the R manuals can be translated almost directly to Python. See the conversion directives in section 5 of file USING. From gerson.kurz at t-online.de Sun Mar 24 14:46:31 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sun, 24 Mar 2002 19:46:31 GMT Subject: The OOM-Killer vs. Python Message-ID: <3c9e2b5f.9993062@news.t-online.de> I have a python-based SMTP server (see http://p-nand-q.com/shicks.htm) running on our server, and in general it has worked flawless (since about nov 2001). However, in the recent week that dreaded linux OOM killer twice killed the python process. [The machine has 768mb ram - call me oldfashioned but that SHOULD be enough for both Linux & Python to get along, really. OK, its running KDE, and has only 256mb for swap, but still...] Anyway, even though I believe that this is more of a fault of the Linux Kernel VM quality than the script (the system has been running fine for months and now two kills in one week - that smells fishy to me) - how CAN I controll the memory usage for pythons GC? Is there a way to easily find out in python which memory is allocated at runtime, and by which objects? From ajeru at vknn.org Sun Mar 3 14:00:33 2002 From: ajeru at vknn.org (Alexander Jerusalem) Date: 3 Mar 2002 11:00:33 -0800 Subject: mx odbc result strings with special characters? References: <24c39b2c.0203021850.7679418c@posting.google.com> Message-ID: <24c39b2c.0203031100.33d57b3d@posting.google.com> Ok, thanks for your reply. Here's my output: >>> import mx.ODBC.Windows as odbc >>> con = odbc.connect("se", "scienceexile", "x") >>> c = con.cursor() >>> c.execute("select * from country") >>> print c.fetchone() ('aa1', '\xd6sterreich-Ungarn', None, None) >>> c.close() >>> con.close() And it's the same when I write the resultset to a file, so I don't believe that it's just a display problem. The data comes from an oracle database and the encoding and stringformat settings don't seem to have any effect. Alexander Gerhard H?ring wrote in message news:... > Le 02/03/02 ? 18:50, Alexander Jerusalem ?crivit: > > Hi, > > > > I'm using the mxODBC package to query a database that contains german > > umlauts. The result strings conatain hex codes instead of umlauts. > > I've played around with encoding and stringformat values but to no > > avail. Any hints? > > Yes. Post an example from an interactive Python session. > > It's not unlikely that everything is just fine but your terminal doesn't > show the umlauts. > > Gerhard From aahz at panix.com Mon Mar 11 11:10:23 2002 From: aahz at panix.com (Aahz Maruch) Date: 11 Mar 2002 08:10:23 -0800 Subject: Is Python an object based programming langauge? References: Message-ID: In article , Graz Bukanoff wrote: > >Is Python an object based programming langauge? Yes. Next question? -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From markus at ibp.de Fri Mar 22 04:44:02 2002 From: markus at ibp.de (Markus Redeker) Date: 22 Mar 2002 10:44:02 +0100 Subject: Popular style document? References: <1016641355.370859@cswreg.cos.agilent.com> <3C9A797E.E6476BEE@spam.nada.kth.se> Message-ID: "Terry Reedy" writes: > Short answer: the language has to work together as a whole. This is a good answer to _many_ Python questions... -Markus From joost_jacob at hotmail.com Fri Mar 22 05:03:33 2002 From: joost_jacob at hotmail.com (J.Jacob) Date: 22 Mar 2002 02:03:33 -0800 Subject: eval of a private attribute References: <3C998F89.66DB1290@infomaniak.ch> <13285ea2.0203210814.7287a5db@posting.google.com> Message-ID: <13285ea2.0203220203.5396e709@posting.google.com> Looking at the other posts the other class i did post can be improved upon. Here is a class for mixin use with a method getAttribute for 'safe' access to attributes, maybe somebody can improve on it still ? # file: GetAttribute.py class GetAttribute: """ A class for 'safe' access to attributes, see method getAttribute(). """ def __init__(self): "__init__() is here only for demonstration purposes." self.__user = "~briner/big/usr.rdb" self.public_user = "thatsme_public" def getAttribute(self, var): """ Get attribute with name 'var', even if "hidden" behind two underscores. Return None if no attribute with the name var exists. """ if hasattr(self, var): p = getattr(self, var) else: try: p = getattr(self, '_%s__%s' % (self.__class__.__name__, var)) except AttributeError: p = None return p if __name__ == '__main__': p = GetAttribute() print p.getAttribute('public_user') # get a public attribute print p.getAttribute('user') # get a 'private' attribute print p.getAttribute('nosuchuser') # get a nonexisting attribute From tejarex at yahoo.com Tue Mar 5 22:32:54 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Wed, 06 Mar 2002 03:32:54 GMT Subject: Nested scopes: design or implementation? References: Message-ID: "logistix" wrote in message news:vcfh8.405$tL.70 at nwrddc02.gnilink.net... > Is the following code operating this way by design or is it just > implementation? It seems to indicate that the nested function is redefined > each time the parent function is called. Is this necessary or desirable? It is consistent with the Python execution model. 'def' is an *executable* statement, not a declaration. When 'def' occurs and is encountered at module level, it is executed. When a function is called, *all* the statements within (except 'global' declarations) are executed as encountered. Terry J. Reedy From wurmy at earthlink.net Sat Mar 2 20:42:25 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Sun, 03 Mar 2002 01:42:25 GMT Subject: PEP 234 little bug? References: <3c817238@nntp.server.uni-frankfurt.de> Message-ID: <3C817FC1.A155DBAB@earthlink.net> Michael 'Mickey' Lauer wrote: > > Just read through some of the already implemented PEPs. > > PEP 234 (iterators) states: > > > - It has been proposed that a file object should be its own > > iterator, with a next() method returning the next line. This > > has certain advantages, and makes it even clearer that this > > iterator is destructive. The disadvantage is that this would > > make it even more painful to implement the "sticky > > StopIteration" feature proposed in the previous bullet. > > > > Resolution: this has been implemented. > > I can't see a next() in a file object. Shouldn't it be > "Resolution: this has not been implemented." ? Hm, I don't think so. I think it does not say that the *file* object should have a next() method... rather, it says that it's its own iterator, and the iterator has the next() method. Maybe the wording could have been a bit more careful, but essentially it's true what is says. And iterating over files has indeed been implemented in 2.2. -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From djc at object-craft.com.au Mon Mar 25 09:09:44 2002 From: djc at object-craft.com.au (Dave Cole) Date: 26 Mar 2002 01:09:44 +1100 Subject: [albatross-users] Re: Python embedded like PHP In-Reply-To: <1017000019.3094.31.camel@localhost> References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> <1017000019.3094.31.camel@localhost> Message-ID: > For this problem, I think the solution is in the interpreter -- your > macros are just hard to work with (from what I can see), because > they are dynamically scoped and being used in lieu of real > functions. It's not a syntax issue. I would really like it if you could explain a little further. The macros do sort of work like functions in that they pass arbitrary template content to the macro for substitution at the location specified by the macro. I tried to work out a simple way in which values from the execution context namespace could be passed as arguments but couldn't see how to do it in a nice fashion > I'm not sold on all the benefits of ZPT either, but I think it's a > natural fit for the particular case of replacing an attribute value. > To me,
    reads pretty well, and > should make some intuitive sense even if you don't understand the > scripting itself. All attributes are kind of hidden, and the > dynamic statement is no more hidden than the thing it is replacing. I agree. My biggest problem with ZPT was the control flow. > Also, you're left with a mostly-intact tag -- al-td isn't an HTML > tag, and software that understands HTML won't understand that tag. > That means you can't preview the unrendered code in a browser and > you can't let a WYSIWYG editor touch it. The reason for the al- prefix is to allow the regex parser to recognise the tag in amongst the plain HTML tags. - Dave -- http://www.object-craft.com.au From neal at metaslash.com Mon Mar 18 16:05:35 2002 From: neal at metaslash.com (Neal Norwitz) Date: Mon, 18 Mar 2002 16:05:35 -0500 Subject: Generating getter methods with exec References: <3C964E1A.84D5A26B@ndh.net> Message-ID: <3C96569F.8E76FA6E@metaslash.com> Stefan Schwarzer wrote: > > I would like to generate some getter methods in a class which in fact > access a stored dictionary. Unfortunately, I'm not able to get it work. > > Suppose the following code is in getter_test.py: > > class GetterTest: > def __init__(self): > self._dict = {'key1': 'one', > 'key2': 'two', > 'key3': 'three'} > > def _make_getters(self, dict_name, key_list): > for key in key_list: > code = ( "def %(key)s(self):\n" > " return self.%(dict_name)s['%(key)s']\n" % > vars() ) > print code > # this seems to be wrong but what should that be? > exec code in globals(), self.__dict__ > > def key3(self): > return self._dict['key3'] > > In the interpreter (Python 2.2) I get: > > >>> import getter_test > >>> gt = getter_test.GetterTest() > >>> gt._make_getters('_dict', ['key1', 'key2']) > def key1(self): > return self._dict['key1'] > > def key2(self): > return self._dict['key2'] > >>> gt.key1() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: key1() takes exactly 1 argument (0 given) > > As can be seen, gt.key1() doesn't behave as expected (at least as > expected by me ;-) ). > > >>> gt.key1(gt) > 'one' > > This works, but needs an additional instance parameter which corresponds > to this observation: > > >>> gt.key1 > > > though I would rather like > > >>> gt.key3 > > > > Can anyone tell me how I can generate the evaluated code as bound > methods instead of functions? Many thanks in advance for any help! :-) You don't need to generate code. This should do what you want: class GetterTest: def __init__(self): self._dict = {'key1': 'one', 'key2': 'two', 'key3': 'three'} def __getattr__(self, attr): try: return self._dict[attr] except KeyError: raise AttributeError, "getting attribute '%s'" % attr >>> g = GetterTest() >>> g.key1 'one' >>> g.key2 'two' >>> g.key3 'three' >>> g.key4 Traceback (most recent call last): File "", line 1, in ? File "", line 8, in __getattr__ AttributeError: getting attribute 'key4' Neal From avv at quasar.ipa.nw.ru Tue Mar 12 19:57:35 2002 From: avv at quasar.ipa.nw.ru (Alexander V. Voinov) Date: Tue, 12 Mar 2002 16:57:35 -0800 Subject: Rule Engine in Python Message-ID: <3C8EA3FF.DE3E38F5@quasar.ipa.nw.ru> Hi Andrae Andrae Muys wrote: > > lee.ingram at 432one.com (Lee Ingram) wrote in message news:... > > I have used Google to scour the web looking for an implementation of a > > rules engine using Python. I need a mechanism whereby slightly trained > > end users will be able to add / modify business rules and have them > > execute. I previously used Blaze Software's Advisor rules engine to do > > something similar. Has anyone seen, implemented, or tossed out this > > idea previously? > > > > Inquiring minds want to know... > > > > Eric Raymond implemented a simple rules engine as the foundation of > the new configuration engine for the linux kernel. If it's useful > then great. CLIPS wrapping are available at V.Ulogov's site at starship, FuzzyCLIPS wrappings on top of it are here: ftp://starship.python.net/pub/crew/avv/clips-wrapper.tgz Alexander From gerson.kurz at t-online.de Fri Mar 29 14:12:46 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 29 Mar 2002 19:12:46 GMT Subject: [ANN] PYNOSPAM 0.1 (and some Embedded-Python-Questions) Message-ID: <3ca4b9e8.10558859@news.t-online.de> pynospam is a Python-Powered extension for Microsoft Outlook, that will - filter spam mail i.e. tag the subject line with [SPAM!] if it thinks it is spam. - Because the spam detection is based on an at-runtime-interpreted python-script, you can easily add your own spam detection algorithms using regexs and whatnot. - and, ..., TADA: even more usefull, convert incoming HTML mails to plaintext and thus be saved from those bad javascript mails ;) (Note: This is for Outlook, not OutlookExpress (OE); or rather: I don't know if it works with OE, it works with Outlook 2000). More info and download incl. source: http://p-nand-q.com/pynospam.htm OK, onto the questions. The code consists of a C++ - written "Exchange Extension" for Outlook, that embedds the Python interpreter and, for new incoming mails calls the python script using PyRun_SimpleFile. I have a few problems: - the script is installed in PYNOSPAM project directory. I seem to be unable to put other scripts there and import them successfully - probably because the directory is not on the python path. Can a python script change the import path at runtime? - Having run in that problem, I tried the "poor-mans-import" approach, which is basically exec(open(filename).read()) That didn't work, but I got no error message?! I redirected sys.stderr before that, and other error messages seem to appear in the logfile, but when I add that nothing gets written, and PyRun_SimpleFile returns -1. From eppstein at ics.uci.edu Sat Mar 2 20:47:00 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Sat, 02 Mar 2002 17:47:00 -0800 Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: Here's another way of looking at the same question. An iterable object has a next() function, that's what it means to be iterable. If numbers are iterable, we can call number.next(), right? So what should 5.next() be? Surely anyone familiar with the Peano axioms would say 6, not 0! -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From fperez528 at yahoo.com Mon Mar 4 14:26:15 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 04 Mar 2002 19:26:15 +0000 Subject: Status of PEP's? References: Message-ID: James_Althoff at i2.com wrote: > Not a problem! Converts, in fact, get special treatment . Seriously > though, if nothing else, perhaps these PEP 276 discussions have helped to > highlight Python's wonderful "everything is a first-class object" > philosophy! Let me try to organize my thoughts a bit on why I dislike this PEP so seriously. I have no problem with the "everything is a first-class object" philosophy in Python. But I feel that precisely what this pep introduces is a bad usage (IMO) of these ideas. When 'for i in 5' becomes valid, what we are saying is, the object '5' knows how to count. Apparently this is ok, but I see problems: '5' is an integer, but there are also negative numbers in the integers. So how do we interpret 'for i in -3'? While one can argue that 0..4 is a 'natural' way to count for positive integers, the same argument becomes difficult to make for negative numbers. And by the way, as far as counting goes one could argue that 1..5 is even more natural, as it truly spans the set of the natural numbers of which 5 is a member, as opposed to the less 'standard' set of the 'non-negative integers less than 5'. But that's a minor nit-pick. The problem in my view is that when something is an object, its methods should do something which is reasonably natural and well defined for _all_ instances of a class. So when we ask the integers to have a counting method (via an iterator), I would want to have that counter behave sensibly for _any_ integer. And unfortunately, there's just no way to make such a definition IMHO. So this ends up introducing lots of context-sensitivity and special-casing (things work _this_ way for non-negative integers, which is not too clean but commonly useufl, and do _that_ for negative ones because someone thought it would be a usefu default...) Down that road lies Perl, and it seems to break very harshly the 'explicit is better than explicit' principle of Python design which I feel has served the language so well thus far. So in summary, it's not that I dislike integers being treated truly as objects, but rather that I want them to be clean objects. Objects whose methods behave in sensible ways for all instances of a class, not full of special defaults. Just my 0.02, f. From peter at engcorp.com Sun Mar 10 20:04:51 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 20:04:51 -0500 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> Message-ID: <3C8C02B3.674898B0@engcorp.com> phil hunt wrote: > > On Sun, 10 Mar 2002 15:29:37 -0500, Christopher Browne wrote: > > > >You might ask the "autocoding" guy if he'd be interested in adding > >this as an alternative syntax for his scheme; it might well be more > >readable than other options... > > Is he still posting here? > > (I killfiled him some time ago). Not in any new threads. I use Netscape for news, and it's not possible to killfile somebody without writing a f5g message filter, so I killed the threads he was in and haven't heard a peep since... -Peter From mstenner at phy.duke.edu Tue Mar 19 14:01:19 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Tue, 19 Mar 2002 14:01:19 -0500 Subject: Process to process synchronization (unix) In-Reply-To: ; from eric.brunel@pragmadev.com on Mon, Mar 18, 2002 at 11:16:55AM +0000 References: Message-ID: <20020319140119.A25754@phy.duke.edu> On Mon, Mar 18, 2002 at 11:16:55AM +0000, Eric Brunel wrote: > Gillou wrote: > > I have a Zope application and another running process (in python too). > > I need to transmit data and signal (hey ! data available, do your job !) > > in an asynchronous way from the Zope app (in an external method) to the > > python running process (that runs for another user). > > The other process waits for the signal, takes given data, does the jobs > > and waits further signal (...) > > I'm 99.9% newbie in process to process communication. > > What packages are helpful for this ? > > The two means that come to my mind are: > - named pipes: quite easy to handle, as they are manipulated just like > files. The problems are that named pipes are quite difficult to synchronize > if both processes should send data to the other, and that's it's a > Unix-only solution. All functions manipulating named pipes are built-ins or > in module os. If you choose that, I may also provide a few simple examples. > - sockets: a bit trickier to handle, but far more practical for two-way > communications and multi-platform. The Python module to handle them is > simply socket. There's an example in the library reference (see > http://www.python.org/doc/current/lib/socket-example.html). It's always seemed to me that named pipes have limited usefulness. They seem like a bit of a hack that have two major selling points. 1) they are truly persistent in the sense that neither program has to "set them up" (although _someone_ does... just not for each instance of the program) and they continue to exist when both programs are gone. 2) it is REALLY easy to take a program that writes (or reads, but writes is easier) to a file, and make it write to a named pipe. The latter is the more persuasive. If you have someone else's program that writes to a file only, but you want to do something more "active" with the output, you can make the file a named pipe. Anyway, other than that, I don't see much going for named pipes. Sockets are nice because they don't require that you have extra crap in the filesystem, and they can easily be made network-aware. (Have the two processes run on two different machines). Bottom line... I would use sockets. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From max at alcyone.com Fri Mar 29 20:47:58 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 29 Mar 2002 17:47:58 -0800 Subject: ANN: cage 1.0 -- Cellular automata engine in Python Message-ID: <3CA5194E.D5AB00E1@alcyone.com> Here's the latest PyOS installment: http://www.alcyone.com/pyos/cage/ Summary CAGE is a fairy generic and complete cellular automaton simulation engine in Python. It supports both 1D and 2D automata, a variety of prepackaged rules, and the concept of "agents" which can move about independently on the map for implementing agent behavior. CAGE comes with numerous examples of fully-functional CA systems, including Conway's Game of Life, Langton's self-reproducing automaton, Langton's "vants," and 1D automata rule explorers. It also comes with simple displayers (including a curses interface for 2D automata). Also included is a unique implementation of a finite state machine (ant.py). Note that CAGE is implemented entirely in Python, and due to its very generalized nature, is not designed for speed. It is sufficient to update a 80x24 Conway's Game of Life grid at a few times per second on a modern machine. CAGE is intended primarily as an education toolkit, rather than an industrial-strength CA simulator. Getting the software The software is available in a tarball here: http://www.alcyone.com/pyos/cage/cage-1.0.tar.gz. The official URL for this Web site is http://www.alcyone.com/pyos/cage/. Introduction In very general terms, a cellular automaton has the following key features: - time is measured in discrete steps, called time units; - a network of cells, each of which with a well-defined state at each time unit; - at each time unit, each cell has a series of other cells which constitutes its neighorhood; - the state each of cell changes according to a state transition function which depends on the state of that cell and the states of the cells of its neighbors; - in synchronous automata (the typical usage), all cell transitions take place simultaneously. In most cellular automata (and most textbook definitions), the cellular network is arranged into a rigid lattice (*i.e.*, a line or a grid), and for any given cell its neighborhood is constant (that is, the same for all time steps). These assumptions, however, are not present in CAGE. ... -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From irmen at NOSPAMREMOVETHISxs4all.nl Wed Mar 27 18:47:53 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 28 Mar 2002 00:47:53 +0100 Subject: unicode experiments + questions References: Message-ID: Martin v. Loewis wrote: > > I'm on Win2000, so when I type > > >>> print e.encode('cp1252') > > I get the Euro symbol. > > What do you mean by that statement? Where do you "get" it? In the > cmd.exe window? Unlikely, since that window uses the OEM encoding. I'm sorry, I forgot to mention that this was in the GUI console window of PythonWin. See the other posting... PythonWin does strange things when printing unicode directly?? Thanks for your other info! Irmen From ajs at ix.netcom.com Mon Mar 18 14:34:04 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Mon, 18 Mar 2002 14:34:04 -0500 Subject: Relieved but disappointed: The Pariah thread Message-ID: <000701c1ceb3$f8559270$7845f6d1@ArtsPortable> >I gave up ages ago. >Dale Strickland-Clark >Riverhall Systems Ltd Where do you go to follow the developments for a tool on which you rely for enhanced productivity - *and* some good knock knock jokes. Art From just at xs4all.nl Thu Mar 7 08:54:16 2002 From: just at xs4all.nl (Just van Rossum) Date: Thu, 07 Mar 2002 14:54:16 +0100 Subject: PEP 276 -- What else could iter(5) mean? References: <6qpu2gzktu.fsf@abnoba.intevation.de> Message-ID: In article , Just van Rossum wrote: > ugliness of the example. s/example/proposal/g Just From martin at v.loewis.de Sun Mar 31 06:14:18 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 13:14:18 +0200 Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: <3CA62CD8.6ABD44D0@accessforall.nl> <3CA6F012.E2631003@accessforall.nl> Message-ID: Ype Kingma writes: > I'd like to know whether this PEP merging all numeric types would also merge > the bool type into its evt. hierarchy. See for yourself: http://python.sourceforge.net/peps/pep-0228.html http://python.sourceforge.net/peps/pep-0242.html > > Notice that the relationship of bool and int has two aspects: one is > > whether you can combine them in numeric operations, > > e.g. 28+isleap(year). There is absolutely no way to remove this > > property from the language - too much code would break if that would > > raise an exception. > > There are two ways to do this: > - marking such code with: from __past__ import nonbool > (as I remarked earlier this is rather radical) I hate the __future__ statement, so I definitely don't want to get a __past__ statement. Following PEP 5, you will need a phased introduction strategy for booleans if you don't want to interact them with numbers. Don't expect to get this in this decade, though. Also, I doubt that this would be implementable: those magic import statements can only perform 'static' analysis of the module in question. Consider the following scenario: # module a.py def foo_p(): return True # module b.py def addem(a,b): return a+b # module c.py from __past__ import nonbool import a,b print b.addem(10, a.foo_p()) How is the bytecode of c.py supposed to know that foo_p returns a boolean, and that addem will attempt to convert this to an integer? > - defining __add__ and __radd__ in the int and float classes to also > accept a bool sounds quite pythonic and acceptable to me. That would work, but only somewhat. There are other places where booleans need to act as integers, e.g. indexing: array[b] ought to work, for backwards compatibility, even if b suddently turns into a boolean. That means that every __getitem__ implementation needs to become aware of booleans - so likely a lot of code would break. > An Square that is a Rectangle has inherits two degrees of freedom, > (height and width) which have to constrained to a single one in the > implementation. > Implementing such constraints is a bit awkward That depends on the rectangle interface. If rectangles are immutable, implementing the constraint is straight-forward, not awkward. class Rectangle: def __init__(self, x, y, w, h): self.x,self.y,self.w,self.h = x,y,w,h def area(self): return self.w*self.h class Square(Rectangle): def __init__(self, x, y, w): Rectangle.__init__(self, x, y, w, w) > When bool is-a int, one would have to (awkwardly) implement at least > one such constraint, namely that bool values can only be 1 or 0. Not at all. Bools are immutable, and singletons. If bool would not inherit from int, nothing in the implementation would change; see the PEP. Regards, Martin From emile at fenx.com Thu Mar 7 09:39:39 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 7 Mar 2002 06:39:39 -0800 Subject: mword2text on win32 References: <3C8776D0.3040200@thomas-guettler.de> Message-ID: Thomas Guettler > Does someone know how I can convert > msword to plain text in python on win32? > > I tried wvware from gnuwin32.sf.net (with popen3) > but it fails with complex documents. > from win32com.client import Dispatch word = Dispatch('Word.Application') worddoc = word.Documents.Open(r'C:\testtext.doc') ii = 1 while 1: try: nextparagraph = worddoc.Paragraphs(ii) except: break print nextparagraph ii += 1 HTH, -- Emile van Sebille emile at fenx.com --------- From corrado.gioannini at nekhem.com Thu Mar 28 09:39:00 2002 From: corrado.gioannini at nekhem.com (Corrado Gioannini) Date: Thu, 28 Mar 2002 15:39:00 +0100 Subject: Declare list of large size In-Reply-To: References: Message-ID: <20020328153900.A2221@zephyr> On Mon, Mar 18, 2002 at 04:43:03PM -0800, David Eppstein wrote: > > > list = [0]*100 > > > > But note that this is only safe for immutable elements. You will obtain a > > reference to the *same* object as each element. > > > > This normally bites people when they try to make multi-dimensional arrays > > ... > > > > list = [[0] * 2] * 2 > > print list > > list[0][0] = 1 > > print list > > > > [[0, 0], [0, 0]] > > [[1, 0], [1, 0]] > > > > As you can see, the first element of each sub-list has been changed - this > > is because each sub-list is in fact the same list! > > I got bitten by that, once. It took very little time to learn not to do > that. > > So, is it considered more Pythonic to create a multidimensional array by > list = [[0]*100 for i in range(100)] > and then access it by > ...list[i][j]... > > or is it more typical to just use dictionaries? > list = {} > ...list[i,j]... another way to build a mutable multidimensional array is simply >>> list = eval(repr([[0] * 2] * 2)) avoiding the problem of multiple references to the same list object do you find it too dirty, unpleasant or un-pythonic? (i'm really asking, it's not an ironic question ;-] ) C. -- Corrado Gioannini - "Thought is only a flash between two long nights, but this flash is everything." (H. Poincar?) From stojek at part-gmbh.de Fri Mar 15 13:24:28 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Fri, 15 Mar 2002 18:24:28 GMT Subject: Memory problem with C-Extension Message-ID: <3c923818.33586312@news.easynews.net> Hi, Im my programm I am using a C-Extension (WinNT, Python 2.1.1, Visual C++ V6) I am passing a couple of arrays filled with data,some ints and one array filled with 0s to the C-routine. The data is needed for calculations (surprise) and the 0-array is a placeholder for the expected int-results. (The values in my example are only dummies of course). Everything works fine, the results are correct but sooner or later after I called the C-routine the program crashes with a memory error. That's not reproducable and depends on the size of the data I am working with. Sometimes it doesn't happen at all. I know that there is missing some information but maybe some of you can see a BIG mistake (e.g. refrence counting) that's responsible. As I am neither very good at Python, nor at C what you see is mostly copied, stolen or guessed ;-) Thanks a lot in advance, Marcus Here is the condensed code : Python------------------------------------------------------------------------- CmEleNr=10000 CmEle=[(1,1,1) for for e in range(CmEleNr)] CmEle=Numeric.array(CmEle) # array of int CmNodesNr=10000 CmNodes=Numeric.array([(1.0,1.0,1.0) for n in range(CmNodesNr)])# array of float AbaPtsNr=15000 aip=[(1.0,1.0,1.0) for a in range(AbaPtsNr)]# array of float AbaPts=Numeric.array(aip) #empty array of int that is filled by the C-routine: MasterEle=Numeric.array([0 for n in range(AbaPtsNr)]) ip2cm = Numeric.array(MasterElement.MasterElement(MasterEle, AbaPts,AbaPtsNr,CmEle,CmEleNr,CmNodes,CmNodesNr)) //C----------------------------------------------------------------------- static PyObject* MasterElement (PyObject *self, PyObject *args) { PyArrayObject *MasterEle, *AbaPts, *CmEle, *CmNodes; int AbaPtsNr, CmEleNr, CmNodesNr; if (!PyArg_ParseTuple(args, "O!O!iO!iO!i", &PyArray_Type, &MasterEle, &PyArray_Type, &AbaPts, &AbaPtsNr, &PyArray_Type, &CmEle, &CmEleNr, &PyArray_Type, &CmNodes, &CmNodesNr ) ) return NULL; // printf ("%d = %d, %d\n", AbaPtsNr, MasterEle->dimensions[0], MasterEle->strides[0]); // The function that does all the work and fills MasterEle with ints MasterIntern ((int*)MasterEle->data, (double*)AbaPts->data, AbaPtsNr, (int*)CmEle->data, CmEleNr, (double*)CmNodes->data, CmNodesNr); return PyArray_Return (MasterEle); } static PyMethodDef MasterElement_methods[] ={ {"MasterElement", MasterElement, METH_VARARGS}, {0,0} }; void initMasterElement (void) { Py_InitModule("MasterElement", MasterElement_methods); import_array(); } From tim.one at comcast.net Fri Mar 1 00:12:45 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 01 Mar 2002 00:12:45 -0500 Subject: dirwalk.py generator version of os.path.walk In-Reply-To: <3C7EFC9B.AB6029EA@cosc.canterbury.ac.nz> Message-ID: [Jim Dennis] > I guess I'm just wary of recursion, particularly when I've read > that Python doesn't support tail-end recursion. [Greg Ewing] > That's only an issue if you abuse recursion for the likes of > iterating along a linear list. In languages which optimise > tail-recursion, it is common for people to do things like > that using recursion, but it would be silly in Python. > If, e.g. the list were a million items long, you'd need a > million stack frames. > > But here, the stack is only going to be as deep as the > directory hierarchy, which is hardly going to kill you. > > So, don't just blindly reject recursion -- think about > how it applies to the problem at hand! If I were Jim, I'd continue leaving recursion out of this specific application. An explicit "todo list" trivially supports either breadth-first or depth-first traversal (a choice Jim explicitly mentioned as something he wants to control). Calling it "a stack" is an illusion suffered by those blindly embracing recursion . From tdelaney at avaya.com Wed Mar 27 18:26:12 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 28 Mar 2002 10:26:12 +1100 Subject: Why does this work? Message-ID: > From: Phlip [mailto:phlip_cpp at my-deja.com] > > We find just >having< a style guideline slightly more > important than the > value of any few marginal items in it. > > And we like to find ways to cure the "magic member bug". If > you can think of > any others, please share. __slots__ Tim Delaney From philh at comuno.freeserve.co.uk Sun Mar 31 08:29:55 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sun, 31 Mar 2002 14:29:55 +0100 Subject: [ANN] PYNOSPAM 0.1 (and some Embedded-Python-Questions) References: <3ca4b9e8.10558859@news.t-online.de> Message-ID: On Sat, 30 Mar 2002 20:00:53 -0800, Gerhard H?ring wrote: >phil hunt wrote: > > at some point I want herbivore to run on Windows >> email clients). > >I still didn't check out herbivore, but what about writing an smtp proxy >for that? That is one of the ways Herbivore will work. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From ianb at colorstudy.com Mon Mar 25 10:11:59 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 25 Mar 2002 09:11:59 -0600 Subject: [albatross-users] Re: Python embedded like PHP In-Reply-To: References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> <1017000019.3094.31.camel@localhost> Message-ID: <1017069119.589.18.camel@localhost> On Mon, 2002-03-25 at 08:09, Dave Cole wrote: > > For this problem, I think the solution is in the interpreter -- your > > macros are just hard to work with (from what I can see), because > > they are dynamically scoped and being used in lieu of real > > functions. It's not a syntax issue. > > I would really like it if you could explain a little further. > > The macros do sort of work like functions in that they pass arbitrary > template content to the macro for substitution at the location > specified by the macro. > > I tried to work out a simple way in which values from the execution > context namespace could be passed as arguments but couldn't see how to > do it in a nice fashion Well, you might be able to help the situation some if you create a new scope for the macro, and have something like dtml-let -- that way you could do stuff like. That way variable assignments inside your macro will pass out of scope when the macro finishes, and at least not overwrite things in the main scope. You can use some form of let to manipulate the namespace when it doesn't match what the macro expects. This is what DTML does, and I assume ZPT uses the same mechanisms (it only seems to be a change of syntax). I don't like this at all, though, as there's all sorts of problems that pop up when you start abstracting things more deeply. Also, I think macros are very important, and keeping them python-like is a very nice. Then you can define, inside a single template, not only the full page style, but the style of components of the page. For instance, I create pages that create headers with lists underneath them, all entirely dynamic. If the template can define what a header and what a list should look like, then I have much more power over the look of the page. I'd pass arguments like: This seems pretty straight-forward, and also maps directly to keyword arguments. You could add the syntax: (which isn't XML, but so it goes), which would equivalent to -- basically saying which parts of the namespace to pass in. It should also be fairly easy to create Python functions that do the same thing as the macro. Some people will still want to pass in entire namespaces... you could use inclusion instead of macros in that case, or make another form of macros. You could also make another form of setting variables, that sets them globally (perhaps as constants) -- this is much cleaner than making every passing variable and loop global. Ian From jason at jorendorff.com Tue Mar 12 13:20:46 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Tue, 12 Mar 2002 12:20:46 -0600 Subject: doctest Hassles! In-Reply-To: <10d46bdc.0203120928.7e9c708b@posting.google.com> Message-ID: Douglas Garstang wrote: > Well, when I print the value of ls, I get: > > [...] > > Notice the blank line at the end. Where did that come from? print x always writes x, followed by a newline. > Also, why is the output in ONE column instead of across > the screen (as in a normal ls) when spawnv is used? All I did was > print the output of the ls command, but the output is different. "ls" has this quirk. If it finds that stdout is a tty, then it spits out nice columns. Otherwise, one file per line. I think GNU "ls" has command-line options that allow you to specify which mode. "ls -1" forces one column. Several Unix utilities do this sort of tty detection. I rather dislike it (except in Python of course). But that's life. > On a side note, I've had this problem before with python, > trying to read text config files. As soon as it hit an empty > line, reading would stop! Huh? Could you clarify this? Is this a separate problem? Do you have source code that illustrates this? > What am I missing here? I would imagine that executing external > programs is central to testing, but it seems to be _really_ difficult. Doctest isn't designed for stuff like this, and there are some limitations to what it can do. Anyway, try os.listdir(os.curdir) and save yourself some trouble. :) ## Jason Orendorff http://www.jorendorff.com/ From john at yahoo.com Sun Mar 31 16:49:47 2002 From: john at yahoo.com (John Warney) Date: Sun, 31 Mar 2002 21:49:47 GMT Subject: newbie question on lists, getting an error on basic addition References: Message-ID: Ah, ok, thanks, it works fine now On 31 Mar 2002 12:22:31 -0500, aahz at pythoncraft.com (Aahz) wrote: >In article , >John Warney wrote: >> >>>>> alist = [1, 2, 3, 4] >>>>> counter = 0 >>>>> answer = 0 >>>>> alist >>[1, 2, 3, 4] >>>>> counter >>0 >>>>> answer >>0 >>>>> while counter < 6: >>... answer = answer + alist[counter] >>... counter = counter + 1 >>... >>Traceback (most recent call last): >> File "", line 2, in ? >>IndexError: list index out of range >>>>> answer >>10 > >Add a print counter at the top of your loop and you'll see why. From sjmachin at lexicon.net Thu Mar 28 16:35:13 2002 From: sjmachin at lexicon.net (John Machin) Date: 28 Mar 2002 13:35:13 -0800 Subject: question on struct.calcsize References: <3ca33d3f.26101031@news.easynews.net> Message-ID: stojek at part-gmbh.de (Marcus Stojek) wrote in message news:<3ca33d3f.26101031 at news.easynews.net>... > Hi, > could anyone explain the following, please. > (Win NT, Python 2.1.1) > > >>> from struct import * > >>> calcsize("i") > 4 > >>> calcsize("s") > 1 > >>> calcsize("si") > 8 Simply, the int is being aligned on the next available 4-byte boundary. See below. >>> from struct import * >>> for n in range(10): ... fmt_str = '%dsi' % n ... print fmt_str, calcsize(fmt_str) ... 0si 4 1si 8 2si 8 3si 8 4si 8 5si 12 6si 12 7si 12 8si 12 9si 16 >>> If you are designing the struct yourself and you want to cut down on wasted memory, list out the structure members in descending order of size -- int, byte, byte will take the space of 2 ints whereas byte, int, byte will take the space of 3 ints. Other things to bear in mind: a 64-bit machine may well have an 8-byte alignment requirement; malloc(n) generally rounds up the space taken to K times the alignment requirement, where K can be > 1; and specifically for small n, malloc may use a greater K -- for example malloc(1) could chew up as much memory as malloc(16). End result: you often have "spare" memory at the end of your struct; packing a small int into a byte may save no memory and may in fact be slower to access on some architectures. Don't try to fight the alignment and get an int starting at offset 1. On some architectures you will get an address violation; on most others accessing such an int would be much slower than accessing an aligned int. OTOH, if the struct is already specified, you need to look very carefully at whether you want "native" alignment (what you have by default in your example) [the calculations are done for you but the answers vary by platform] or "standard" alignment [which really means no assistance with alignment; you have to put "x" pad bytes in the format string yourself] -- read the docs. If the producer and consumer are on different platforms, you need a carefully-designed standard-alignment struct or, better, use a higher-level-than-C-struct data interchange protocol. ... and that *was* the SHORT answer :-) HTH, John From tim.one at comcast.net Sat Mar 30 20:17:40 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 20:17:40 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: <200203302336.g2UNa8F10511@pcp742651pcs.reston01.va.comcast.net> Message-ID: [Guido, on why operator.truth() should change to return True/False] >>> Tim must be missing something. The obvious way to turn a bool b into >>> an int is int(b). [Tim, being difficult] >> It's also an incorrect way for me, [Guido, being more difficult] > No it's not, note that I said "turn a bool b into an int". Clearly > the assumption there is that b is a bool, not an arbitrary value in > whose truth value we're interested. In context, your original int(b) suggestion was in response to my: people have a legitimate need to make an arbitrary true/false expression produce 0 and 1 too, if only to preserve 0/1-based true/false output. operator.truth() has always been the best way to do exactly that. Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and "(0,1)[boolexpr]" reek in comparison. where, as I explained in the later msg to which you're replying now, just in case it wasn't clear the first time around: I meant "true/false expression" in the way Python has always meant it, e.g. operator.truth([]) == 0, but int([]) raises an exception. So you may say that "clearly the assumption there is that b is a bool", but it's not at all clear that was a *reasonable* assumption in the context in which you first said it: I've been thru the business twice now of explaining why int() isn't suitable for the cases I was talking about. int(bool) is not a case I was talking about. > IMO, bool(x) is the right way to "normalize" any value into a truth > value. Sure, it will be. But if you need to, e.g., "preserve 0/1-based true/false output", bool(x) may not work (depending on whether you yield to making str(bool) and/or repr(bool) return "0"/"1"). > The way I think of operator.truth(x) is as something returning > a normalized truth value. Well, that's where we differ: bool(x) will be *the* "right way to 'normalize' any value into a truth value". As at the start, I don't need two "right ways" to do exactly the same thing. > ... > [more of the same] > ... > I'm going to make this a BDFL pronouncement; I understand your > argument but I don't agree with it. Whew! I'm glad that's finally over, you-should-do-that-more-often-ly y'rs - tim From skip at pobox.com Wed Mar 27 11:45:00 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Mar 2002 10:45:00 -0600 Subject: instrumenting Python code In-Reply-To: References: <15521.59902.657216.982543@12-248-41-177.client.attbi.com> Message-ID: <15521.63244.469114.753420@beluga.mojam.com> Dave> Now, about profiling multithreaded applications. Do you have any Dave> suggestions? Other than looking at Python/ceval.c and Modules/_hotshot.c to see what needs to be done, no. A quick peek at the slides from Fred's hotshot talk at IPC10 suggests that multithreading is either not yet supported or not well-supported. Fred probably has a better idea what still needs to be done if you want to tackle it. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From syver-en+usenet at online.no Sat Mar 9 19:40:08 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sun, 10 Mar 2002 00:40:08 GMT Subject: Howto: Tkinter Listbox keyboard support Message-ID: Anyone knows how to get the arrow keys to scroll the selection in a Tkinter Listbox? -- Vennlig hilsen Syver Enstad From joonas at olen.to Fri Mar 1 15:14:13 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Fri, 01 Mar 2002 22:14:13 +0200 Subject: Securely passing arguments when opening a pipe to a program Message-ID: <3C7FE115.9832EE5C@olen.to> I am using Gnokii to send SMS messages with Python. Gnokii is started with popen2.popen2 like this: gnokiiRead, gnokiiWrite = popen2.popen2("gnokii --sendsms %s" % phonenumber) gnokiiWrite.write(message) gnokiiWrite.close() response = gnokiiRead.read() gnokiiRead.close() The problem is that the phonenumber string is not safe; it can even be "000; rm -fR ~/*". How can I securely pass arguments when opening the pipe? Is there a way to pass the arguments like in os.execv. - Joonas From nobody at nobody.com Sat Mar 30 17:34:36 2002 From: nobody at nobody.com (John) Date: Sat, 30 Mar 2002 16:34:36 -0600 Subject: list of functions Message-ID: <01rp8.34168$tg4.401910@vixen.cso.uiuc.edu> Hi, I was glad to find that Python allows the following: def addone(a): return a+1 list_of_functions=[addone] list_of_functions[0](1) --> returns 2 However, what if the functions require more than one arguments? say def addall(a,b,c): return a+b+c? Though list_of_functions[0](1,2,3) works, I'd like to make (1,2,3) as variables.. How do I pass the variables to such functions? From vku at lfpt.rwth-aachen.de Mon Mar 18 04:12:01 2002 From: vku at lfpt.rwth-aachen.de (Viatcheslav Kulikov RWTH Aachen) Date: Mon, 18 Mar 2002 10:12:01 +0100 Subject: Python + Omni CORBA libraries link Message-ID: <3C95AF61.5D25C8CD@lfpt.rwth-aachen.de> I am beginning to write a Python wrapper interface in order to make it comminucate via CORBA-bus. At the compilation stage I receive the following set of traceback messages: Traceback (most recent call last): File "D:\PROGRA~1\Python21\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "G:\Source\hysys_unit\corba_wrapper\impl\hysys_unit_factory_srv.py", line 7, in ? from omniORB import CORBA, URI, PortableServer File "D:\Programme\omni\lib\python\omniORB\__init__.py", line 139, in ? import _omnipy ImportError: DLL load failed: Das angegebene Modul wurde nicht gefunden. >>> I am using Python 2.1. and OmniORB compiler 1.0. The _omnipy module is available there with a .pyd extension (a compiled library). This message is received when the library is present at the PythonPath; when it is not, the interpreter simply finds no module name _omnipy. Please advise what can be done. I am new to the Python programming, so please give as much detail as possible. From jkraska at san.rr.com Sat Mar 9 12:09:32 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 09 Mar 2002 17:09:32 GMT Subject: Is current integer for-loop syntax a wart? References: Message-ID: >What you sohuld be able to do is say: > > for i in a.keys(): > b[i] = a[i] Thinking about this, what you say seems plainly correct. Both Python lists and dictionaries have keys and values: it's just that, for some reason, we don't think of lists as having 'keys' for some reason, even though they plainly do. It would follow that the appropriate implementation of this would be to return a iterator. C// From cfelling at iae.nl Sat Mar 2 13:05:25 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 2 Mar 2002 19:05:25 +0100 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: Emile van Sebille wrote: > "Carel Fellinger" >> You specify that the >> integer to iterate over should be possitive, why not allow for >> negative values and do the sensible thing, like: >> >> >>> [i for i in -3] >> [-1, -2, -3] > If you change the sensible thing to mean: > [-3, -2, -1] > I'd like it better. ;-) I noted the smiley, but just in case someone might think you have a point: what would be the benefit of that? It just let you loop over a sequence in the standard order, but now with negative indici. And the range call to get this isn't that hard either: range(-3,0). My proposal makes iterating in *reverse* order simple. The tutorial could introduce it like: In python integers are objects too. And objects know how to do things, e.g. integer objects know how to add and just recently they learned how to count. Positive integers count from zero upto but not including the number itself, whereas negative integers count from -1 downto and including the number itself. A common place where this feature of integers is used is in for loops and list comprehension. e.g. >>> s = "silly walk".split() >>> print " ".join([s[i] for i in len(s)]) silly walk >>> print " ".join([s[i] for i in -len(s)]) walk silly Although the first print statement is generally written as: >>> print " ".join([x for x in s]) The implementation is dead simple, to play around with it in 2.2: class Int(int): def __neg__(self): return Int(int(self).__neg__()) def __iter__(self): i = 0 if self >= 0: while i < self: yield i i += 1 else: while i > self: i -= 1 yield i and define your classes to let __len__ return an Int object. class List(list): def __len__(self): return Int(len(list(self))) trying it out, yack it doesn't work, len forces it into an int again:( >>> spam = List("spam") >>> type(spam.__len__()) >>> type(len(spam)) I think this qualifies as a bug. -- groetjes, carel From gh_pythonlist at gmx.de Sat Mar 9 11:42:04 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 9 Mar 2002 17:42:04 +0100 Subject: how to set the background color of a window with curses In-Reply-To: <20020309125336.GA2236@lurkabove.darkstar> References: <20020309125336.GA2236@lurkabove.darkstar> Message-ID: <20020309164204.GB1466@lilith.hqd-internal> Le 09/03/02 ? 13:53, Marco Herrn ?crivit: > Hi, > > I am trying to set a backround color for a window and did it with > > stdscr.bkgd(' ', curses.COLOR_BLUE) > > But that doesn't work. It seems to do nothing. > What am I doing wrong? You're confusing colors with attributes. I recently stumbled across that one, too :) This will do the trick: # define color 1 as black on blue curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_BLUE) stdscr.bkgd(' ', curses.color_pair(1)) If you're getting this error: File "clock.py", line 6, in mymain curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_BLUE) _curses.error: must call start_color() first your TERM setting doesn't allow colors. You can then use something like TERM=xterm-color instead. Btw. there's a curses howto on http://py-howto.sf.net/ in case you didn't know. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From a.clarke11 at pop.ntlworld.com Thu Mar 7 03:37:06 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Thu, 07 Mar 2002 08:37:06 +0000 Subject: Beginner References: Message-ID: <3C8726B1.2C619018@pop.ntlworld.com> Hi, I sometimes look at the book on line: it seems clear simple and fairly wide in scope. However, I wouldn't use it as reference, and its a bit light on object processes. A good, light introduction: perhaps you should also have a more heavywight intro as well, eg the O'Reilly books? I've been pythoning for less than a year, with little experience of other languages. Best wishes Tony Mr Boxer wrote: Have you experience of the book "How to think like a computer scientist - Learning with Python"? I would like to learn python and begin with reading that tutorial I found online at python site. I'm not a "strong old programmer" but I've some experience with shell, perl, elisp and C. Thanks a lot. From martin at v.loewis.de Sat Mar 30 03:34:04 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 09:34:04 +0100 Subject: Unicode with win32com and makepy References: <71jaau4q7m8ljplv7r9vrog529dibnf4s9@4ax.com> Message-ID: Tim Roberts writes: > Here's the question: what do we do in the long term? Should makepy > generate a __unicode__ member every time it generates a __str__ member? I think so, although it could probably phrase that as def __unicode__(self, *args): try: return unicode(self.__call__(*args)) except pythoncom.com_error: return repr(self) def __str__(self, *args): return str(unicode(self, *args)) What is the set of types that __call__ can return? Regards, Martin From skip at pobox.com Sun Mar 10 18:11:03 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 10 Mar 2002 17:11:03 -0600 Subject: Regular expressions newbie: something for templates In-Reply-To: References: Message-ID: <15499.59399.171945.639758@12-248-41-177.client.attbi.com> Thomas> "This is the test $var1$ and this is $var2$" Thomas> and turn it into Thomas> "This is the test %(var1)s and this is %(var2)s" Give this a try: >>> import re >>> s = "This is the test $var1$ and this is $var2$" >>> re.sub(r"\$([a-zA-Z_0-9]+)\$", r"%(\1)s", s) 'This is the test %(var1)s and this is %(var2)s' -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) "As often happens in Net communities, people find all kinds of energy to compose incisive criticisms of the threads and postings of other members, when they could be directing that energy towards brilliant new threads and postings of their own." - Tom Neff From woodsplitter at rocketmail.com Mon Mar 18 16:05:43 2002 From: woodsplitter at rocketmail.com (David Rushby) Date: Mon, 18 Mar 2002 16:05:43 -0500 Subject: Still same bug even with email ver. 1.2 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> Message-ID: "Michael Hudson" wrote in message news:u4rjdred0.fsf at python.net... > woodsplitter at rocketmail.com (David Rushby) writes: > > > And here's SourceForge bug #491612 (closed now), which was filed to > > report this very bug: > > http://sourceforge.net/tracker/index.php?func=detail&aid=491612&group_ id=25568&atid=384678 > > > > Unfortunately, contrary to Oleg's assertion in c.l.py and Barry's in > > his message added to the SF bug report, the CVS version of has *not* > > been fixed. > > Are you sure? It's certainly possible, but I think revision 1.6 of > Lib/email/Parser.py, which became revision 1.5.10.1 on the > release22-maint branch, was certainly aimed at fixing this bug. > ... > First it would be good if you could supply some evidence that the bug > isn't, in fact, fixed. I checked the release22-maint branch of Python out of SF CVS at approx 15:00 GMT on March 18. I took the next to last example in email.tex (the program that mails the contents of a directory) and ran it for three cases: A) the target directory contains no files B) the target directory contains exactly one file C) the target directory contains more than one file Here is the stderr ouput for case A: ---------------------------------------------------------------------- ----- Traceback (most recent call last): File "dirmail.py", line 134, in ? main() File "dirmail.py", line 129, in main s.sendmail(sender, recips, outer.as_string(0)) File "c:\dev\python\core\lib\email\Message.py", line 59, in as_string g(self, unixfrom=unixfrom) File "c:\dev\python\core\lib\email\Generator.py", line 83, in __call__ self._write(msg) File "c:\dev\python\core\lib\email\Generator.py", line 104, in _write self._dispatch(msg) File "c:\dev\python\core\lib\email\Generator.py", line 134, in _dispatch meth(msg) File "c:\dev\python\core\lib\email\Generator.py", line 240, in _handle_multipart for part in msg.get_payload(): TypeError: iteration over non-sequence ---------------------------------------------------------------------- ----- Here is the stderr ouput for case B: ---------------------------------------------------------------------- ----- Traceback (most recent call last): File "dirmail.py", line 134, in ? main() File "dirmail.py", line 129, in main s.sendmail(sender, recips, outer.as_string(0)) File "c:\dev\python\core\lib\email\Message.py", line 59, in as_string g(self, unixfrom=unixfrom) File "c:\dev\python\core\lib\email\Generator.py", line 83, in __call__ self._write(msg) File "c:\dev\python\core\lib\email\Generator.py", line 104, in _write self._dispatch(msg) File "c:\dev\python\core\lib\email\Generator.py", line 134, in _dispatch meth(msg) File "c:\dev\python\core\lib\email\Generator.py", line 240, in _handle_multipart for part in msg.get_payload(): File "c:\dev\python\core\lib\email\Message.py", line 151, in __getitem__ return self.get(name) File "c:\dev\python\core\lib\email\Message.py", line 214, in get name = name.lower() AttributeError: 'int' object has no attribute 'lower' ---------------------------------------------------------------------- ----- There is no output to stderr for case C, because it works fine. I hope this adequately demonstrates that SourceForge bug #491612 (which was filed against the mimelib for of the email package, but is still relevant to the stdlib fork) has not been fixed, even in the release22-maint CVS branch. BTW, my operating system is Windows NT 4.0 SP6a. The example program is shown below. I made one trivial change to make the temp file name cross-platform; I flagged that change with "DSR:platform independent version:begin" and "DSR:platform independent version:end". ---------------------------------------------------------------------- ----- #!/usr/bin/env python """Send the contents of a directory as a MIME message. Usage: dirmail [options] from to [to ...]* Options: -h / --help Print this message and exit. -d directory --directory=directory Mail the contents of the specified directory, otherwise use the current directory. Only the regular files in the directory are sent, and we don't recurse to subdirectories. `from' is the email address of the sender of the message. `to' is the email address of the recipient of the message, and multiple recipients may be given. The email is sent by forwarding to your local SMTP server, which then does the normal delivery process. Your local machine must be running an SMTP server. """ import sys import os import getopt import smtplib # For guessing MIME type based on file name extension import mimetypes from email import Encoders from email.Message import Message from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText COMMASPACE = ', ' def usage(code, msg=''): print >> sys.stderr, __doc__ if msg: print >> sys.stderr, msg sys.exit(code) def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory=']) except getopt.error, msg: usage(1, msg) dir = os.curdir for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-d', '--directory'): dir = arg if len(args) < 2: usage(1) sender = args[0] recips = args[1:] # Create the enclosing (outer) message outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'Contents of directory %s' % os.path.abspath(dir) outer['To'] = sender outer['From'] = COMMASPACE.join(recips) outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' # To guarantee the message ends with a newline outer.epilogue = '' for filename in os.listdir(dir): path = os.path.join(dir, filename) if not os.path.isfile(path): continue # Guess the Content-Type: based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(path) # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(maintype, subtype) msg.add_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) # DSR:platform independent version:begin # Was: #fp = open('/tmp/debug.pck', 'w') # Changed to: import tempfile fp = open(tempfile.mktemp(), 'w') # DSR:platform independent version:end import cPickle cPickle.dump(outer, fp) fp.close() # Now send the message s = smtplib.SMTP() s.connect() s.sendmail(sender, recips, outer.as_string(0)) s.close() if __name__ == '__main__': main() From nhodgson at bigpond.net.au Wed Mar 20 18:11:42 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 20 Mar 2002 23:11:42 GMT Subject: Chewing international (unicode) filenames on windows? References: <3C97FC23.1030702@skippinet.com.au> Message-ID: Mark Hammond: > > There is also a lot that should be shared, such as the docstrings, much > > of the argument parsing as well as many of the posix calls. Splitting may > > lead to more breakage when common patches aren't applied to both. > > How about just using #include files here then? I'm sure some good form of packaging is possible, but as this is a large and important module, I feel it needs quite a bit of thought and effort to get right. > > It needs a way to specify the base generic > > posix case cleanly but then to allow platforms to specialise or remove those > > functions needing different implementations or which can not be implemented. > > In my own C++ work, I normally do this through subclassing. > > It doesn't have to be *too* cleanly :) Having little helper functions > isn't too bad and could probably work - ie, think "pragmatically" more > than "cleanly" :) I may be in an over-design mode but I've seen large modules (posixmodule is 150K of fairly dense code) go bad through poor redesign before. What is apparent in reading through this code is that there are some fairly repetitive code patterns. You have a posix function, so it gets a doc string, some 'HAVE_*' protection, a method table def, and a function. In the function, the arguments are parsed, the system call is made with threads turned on, then any error status is turned into an exception and the return value is boxed. Any allocations are cleaned up. This tickles the commonality seeker in my brain. The code tries to merge some common sequences with posix_1str and posix_2str but even this has been complexified by my patch. BTW, I'm not volunteering to redesign posixmodule. My original change was just to allow the file constructor to take a Unicode string which is to me the biggest gain in functionality. Neil From bergeston at yahoo.fr Wed Mar 27 13:28:42 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Wed, 27 Mar 2002 19:28:42 +0100 Subject: Traceback without __class__ attribute ? Message-ID: Hi Pythonistas, I am wondering about this (hurting my OO comprehension): >>> try: ... 5/0 ... except: ... type, value, traceback = sys.exc_info() ... >>> traceback >>> type(traceback) >>> traceback.__class__ Traceback (most recent call last): File "", line 1, in ? AttributeError: __class__ >>> sys.version '2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)]' >>> Why traceback has no __class__ attribute ? Is it planned to change ? Does it mean that exceptions.ZeroDivisionError is an "old style class" ? What is the best mean to check the type/class in Python 2.2 (and next versions) ? (and more specifically for dictionnary-like and list-like objects). TIA to everybody spending time to satisfy my curiosity (and/or correcting me if I am wrong in my understanding). B From DavidA at ActiveState.com Fri Mar 29 01:46:25 2002 From: DavidA at ActiveState.com (David Ascher) Date: Thu, 28 Mar 2002 22:46:25 -0800 Subject: ActivePython 2.2 released! Message-ID: <3CA40DC1.9A9D0A05@ActiveState.com> We are pleased to announce that version 2.2 of ActivePython is now available for download from http://www.ActiveState.com/ActivePython I'll also take this opportunity to mention that we will shortly be issuing ActivePython 2.1.2 (a bug-fix release for Python 2.1), and ActivePython 2.2.1 (a bug fix release for Python 2.2 currently undergoing final testing). We're releasing 2.2 regardless of these upcoming releases because we'd like to solicit feedback on some of the changes we've made in ActivePython. Specifically, - the Windows installer is brand new, and should work on a wider variety of platforms than before, including non-Administrator accounts. - there is more documentation bundled, including several tutorials which were not previously shipped (especially on Linux). - We've made some changes to the Python Package Manager (PyPPM). The PPM modules currently available include: * mxBase -- A set of utility classes including mxDateTime, mxTextTools, mxStack, mxTools, and mxProxy * Numeric -- high performance multi-dimensional array support * PIL -- the standard Python Imaging Library * PyChecker -- a code-proofing tool * StandaloneZODB -- the persistence solution from Zope, now available outside of Zope * ZSI -- the reference SOAP library * pyperl -- ActiveState's interface between Python and Perl Please submit email feedback to ActivePython-feedback at ActiveState.com, and file bugs against ActivePython at bugs.ActiveState.com/ActivePython. We will be using that feedback to prepare the 2.2.1 and 2.1.2 releases. Thanks, and enjoy! -- David Ascher ActiveState From loewis at informatik.hu-berlin.de Mon Mar 4 07:10:58 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 04 Mar 2002 13:10:58 +0100 Subject: How can I use a foreign language char in Swing References: Message-ID: "Jason Orendorff" writes: > > Actually, this is quite likely: MS normally choses "?" as the > > replacement character, and you need to explicitly request CJK fonts > > when installing the English edition of W2k. If "Windows" really means > > "W9x" in this context, things are probably even worse. > > Wow, really? I know next to nothing about it - but it feels > as though I once heard that fonts have an explicit "i-am-stumped" > glyph, usually an empty box... I don't know what they do when the font does not incorporate the glyph. However, if you use WideCharacterToMultiByte (or some such), the replacement character normally is the question mark. You can see this happen if you have a filename with funny characters, and try to display those in console with the raster font. Regards, Martin From shalehperry at attbi.com Wed Mar 6 19:56:11 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 06 Mar 2002 16:56:11 -0800 (PST) Subject: Code Bash!!! (CacheDictionary) In-Reply-To: <19650FF08A99D511B19E00B0D0F06323060B45@SRM201002> Message-ID: Comments: *) maxlength=1000, I belive this variable is poorly named. A dictionary is not 10 items long, it contains 10 items. Something like maxitems or maxcount. *) is kill_old() part of the interface for users? I would guess this method should be protected with a leading _. *) self._timeout[k] = int(time()) + self._maxtimeout ^^^ -- shouldn't that be 'key'? *) why use two dictionaries? why not store data in dict? From sdm7g at Virginia.EDU Thu Mar 28 12:27:56 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Thu, 28 Mar 2002 12:27:56 -0500 (EST) Subject: Sorting distionary by value In-Reply-To: Message-ID: On Thu, 28 Mar 2002, phil hunt wrote: > On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen wrote: > >Jim Dennis wrote: > >> > >> The core loop is something like: > >> > >> freq = {} > >> for line in file: > >> for word in line.split(): > >> if word in freq: freq[word] += 1 > >> else: freq[word] = 1 > >> > >> (assuming Python2.2 for file interation and dictionary membership > >> support using "in." I *really* like those 2.2 features! They make > >> my psuedo-code so executable!) > > > >Something like freq[word] = freq.get(word, 0) + 1 > > > >would probably be faster, and it's a little simpler I think, > >although I could see an argument that it's less readable. > >Also doesn't depend on 2.2. > > IIRC in Awk you can just say: freq[word] ++ and it works > correctly even when there is no pre-existing index of word in freq. > > IMO it's a pity Python isn't like that. > However, with 2.2 you can do something like this to give key access a default value: Python 2.2.1c1 (#1, Mar 19 2002, 02:06:22) [GCC 2.95.2 19991024 (release)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class Dcounter(dict): ... default = 0 ... def __getitem__( self, key ): ... return self.get( key, self.default ) ... >>> >>> count = Dcounter( {'ten':10, 'nine':9 } ) >>> count['ten'] 10 >>> count['one'] += 1 >>> count['one'] 1 >>> count['two'] += 1 >>> count['two'] += 1 >>> count['two'] 2 >>> count {'nine': 9, 'two': 2, 'ten': 10, 'one': 1} >>> count['zero'] 0 -- Steve Majewski From sdm7g at virginia.edu Fri Mar 29 13:39:44 2002 From: sdm7g at virginia.edu (Steven Majewski) Date: Fri, 29 Mar 2002 13:39:44 -0500 (EST) Subject: Standalone CGI Server - Question for Group In-Reply-To: Message-ID: On 29 Mar 2002, Gerhard [iso-8859-15] H?ring wrote: > Maybe it's just me, but I often have difficulties to understand the > point of the "overkill" argument. > > > Any thoughts? I sincerely appreciate everyone's help! > > If you can spare 5 megs of RAM and a little disk space, just go for > Apache (or Xitami, or whatever). When you're running the webserver and > are not using it currently, it'll be swapped out anyway, so why > bother? > > It's a myth that Apache is complex to get running, here's what you'd > need to do on Windows: > > 1) Install Python > 2) Install Apache > 3) edit etc/httpd.conf and add the line > > ScriptInterpreterSource Registry > > at the end of the file. Apache comes preinstalled on Mac OSX, and all you have to do there is click on "Start Web Sharing" in the System Preferences Panel. This is on all of the desktop machines, not just servers, so they apparently didn't think it was overkill! -- Steve From sjmachin at lexicon.net Wed Mar 27 06:16:45 2002 From: sjmachin at lexicon.net (John Machin) Date: 27 Mar 2002 03:16:45 -0800 Subject: C API for modules References: <3CA09F43.80206@erols.com> <3CA1499D.4070802@erols.com> Message-ID: "Edward C. Jones" wrote in message news:<3CA1499D.4070802 at erols.com>... > John Machin wrote: > > "Edward C. Jones" wrote in message news:<3CA09F43.80206 at erols.com>... > > > >>Is there some simple way to call functions in modules from C? In > >>particular, for module struct, how do I call pack, unpack, and calcsize? > >> > > > > > > OK, I'll be the bunny and ask the obvious(?) meta-question: > > > > Give that the struct module is designed for Python callers to > > pack/unpack C structs (laboriously), why bother? Why not just > > manipulate the structs in C?? > > So I should use PyString_FromStringAndSize in C and struct.unpack in > Python or struct.pack in Python and PyString_AsStringAndSize in C. Clarifying your "or": Possible to use [PyString_FromStringAndSize in C and struct.unpack in Python] to pass data from C to Python AND [struct.pack in Python and PyString_AsStringAndSize in C] to pass data from Python to C. Just get check, re-check and re-re-check your format strings. Yes, you sure don't need to call Python's struct.anything() from C, especially struct.calcsize -- just spell it "sizeof" :-) The struct module is designed for Python callers who have to interact with C structs over whose format and layout the Python callers have no control -- for example data in a binary file. As you seem to be in control of both the Python side and the C side, you may have more flexibility. If I didn't already have lots of C code expecting the data to be in a particular struct, and there were only a few fields involved, I'd be inclined to use Py_BuildValue to send data from C to Python and PyArg_{Parse|Unpack}Tuple to get data from Python -- in other words, the normal argument passing and return-value mechanism. For a large/variable number of items of the same type, the array module would be indicated. Cheers, John From sjmachin at lexicon.net Sat Mar 23 16:05:03 2002 From: sjmachin at lexicon.net (John Machin) Date: 23 Mar 2002 13:05:03 -0800 Subject: Sorting distionary by value References: <7xd6xwntgx.fsf@ruckus.brouhaha.com> Message-ID: "Terry Reedy" wrote in message news:... > "John Machin" wrote in message > news:c76ff6fc.0203230339.48961684 at posting.google.com... > > Paul Rubin wrote in message > news:<7xd6xwntgx.fsf at ruckus.brouhaha.com>... > > > counts = {} > > > a = string.split(open(sys.argv[1],'r').read()) > > > for w in a: > > > if counts.has_key(w): > > > counts[w] += 1 > > > else: > > > counts[w] = 1 > > > > > > words = counts.keys() > > > words.sort() > > > words.reverse() > > > > > > for w in words: > > > print words[w], w > > > > Sorry, but this doesn't work. If you were to actually *run* your > code, > > you would get this result [after adding > > > > import string, sys > > > > at the start of the script]: > > > > print words[w], w > > TypeError: sequence index must be integer > ... > > Try replacing the last part of the script with: > > > > words = [(-count, word) for word, count in counts.items()] > > words.sort() > > for count, word in words: > > print word, -count > > or, I believe, change the last line to > print counts[w], w The basis for whatever it is you believe apparently doesn't include running the code. The effect of the above change is to list the results in reverse *word* order irrespective of the frequencies of those words e.g. 42 zot 1 foo 666 bar Anybody who considers this result to be useful, please post, as I would be delighted to converse with you. Cheers, John From bernie at 3captus.com Sun Mar 17 17:09:22 2002 From: bernie at 3captus.com (Bernard Yue) Date: Sun, 17 Mar 2002 22:09:22 GMT Subject: MySQL-mod: setup-error: invalid distrib.option 'platforms' References: <3C925742.8040001@web.de> Message-ID: <3C951470.FDCFC92B@3captus.com> Florian Konnertz wrote: > > Hi! Any idea how to solve this prob? > > root at xy /usr/local/mysql/MySQL-python-0.9.1 > python setup.py build > error in setup script: invalid distribution option 'platforms' > > OS: SuSe 7.2 > Python 2.0 > MySQL: /usr/local/mysql/bin/mysql > Ver 11.17 Distrib 3.23.49a, for pc-linux-gnu (i686) > > In setup.py I changed the following var. to my local paths: > ... > if sys.platform in ("linux-i386", "linux2"): # most Linux > include_dirs = ['/usr/local/mysql/include/mysql'] > # include_dirs = ['/usr/include/mysql'] > library_dirs = ['/usr/local/mysql/lib'] > # library_dirs = ['/usr/lib/mysql'] > > I appreciate your help! What's wrong? Are my paths too irregular? > Thanx. I've use Suse 7.3 with Python 2.1.1 and MySQL 3.23.46 (installed on /usr/local/mysql) and does not encounter the problem you are facing (BTW, same MySQL-python). Are you willing to upgrade your Python to give it a try? Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From andymac at bullseye.apana.org.au Sat Mar 2 06:00:56 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 2 Mar 2002 22:00:56 +1100 (EDT) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: Message-ID: On 2 Mar 2002, Konrad Hinsen wrote: > Tim Peters writes: > > > > # Python 2.2 > > > > > > >>> 1e-200**2 > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > OverflowError: (34, 'Numerical result out of range') > > > > That one is surprising and definitely not intended: it suggests your > > platform libm is setting errno to ERANGE for pow(1e-200, 2.0), or that your > > platform C headers define INFINITY but incorrectly, or that your platform C > > headers define HUGE_VAL but incorrectly, or that your platform C compiler > > generates bad code, or optimizes incorrectly, for negating and/or comparing > > I just tested and found the same behaviour, on RedHat Linux 7.1 > running on a Pentium machine. Python 2.1, compiled and running on the > same machine, returns 0. So does the Python 1.5.2 that comes with the > RedHat installation. Although there might certainly be something wrong > with the C compiler and/or header files, something has likely changed > in Python as well in going to 2.2, the only other explanation I see > would be a compiler optimization bug that didn't have an effect with > earlier Python releases. Other examples... FreeBSD 4.4: Python 2.1.1 (#1, Sep 13 2001, 18:12:15) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 >>> 1e200**2 Inf Python 2.3a0 (#1, Mar 1 2002, 00:00:52) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 >>> 1e200**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Result too large') Both builds built with "./configure --with-fpectl", although the optimisation settings for the 2.3a0 (CVS of yesterday) build were tweaked (2.1.1: "-g -O3"; 2.3a0: "-s -m486 -Os"). My 2.2 OS/2 EMX build (which uses gcc 2.8.1 -O2) produces exactly the same result as 2.3a0 on FreeBSD. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From morus.walter at web.de Tue Mar 26 15:18:19 2002 From: morus.walter at web.de (Morus Walter) Date: Tue, 26 Mar 2002 21:18:19 +0100 Subject: re.split and lookaheads Message-ID: Hi, I'm trying to split a string into two parts using zero width record boundaries. This should be possible by using a regular expression which consists of a lookahead only. Unfortunately python does not split my string. So for example: import re text = "abc" exp = re.compile("(?=b)") print exp.split(text) prints ['abc'] whereas I would expect ['a', 'bc']. (since (?=b) is supposed to match the position before b) Is this a limitation of pythons re split? Or am I missing something? If I use the same RE for searching, it matches as exepted: e.g. mo = exp.search(text) print mo.start(), mo.end() => 1 1 I know, that I can get the record boundaries as part of the result list, if the RE matches some text, but that's not really what I want to get. Any comments? greetings Morus From sjmachin at lexicon.net Fri Mar 29 17:26:42 2002 From: sjmachin at lexicon.net (John Machin) Date: 29 Mar 2002 14:26:42 -0800 Subject: Python 2.2 chr representation errors with embedded C References: Message-ID: "Mark Szigety" wrote in message news:... > Hello, > > I have recently made the upgrade to Python 2.2 from 1.5.2. In the > Python application which I develop, we have several embedded C > functions, one of which is a simple function to convert a hex string to Please post *examples*: (a) a "hex string" (b) its corresponding "100% accurate" conversion to octal by a C routine when called by Python 1.5.2 (c) its corresponding incorrect conversion to octal by a C routine when called by Python 2.2 > octal--it simply chars each byte and returns the new buffer. Please explain (or post the *relevant* parts of C routine) -- the verb "to char" has to me at least connotations not of C but of possibly injudicious application of heat in cookery :-) -- seriously, you don't convert from a hex representation to an octal representation by "simply charring" each byte, for any conceivable meaning of "char". > However, I > have noticed a 0.01% error rate in Python 2.2 which I did not see in > Python 1.5.2 (it was 100% accurate). That is, 1 out of 10,000 hex > strings will be converted incorrectly in the C function, usually one > byte is returned as \x00 instead of what is should be. 1. Could be a NUL-terminated-string gotcher. Show us the C code. 2. And unusually it exhibits what other kind(s) of incorrect behaviour? > I also have > noticed that in Python 2.2, chr(0xff) returns \xff instead of \377 in > Python 1.5.2. chr(0xff) has not changed; it returns "\xff" or "\377" which are just different ways of representing exactly the *same* 1-character string. The repr() function changed somewhere between 1.5.2 and 2.2 from producing an octal representation to producing a hex representation. What you are seeing is a difference in the representation of the result of chr(), not a difference in the result itself. > Could this be the source of the communication breakdown? Hmmm ... this misunderstanding could have percolated into the conversion routine. Makes me very curious to see what these "hex strings" are. > > I should mention that writing a similar conversion function totally in > Python is 100% accurate in Python 2.2 as well as Python 1.5.2, although > it is an order of magnitude slower. > If as you say the Python routine performs correctly, please post it -- two reasons: (a) it will help define what your requirement for the C routine is (b) the Python optimisation specialists may be able to eat into that "order of magnitude slower". From garrett at bgb.cc Mon Mar 18 17:32:43 2002 From: garrett at bgb.cc (Don Garrett) Date: Mon, 18 Mar 2002 22:32:43 GMT Subject: os.popen4 and exit codes Message-ID: <3C966B18.BB1E81BD@bgb.cc> My understanding for the popen2-4 functions was that they returned the exit code as the result of the last related call to close(). This seems to be working for me under Windows, but not Linux. This is the inverse of what I would expect. I'm running Python 2.2 built from the src RPM on a RedHat 7.2 machine, but found the same problem using the Python2 RPMs distributed by RedHat. As an example: >>> (stdin, stdout, stderr) = os.popen3("false") >>> stdin.close() >>> stdout.close() >>> stderr.close() I would expect the close of stderr to return 256, but that doesn't seem to happen. The close DOES return the exit code when I use os.popen(), but I need to be able to capture stderr. Is this a known bug, am I doing something wrong, and/or is there a decent workaround? I could do something funky like extend the command line to print the error code on the last line of output, but I'd prefer to do this right if I can. Thanks for any help! -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From gh_pythonlist at gmx.de Thu Mar 21 06:53:46 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 21 Mar 2002 12:53:46 +0100 Subject: How Can I Determine the Operating System with Python? In-Reply-To: References: Message-ID: <20020321115345.GA1542@lilith.hqd-internal> * Mark Hadfield [2002-03-21 14:02 +1200]: > "Jill Obsidian" wrote in message > news:cc779aae.0203201733.3717f882 at posting.google.com... > > > How can I put a check in my script which will allow me to determine > > whether I'm running on Windows or Linux at execution time? > > >>> import sys > >>> sys.platform > 'win32' > >>> import os > >>> os.name > 'nt' That's a crude way of determining the platform, because sys.platform depends on the compiler used to compile Python. Yes, even on Windows. But I'm reasonably sure that the Pythonlabs folks won't change their Windows compiler anytime soon. I'd very much like to have a real way for determining the platform. Anybody wants to write a PEP? :-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 13.3 ?C Wind: 7.1 m/s From narnett at mccmedia.com Fri Mar 15 15:26:30 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Fri, 15 Mar 2002 12:26:30 -0800 Subject: Word frequencies -- Python or Perl for performance? In-Reply-To: Message-ID: Anybody have any experience generating word frequencies from short documents with Python and Perl? Given a choice between the two, I'm wondering what will be faster. And a related question... any idea if there will be a significant performance hit (or advantage?) from storing the data in MySQL v. my own file-based data structures? I'll be processing a fairly large number of short (1-6K or so) documents at a time, so I'll be able to batch up things quite a bit. I'm thinking that the database might help me avoid loading up a lot of useless data. Since word frequencies follow a Zipf distribution, I'm guessing that I can spot unusual words (my goal here) by loading up the top 80 percent or so of words in the database (by occurrences) and focusing on the words that are in the docs but not in the set retrieved from the database. Thanks for any thoughts on this and pointers to helpful examples or modules. Nick Arnett From doug at pobox.com Mon Mar 11 17:49:55 2002 From: doug at pobox.com (Douglas Garstang) Date: 11 Mar 2002 14:49:55 -0800 Subject: Using doctest and executing a process Message-ID: <10d46bdc.0203111449.6bd761f5@posting.google.com> I'm trying to integrate execution of an external process output into doctest. The following snippet of code: def tester3(): """ >>> import os >>> os.system ('/bin/ls') example.py example.pyc tester.py 0 """ produces this output: (dougg at ultra5-4:)%python example.py example.py example.pyc tester.py ***************************************************************** Failure in example: os.system ('/bin/ls') from line #2 of example.tester3 Expected: example.py example.pyc tester.py 0 Got: 0 ***************************************************************** 1 items had failures: 1 of 2 in example.tester3 ***Test Failed*** 1 failures. WHY? It runs fine interactively. It also knows to expect the right stuff. It just SEEMS to think its only getting the return status code of 0. Where did the other output from the external program go? I also tried using os.spawnv instead of os.system and I got the same results. Regards Douglas Garstang From m2 at plusseven.com Tue Mar 26 02:29:36 2002 From: m2 at plusseven.com (m2 at plusseven.com) Date: Tue, 26 Mar 2002 08:29:36 +0100 Subject: reduce vs. for loop Message-ID: <20020326072936.GA12343@matijek> Just out curiosity, why is fact2 a bit faster than fact1? def fact1(n): return reduce (operator.mul, range(1L,n + 1)) def fact2(n): result = n * 1L for i in range(1 , n): result *= i return result -- o polite http://plusseven.com/gpg/ From lac at strakt.com Wed Mar 27 11:24:02 2002 From: lac at strakt.com (Laura Creighton) Date: Wed, 27 Mar 2002 17:24:02 +0100 Subject: list comprehension question In-Reply-To: Message from Peter Hansen of "Wed, 27 Mar 2002 07:19:10 EST." Message-ID: <200203271624.g2RGO2rq014696@ratthing-b246.strakt.com> It wasn't the Robot books where I was thiking of looking, but a different short story. I actually believe that apologies are something which are necessary due to one's-own need to behave rightly, rather than somebody else's need to receive redress. A society with both Asimov-type robots and small children needs to do something about the small child's propensity to order the robot to go jump out the space station airlock. When Mom says 'decent children don't order robots to do foolish things' she can't make an appeal to the robot's feelings, but to other things such as the anti-socialness of waste. Once such considerations come into play, the social value of apologising needs examination -- and certainly, in a society which is not based on enslavement, there is no room for somebody who is 'too big to apologise'. People who regularily avoid apologising when they know perfectly well that they are in the wrong need to do so far more for themselves than for other people. That is trying to opt in and out of society whenever it suits you. Now I remember reading this and thinking this was pretty powerful stuff when I was 14 or so. And nun-dominated boarding school, where I escaped classes that I was not interested in taking by illegally clibing trees, reading books where I could not be found since 'tree-climbing' was so much more forbidden than cutting physical educaiton classes that nobody thought to look for me in the trees. I'd sit in the top and watch them seek and call for me at ground level. Since thoughts that 'leopards kill their prey by dropping on them out of trees' featured hightly in my thoughts at such a time, the discovery that I might be damaging myself by opting out of society hit rather hard. And I believed that it was Asimov who mentioned that -- until today. It doesn't sound like him. It sounds more like Heinlein, but the Heinlein fans have posted every satement he has ever written to the net, so if I can't find it there, it is almost certainly not from Heinlein. (He does state this: In a family argument, if it turns out you are right - apologize at once! But it is doubtful that this quote would have had such an effect on me, my status as 'woefully misunderstood intellectual' was running at an all time high then. But figuring out if I wanted to reject all of society or only my status as child within it was a nice problem. And, arrogant worm that I was, I took great comfort in the fact that all the people whom I felt owed me apologies, (and there was quite a list) were secretly damaging themselves in nasty permanent ways. It was only much later that I was able to connect their ability to treat me and the other children so cruelly with the sort of damaging they were doing by not apologising. However, all of this would only have been funny if the quote about half of the apologising being for yoruself was from Asimov. In usenet fashion I will find the answer to who wrote this about 20 minutes after I post this. Laura From arthur.siegel at rsmi.com Tue Mar 26 10:36:34 2002 From: arthur.siegel at rsmi.com (arthur.siegel at rsmi.com) Date: Tue, 26 Mar 2002 10:36:34 -0500 Subject: keyword args - subclassing built-ins Message-ID: Using keyword args seems to be a no go when subbing at least numeric type builtins. This seems to hold even when introducing **kw down the road in the chain in a class multi-inheriting from a class derived from a builtin and a classic class. Or else I'm just confused again. Is anyone aware of documentation on the use of keywords with subs of built-ins. I am aware of the __new__ syntax, and expect my answer might be there somewhere - but I am not sure I can get the behavior I am looking for since __new__ is static. Art From loewis at informatik.hu-berlin.de Mon Mar 4 12:06:53 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 04 Mar 2002 18:06:53 +0100 Subject: Win32 2.2 & 2.1.2 References: Message-ID: Robin Becker writes: > Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the > default for a win32 box. It would allow us to dip a toe in the water > without drowning. Yes, you'll need to unpack all the files manually, then add the registry entries manually - except the ones where it associates .py files with the 2.2 executable. It might be best to do this by copying an existing installation. Regards, Martin From kp87 at lycos.com Wed Mar 27 05:31:38 2002 From: kp87 at lycos.com (kevin parks) Date: 27 Mar 2002 02:31:38 -0800 Subject: Most efficient unzip - inverse of zip? References: <3CA0ECAB.2070900@free.fr> Message-ID: <5e8bd451.0203270231.2295c7d1@posting.google.com> # Two unzippers! slightly different. first is from the python cookbook # (there are 2 there this one was much better than the other, which was # slow and not as flexible The second one is from the tutor list and is # fast, plus it allows you to grab only certain unzipped portions # Title:?A function to 'unzip' simple list-like objects # Submitter:?gyro funch (other recipes) Last Updated:?2001/08/28 # Version no:?1.0 # # Description: This function takes a list and pulls it apart into a # user-defined number of pieces. It acts like a sort of reverse zip # function (although it deals with only the very simplest cases). # # -- Renamed: unlace(), was def unzip(p, n): def unlace(p, n): """Split a list-like object, 'p', into 'n' sub-lists by taking the next unused element of the main list and adding it to the next sub-list. A list of tuples (the sub-lists) is returned. Each of the sub-lists is of the same length; if p%n != 0, the shorter sub-lists are padded with 'None'. Example: >>> unlace(['a','b','c','d','e'], 3) [('a', 'd'), ('b', 'e'), ('c', None)] """ (mlen, lft) = divmod(len(p),n) # find length of longest sub-list if lft != 0: mlen += 1 lst = [[None]*mlen for i in range(n)] # initialize list of lists for i in range(len(p)): (j, k) = divmod(i, n) lst[k][j] = p[i] return map(tuple, lst) # Date: Fri, 13 Jul 2001 23:01:36 -0500 # To: tutor at python.org # Cc: rob at jam.rr.com # From: "Christopher Smith" # Subject: [Tutor] Unzip # # Here's a piece of useless code which extracts lists that have been zipped # together (or mapped together with None: # map(Nane,l1,l2) is the same as zip(l1,l2) def unzip(l,*jj): """Returns one or more of the elements in the tuples of l that were zipped together. This code will unzip lists which have been zipped together. If you created a zipped list, l=zip(a,b,c), you can use unzip to extract one or more of the lists: >>> a=[1,2,3]; b=[4,5,6]; c=[7,8,9]; l=zip(a,b,c) >>> x,y,z= unzip(l) # get them all: x=[1,2,3], y=[4,5,6], z=[7,8,9] >>> y=unzip(l,1) # get the 1th one: y as above >>> x,z=unzip(l,0,2) # get the 0th and 2th ones: x and z as above """ if jj==(): jj=range(len(l[0])) rl = [[li[j] for li in l] for j in jj] # a list of lists if len(rl)==1: rl=rl[0] #convert list of 1 list to a list return rl From stephen at xemacs.org Mon Mar 4 12:00:33 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 05 Mar 2002 02:00:33 +0900 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87ofi42rpq.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Skip" == Skip Montanaro writes: Martin> A byte string should certainly be able to store arbitrary Martin> bytes. Under Stephen's proposal, it would indeed not be possible Martin> anymore to put arbitrary binary data into source code. This is not clear, but it is certainly the easiest way to deal with the issue. Skip> Just to make sure I understand correctly, under Stephen's Skip> propsal would Skip> s = "\xff" Skip> be correct? Correct in the sense that I'm sure it would be accepted. However, it would not necessarily be the only way to do it (in fact, it surely would not). Skip> s = "?" Skip> (a literal 0377 character) would be an error, yes? Assuming you mean that the source file contains eight bytes 0x73 0x20 0x3D 0x20 0x22 0xFF 0x22 0x0A the parser should reject it, as 0xFF may not occur in a UTF-8-encoded file. However, Python would surely provide an optional module to transparently decode that to UTF-8, before the parser proper sees it. There would be no reason to write throwaway code in UTF-8 for pretty much any language that already has codecs. I'd like to emphasize that the point of my proposal is not to make life harder for people who are just doing what comes naturally, and it shouldn't. AFAICT most of the things that people would like to do will be just as easy to do under my proposal as under Martin's. They just won't be sanctioned as part of "true" Python. It's kind of like a contract: you can translate it into other languages, but for the purposes of legal interpretation, there is an original language which is that of the court with jurisdiction. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From gh_pythonlist at gmx.de Sun Mar 31 20:57:34 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 03:57:34 +0200 Subject: chat server In-Reply-To: <3CA4544D.6646CB30@q-survey.be> References: <3CA4544D.6646CB30@q-survey.be> Message-ID: <20020401015734.GD333@lilith.hqd-internal> * Laurent Szyster [2002-03-29 12:47 +0100]: > Henning Peters wrote: > > > > i am planning to write a small chat server that uses select() in > > python. multiple clients should be able to connect and chat wih > > each other - like on a normal chatserver, just asynchronous ... > > Don't reinvent the wheel. Use asyncore.py and asynchat.py, it's > part of the standard Python library. Or SocketServer, also in the standard library. Easiest to use in my experience is sockserv, which can be found in the Vaults of Parnassus. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 5.9 ?C Wind: 0.8 m/s From tanzer at swing.co.at Thu Mar 7 01:02:00 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Thu, 07 Mar 2002 07:02:00 +0100 Subject: Reorganizing python.org (was: Why isn't pychecker...) In-Reply-To: Your message of "Wed, 06 Mar 2002 13:15:53 +0100." <3C860879.BEC1002B@philips.com> Message-ID: Gerrit Muller wrote: > > > > Another example, the otherwise superb intro to Tkinter, > > > > http://www.pythonware.com/library/tkinter/introduction/index.htm > > > > would be vastly more useful if it fit on a single page. > > > > > > Define "page". If you say 800x600 you'd lose. > > > > Good question. How would you define a page in terms of web design? > > > > Eliminating most if not all scrolling on reference pages seems > > particularly important. Some reference pages seem way too long. And > > your point is well taken. I have a large monitor, but I use relatively > > big fonts, so I'm only using 1024x768... > > > > Edward > <...snip...> > at this moment in time 1024*768 is a reasonable choice; the poor 14" CRT > users will need some scrolling, but all more lucky 15" LCD and 17" CRT > and above will have a scroll free overview. You are assuming that everybody is wasting the full screen on the browser's window. That might be true for the average windows user but is not true in general. For instance, my monitor displays 1800x1024, but the browser gets only about 850x650 of that. IMHO, software/web pages making such assumptions suck. -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From lenny_self at hotmail.com Thu Mar 7 18:59:01 2002 From: lenny_self at hotmail.com (Lenny Self) Date: 7 Mar 2002 15:59:01 -0800 Subject: List of Dictionaries Message-ID: <14dc40e2.0203071559.5e3d4550@posting.google.com> I am having a problem I was hoping someone might be able to help me with. I am attempting to append several dictionaries to a list for further processing, however I am seeing some rather odd behavior. When I add the first dictionary element to the list all is well. When I add the second element to the list both the first and second element reference the second dictionary that was added. The behavior continues whenever I add an element. So, if I add, say 50 dictionaries, all of the listes elements reference the last dictionary I added. I don't have the code with me right now, but I can assure you it is easy as this: allMail = [...] # list of mail objects dictsList = [] for mail in allMail: dictsList.append(mail.getData()) # getData returns a dictionary I have tried this code with both Python 2.1.1 and 2.2. Same behavior. Also, I am positive that each of the objects I attempt to append to the list are different. Any suggestions? Any help would be great. Thanks. -- Lenny From h.jehadalwan at student.kun.nl Mon Mar 11 03:45:57 2002 From: h.jehadalwan at student.kun.nl (husam) Date: Mon, 11 Mar 2002 09:45:57 +0100 Subject: How do you protect the source code of python applications? Message-ID: <3C8C6EC5.8080308@student.kun.nl> hi, Is there a way to protect the source code of applications written with python? From tdelaney at avaya.com Mon Mar 25 01:44:07 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 25 Mar 2002 17:44:07 +1100 Subject: files and reading from them Message-ID: > From: Avi Homes [mailto:Moo at houston.rr.com] > > I am writing a dictionary to a file, like so > f.write(str(Info)) [snip] > What i would like to do is pull a readline or somesuch.. and > have it take in > the whole thing, and then just let me assign that to a empty > name, and turn > it into a new dictionary.. like say > file.seek(1) > //thats how i'd go to the first place in the file correct? > X=file.readline() Look up 'pickle' and 'cPickle' in the python reference. Tim Delaney From helmut.zeisel at aon.at Fri Mar 8 08:28:56 2002 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: 8 Mar 2002 05:28:56 -0800 Subject: Embedded Python and SWIG shadow classes Message-ID: I used SWIG to create some Python shadow classes for my C++ library, say MyClass { ... }; MyClass myFct(); No I want to call embedded Python code from a C++ program, i.e. in C++, I call PyObject* pmod = PyImport_ImportModule("myclass"); PyObject* pdict = PyModule_GetDict(pmod); PyObject* p = PyRun_String("myFct()", Py_eval_input, pdict, pdict); How do I extract the MyClass mc from the PyObject* p? >From what I can see from the generated myclass_wrap.cxx, I have to use something like MyClass* mc; if ((SWIG_ConvertPtr(p,(void **) &mc, SWIGTYPE_p_MyClass,1)) == -1) { cout << "Not converted" << endl; } else { cout << "Converted" << endl; } First problems were, however, that SWIG_ConvertPtr and SWIGTYPE_p_MyClass are unresolved symbols. So I comnpiled myclass_wrap.cxx with -DSWIG_GLOBAL and replace SWIGTYPE_p_MyClass by _swigt__p_MyClass, and added some struct definitions and static swig_type_info _swigt__p_MyClass[] = {{"_p_MyClass", 0, "MyClass *"},{"_p_MyClass"},{0}}; to the C++ program calling PyRun_String. No my code compiles and links, but the output is "Not converted" What is the usual way to solve this problem? Helmut From python at chajadan.net Fri Mar 1 04:47:47 2002 From: python at chajadan.net (chajadan) Date: Fri, 01 Mar 2002 01:47:47 -0800 Subject: wxPython error on import Message-ID: <5.1.0.14.0.20020301014436.00a79ae0@63.118.78.184> I get this error: from wxPython.wx import * SystemError: C:\Code\22\Objects\listobject.c:88: bad argument to internal function Now, there is no C:\Code\22\ anything on my comp, but maybe you guessed that. This error generates with or without the .wx on wxPython I'm on Windows, using python 2.2 and wxPython (Hybrid) for 2.2 hmm.... maybe it's this hybrid thing... any help, as always, gives me less work to do ;) --chajadan From phd at phd.pp.ru Wed Mar 27 07:11:07 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 27 Mar 2002 15:11:07 +0300 Subject: overwrite bytes in file In-Reply-To: <3ca1c344.16256546@news.easynews.net>; from stojek@part-gmbh.de on Wed, Mar 27, 2002 at 01:05:47PM +0000 References: <3ca1c344.16256546@news.easynews.net> Message-ID: <20020327151107.B30084@phd.pp.ru> On Wed, Mar 27, 2002 at 01:05:47PM +0000, Marcus Stojek wrote: > how can I overwrite certain bytes in a file (Win NT) and > keep the rest unchanged. Just open the file, seek to some position and start writing. > All open options are truncating the file. No, not all. Use "open(filename, 'rb+')". Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From gerson.kurz at t-online.de Fri Mar 1 13:50:34 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 01 Mar 2002 18:50:34 GMT Subject: ANN: experimental patch to allow importing from file-like objects Message-ID: <3c7fcbe6.7419921@news.t-online.de> Motivation: Write a customized import that reads data from encrypted files. Both execfile() and exec() are limited, if only that that they don't mimic the import syntax. Problem: imp.load_module does expect a file object, but you can only pass "real" files, not file-like objects. The internal C-code expects native FILE* stuff. Solution: An experimental patch to the python22.dll that makes this possible. Using file-like objects for import opens up a whole new set of possibilities, for example you could fetch the code at runtime from a database or a socket. Limitations: - Currently, Win32 only. - Currently, you can only import source from file-like objects, not precompiled binaries. - Currently, error handling is completely undefined. Sample Code: import imp, os, rotor # sample code *************************************** source = """ print 'Inside encrypted code' variable = 123 """ # generate encrypted file *************************** file = open("test.raw","wb") rt = rotor.newrotor('key', 12) file.write( rt.encrypt(source) ) file.close() # sample file class, that reads data from encrypted file class my_file_class: def __init__(self,filename): rt = rotor.newrotor('key', 12) self.lines = rt.decrypt(open(filename).read()).split('\n') print "read", len(self.lines), "lines from encrypted file" def read(self,size): if self.lines: line = self.lines[0] # must make sure line ends with \n if not line: line = '\n' elif not (line[-1] == '\n'): line += '\n' self.lines = self.lines[1:] return line # redirect import hook ****************************** old_import_func = __import__ def my_import_func(name, globals=None, locals=None, fromlist=None): global old_import_func if name == "encrypted_test": return imp.load_module(name, my_file_class("test.raw"), "test.raw", ('.raw','rb',imp.PY_FILEOBJECT_SOURCE)) # use original code return old_import_func( name, globals, locals, fromlist ) __builtins__.__import__ = my_import_func # test code import encrypted_test print encrypted_test.variable Download: http://p-nand-q.com/python/pyimport.zip More technical details: http://p-nand-q.com/pyimport.htm (at the bottom) Now what? PEP-stuff? Or completely uninteresting? From rann-chan at attbi.com Sun Mar 24 17:32:35 2002 From: rann-chan at attbi.com (Rann Aridorn) Date: Sun, 24 Mar 2002 22:32:35 GMT Subject: I am TGOS your new ruler References: <07fcd5f6.3ba05335@tgos.org> <2sjl7a.ap6.ln@hairy.machine.org> Message-ID: <3C9E5402.7070406@attbi.com> Sly Mee wrote: > On Sun, 24 Mar 2002 12:46:44 -0600, TGOS said: > > >>That's right you stupid, inbred, shit eating, pathetic, motherfucking, >>brain dead, useless cocksuckers! I'm taking over all of Usenet! There >>isn't a fucking thing you can do about it either! You're all a bunch of >>worthless scumbags, and now you will all answer to me! If you don't like >>this fact TOO FUCKING BAD! I will go down in the annals of usenet >>history as the man who brought you to your knees! Now get down on your >>knees and pay proper tribute to my glorious self! >> >>I AM THE GUARDIAN OF SAILOR MOON! LORD AND HIGH MASTER OF USENET! >> > > .....And High Moron of All You Survey! > > Sorry about this. A hipcrimer is trying to cause trouble for Alt.Hentai.Sailor-Moon by impersonating one of our regulars. If you care to register your displeasure, please do so in the hipcrimer's own stomping grounds, alt.mag.hustler -Rann From greg at cosc.canterbury.ac.nz Tue Mar 5 19:32:54 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 06 Mar 2002 13:32:54 +1300 Subject: Status of PEP's? References: Message-ID: <3C8563B6.1DB3B19@cosc.canterbury.ac.nz> James_Althoff at i2.com wrote: > > I don't have to think that a dict object *is* a sequence to be content with > it being a valid arg to iter(). Well, more generally, "collection". And I *do* think of a dict as being a collection -- of key-value pairs. It's perhaps debatable whether its iterator should return just the keys or keys+values, but the decision made here makes perfectly good sense to me. In real life, it doesn't seem at all odd to ask things like "Is 'furgleblunger' in the dictionary?" But if someone asked me "Is 7 in 42?" I'd think I'd misheard them somehow. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From dragon at china.org Sat Mar 9 11:29:33 2002 From: dragon at china.org (Qiang.JL) Date: Sat, 09 Mar 2002 16:29:33 GMT Subject: should i learn it first ? References: <7xpu2ex6xz.fsf@ruckus.brouhaha.com> Message-ID: thanks for your insightful answer , Paul "Paul Rubin" wrote in message news:7xpu2ex6xz.fsf at ruckus.brouhaha.com... > "Qiang.JL" writes: > That's separate from needing to learn something to be a good > programmer. To be a good programmer I think you need a sense of what > the machine is doing, so you should learn a low level language, but if > you're just doing it for the sake of learning, you may as well go all > the way and learn to program in assembly language. There used to be a > saying that assembly language programming is good for the soul. > > That doesn't mean you should actually try to develop complex programs > in assembler and make them useful--you should just get some experience > with it as an exercise, to understand how computer's instruction set > works and have a sense of what a compiler does. Once you've done > that, C will seem very straightforward and logical to you. oh, assembly language. It's one of my course now :) > > which one is better to start with ? ( I'm not a program beginner so python > > being a beginner programmer maybe not be applied here) > > > > How many language do you think one should _master_? I think one or two is > > enough.learning others are letting you to learn the language concept and > > structure etc certainly helpful. > > If you're an experienced programmer in other languages, you can learn > basically everything about Python in a few weeks. C++ takes longer > but again, it's just a computer language that some people designed. > It's not like a spoken language which evolves over thousands of years. > The thing is, to really understand C++, you have to spend time working > on multi-programmer projects. If you only program by yourself, some > parts of C++ will never make sense to you. Note that i said to have a couple language to "master"? I really want to learn some in depth not just being able to write couple lines. currently these languages i am going to dig deeper and know it better. java perl python (maybe C/C++ someday, man i really have the urge to learn it,as everyone around me saying to get into serious programming, C/C++ is a must. well, i heard what you said :- ) and there are a lot more i want to learn. popular or useful .................... Q. From tanzer at swing.co.at Sun Mar 17 07:58:44 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Sun, 17 Mar 2002 13:58:44 +0100 Subject: mixing regular expression In-Reply-To: Your message of "Sun, 17 Mar 2002 05:46:11 GMT." Message-ID: "Ian McMeans" wrote: > I want one huge regular expression to be composed of a bunch of others > - is there some way I can include a regular expression inside another? > > Or should I do it with strings - just save each regular expression's > string, and then compile each combination separately? > > What I mean is this: > foo = re.compile("someregexcode") > bar = re.compile("moreregexcode") > > big = re.compile("foo|bar") > > is that possible at all? To combine regular expression objects? Or do > you suggest that I just make strings for foo and bar, and then compile > the combined strings into big? >>> import re >>> foo = re.compile("someregexcode") >>> bar = re.compile("moreregexcode") >>> big = re.compile("%s|%s" % (foo.pattern, bar.pattern)) >>> big.pattern 'someregexcode|moreregexcode' -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From jimd at vega.starshine.org Tue Mar 19 12:50:51 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 19 Mar 2002 17:50:51 GMT Subject: Access to shared directories References: Message-ID: In article , Tim Howarth wrote: > >In message > "Fabrizio" wrote: >> I just want to read a .txt file that I have in a shared directory on >> another PC which is part of a WindowsNT/98 LAN. >> What path should I use in order to read that file from my PC ? >\\pcname\sharename\file.txt Warning: under Python you'll usually want to specify a "raw string" for MS Windows path names: r'\\machine\share\filename.ext' ... otherwise Python's string parser will try to interpret the backslash sequences like \n (newline) \r (return) \t (tab) \0xNN (hex character code) \0nnn (octal char. code) \\ (one "real" backwack) etc. This is an FAQ. Newbies frequently have trouble with filename literals under various MS OSes. Normal Python strings are delimited with single or double quotes 'foo' or "foo." However, "raw" strings are preceded by a letter r as in r'foo,' R"foo," R'foo' or r"foo." Newer versions of Python also support unicode literals (preceded by a U if I recall correctly). BTW: you cannot end a raw string literal with a single \ but you can "add" one to a string using the + operator. Thus foo = r'\something\somewhere' + '\\' print foo ... yields: \something\somewhere\ >___ > |im ---- ARM Powered ---- From tdelaney at avaya.com Wed Mar 6 18:09:33 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 7 Mar 2002 10:09:33 +1100 Subject: PEP 284, Integer for-loops Message-ID: > PEP 276 [4] proposes to allow automatic conversion of integers to > iterators, simplifying the most common half-open case but not > addressing the complexities of other types of interval. > Additional alternatives have been discussed on python-list. This is incorrect. PEP 276 proposes to make integers iterable. There is a significant difference, which I have noticed you either not understanding or ignoring. I would suggest an amendment to PEP 284 to correct this. Whilst I like the general idea of PEP 284, I see too many problems with it - most notable, that it is an attempt to be a general solution (whether the problem exists or not - I believe it does) without being a general solution (no step ... though it can be simulated to an extent, different syntax to traverse in the opposite direction, etc). Cheers. Tim Delaney From netzapper at magicstar.net Sat Mar 2 12:44:08 2002 From: netzapper at magicstar.net (A. Jones) Date: Sat, 02 Mar 2002 17:44:08 GMT Subject: Newbie question Message-ID: <3c810efa.475638531@mammoth.usenet-access.com> What is the function that forces conversion to a three-quote string? I need to save a string that has a LOT of \n's in it, and need to save both the formatting and the \'ns. I checked the manuals (and the online lists of functions), and all I came up with was str(), which doesn't do the tripple quote. Thanks ______________________________________________________________________________ Posted Via Binaries.net = SPEED+RETENTION+COMPLETION = http://www.binaries.net From gh_pythonlist at gmx.de Tue Mar 5 02:26:55 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 5 Mar 2002 08:26:55 +0100 Subject: Get reference to "owner" In-Reply-To: References: Message-ID: <20020305072655.GA1525@lilith.hqd-internal> Le 05/03/02 ? 01:41, Robert Oschler ?crivit: > I've never seen this feature in any programming language I've worked in but > it can't hurt to ask. Can an aggregated class object get a reference to the > class object that aggregates it? So if ClassAggregator contained an > instance of ClassAggregatee is there a Python syntax/construct that a > function in ClassAggregatee could use to get a reference to the instance of > ClassAggregator that contained it? I've no idea what you're talking about. But this doesn't hinder me from replying ;-) You want to do something like the following? import sys, traceback class A: def __init__(self): self.b = B() class B: def __init__(self): # Determine here from where we're instantiated a = A() If this is possible at all, I think it will involve the traceback module. I can't currently think of a complete solution, though. With traceback.extract_stack, one could easily determine the line you're called from, but I can't think of a way to determine the class. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 1.9 ?C Wind: 0.8 m/s From jeff at ccvcorp.com Tue Mar 26 18:32:45 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 15:32:45 -0800 Subject: seek in a file References: Message-ID: <3CA1051C.250D3D2E@ccvcorp.com> Andreas Penzel wrote: > Hello NG! > > How to jump to a specified line in a file which is read-opened? > With seek() I can jump to an exact position of the complete file in > "byte-steps". > Is seek able to jump to a line-number? > If not, what else can I do? seek() won't work well on text-mode files, because the number of bytes does not necessarily equal the number of characters (due, mostly to /r/n <-> /n conversions). I think that the best you can do to jump to a particular line number would be using readlines()/xreadlines() and skipping over the initial (undesired) part. Jeff Shannon Technician/Programmer Credit International From joekm at earthlink.net Mon Mar 25 18:04:11 2002 From: joekm at earthlink.net (Joe) Date: Mon, 25 Mar 2002 23:04:11 GMT Subject: Programming Puzzle for you Experts out There Message-ID: <3c9fa91e.506871@news.earthlink.net> First a little background: I'm in the process of writing a fatigue and damage tolerance analysis program using python. One of the things the math engine can do is compute the remaining strength of the material after it has sustained damage. However, there are two problems: 1) Redisual strength is influenced by two competing physical properties of the metal. So far, nobody has developed a method for evaluating the transition between these properties so the conventional wisdom is to "eyeball" a curve between them. 2) Sometimes, the damage or fatigue involves a "ligament break", this will suddenly change the stress field and, not surprisingly, cause a step change in the residual strength curve. So here is the problem...... I have two vectors that, when plotted against each other are mostly smooth with occasional inflection points and step changes. I want to keep the step changes but inscribe a smooth arc below the inflection points that will eventually be tangent to the intersecting curves. Now, here is the hard part...... To get the boundary conditions, I must sample the vectors "as is". Re-iterating the numbers to get better data will require me to go back into the math engine which will suck up processor time. I've tried 4th order polynomial fits and hyperbolic fits but neither have been robust enough to track all of the fracture scenarios I've thrown at it without Gibb's overshoots or other issues. I have not tried Fourier or other series fits as of yet. Probably try that next. Still working on it....but I'm willing to entertain suggestions. Joe From tim.one at comcast.net Fri Mar 29 15:17:48 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 29 Mar 2002 15:17:48 -0500 Subject: test_struct.py fails when building Python 2.2 on RedHat 6.2/alpha In-Reply-To: Message-ID: [Mike Carifio] > I've recently built Python 2.2 on a RedHat 6.2/alpha box. > When I run the regression test suite ('make test'), test_struct.py > fails with a floating point exception and stops the regression test > suite. > > Some questions: > > 1) Is this a know error or have I discovered something new? It's news to me. > I tried to find out if this error was seen before by going to > the python bugs database ... > and searching the newsgroup in Google. Are there other sources? You already found the best. > I didn't find a good way to search the sourceforge bug tracker for > specific keywords (like 'test_struct' or 'alpha'). There's a "Search" box in the left margin. Be sure the dropdown list has "Bugs" selected. It turns up 3 test_struct bug reports, all closed. > 2) Once I take test_struct.py out of the test list, the suite runs to > completion, but I still have 24 tests that have failed. Sounds like your installation is a mess. Open a bug report and attach some details (like *which* tests failed). > Are all tests the same? No. > For example, if test_bsddb fails, is my installation bogus or > should I just shy away from db files on RH6.2/alpha? It's impossible to guess from what you've said so far -- open a bug report and people will help there. > Is there a document or file somewhere that tells me how to interpret > these results? No. The tests are all written in Python, so ambitious users dig into them and figure out why they fail. > 3) And related to (2), is test_struct.py a "mandatory" test? It tests the struct module. If you never use the struct module, it probably doesn't matter whether it fails. But there's no good reason for it failing, so it suggests deep problems. It *sounds* like your build was such a disaster that you've got severe problems. > I guess the question I'm asking is: if some of the tests fail, is > the build to be distrusted? If there's a judgment call to make here, how > do I inform my judgement? Sorry, that's up to you. I personally would not trust a box where any test failed; tests being skipped is a different issue. From dubois at users.sourceforge.net Sat Mar 16 11:35:44 2002 From: dubois at users.sourceforge.net (Paul F. Dubois) Date: Sat, 16 Mar 2002 16:35:44 GMT Subject: HP-UX, PyThread_* missing Message-ID: I am trying to get Python 2.2 to compile on HP-UX B.10.20. I get a set of missing externals with names PyThread_something. I need threads so I don't want to turn them off. Is there a package I need to install first? Or some other hint about what to do? From gerhard at bigfoot.de Fri Mar 22 12:53:30 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 22 Mar 2002 17:53:30 GMT Subject: New SIG on logic/CLP programming in Python References: Message-ID: Nicolas Chauvat wrote in comp.lang.python: > [About Mozart] the syntax is... difficult. That's putting it nicely. Not that I've done very much besides 'Hello, world' in the Mozart tutorial, though. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From evil_wicked at ofir.dk Mon Mar 18 02:44:01 2002 From: evil_wicked at ofir.dk (h_b_jensen) Date: Mon, 18 Mar 2002 07:44:01 -0000 Subject: Installing CXX: ImportError Message-ID: When installing CXX: 1) Untar file in /usr/local 2) cd PyCXXblabla 2) python setup.py install ...this error occurs: [pos at localhost PyCXX-V5.1-rc2]$ python setup.py install Traceback (innermost last): File "setup.py", line 3, in ? from distutils.command.install import install ImportError: No module named distutils.command.install Shouldn't distutils be properly installed when you install Python 2.2 this way: 1) Untar Python-file 2) ./configure 3) make 4) make install ? Thanks in advance, Best regards, Henrik Jensen From dguest at bigfoot.com Tue Mar 19 04:44:15 2002 From: dguest at bigfoot.com (David Guest) Date: Tue, 19 Mar 2002 20:44:15 +1100 Subject: Relieved but disappointed: The Pariah thread References: <5l2c9usr5q536u9ki0vc38jlu6oud859sj@4ax.com> <1016467478.18470.38.camel@ahopkins> Message-ID: <3C97086F.1030504@bigfoot.com> marduk wrote: >LOL > >On Mon, 2002-03-18 at 09:48, Dale Strickland-Clark wrote: >[...] > >>This easily the most humourless, anal-retentive group I read. >> >>The most daring humour you are likely to get away with is a bit of >>clearly labelled sarcasm. >> >>Or, for a real belly laugh, string a bunch of words together with >>hyphens and add '-ly yours' on the end. >> >>I gave up ages ago. >>-- >>Dale Strickland-Clark >>Riverhall Systems Ltd >> I think you meant LOL-ly yours. ~~~~~~~~~~~~~~~~~~~ David Guest self.reflexion == narcissism 1 From bokr at oz.net Tue Mar 26 20:14:23 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Mar 2002 01:14:23 GMT Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> <11e94203.0203232201.4dde9883@posting.google.com> Message-ID: On 23 Mar 2002 22:01:45 -0800, jriveramerla at yahoo.com (Jose Rivera) wrote: >Thanks for your comments... the site uses POST method, so >I saved to disk the page, and modify it to use GET so >I could get an idea of the parameters used... >The URL calculated : > >http://avisos.elnorte.com/casa_venta_result.asp?fotos=0&Order=order+by+colonia&Precio_i=-1&Presentacion=Tabla&Precio_f=-1&PLANTAS=0&pagina=1&id_inmueble=3&dia=&RECAMARAS=0&constr_f=-1&COLONIA=0&BANOS=0&Tipo=CASAS&Constr_i=-1&Terreno_i=-1&Terreno_f=-1&zona=0 > >works on my PC, try it, and let's see whats wrong. > >thanks for your time, and comments. > >Does anyone have an idea of how I can save it to a DataBase? Is there >a better way? > The best way would probably be to get an account on their database and talk to it directly over a secure SSL link, and bypass all the web stuff. Do you think they would go for that? Regards, Bengt Richter From theller at python.net Tue Mar 19 07:45:34 2002 From: theller at python.net (Thomas Heller) Date: Tue, 19 Mar 2002 13:45:34 +0100 Subject: py2exe and Tkinter References: Message-ID: "Lindstrom Greg - glinds" wrote in message news:mailman.1016477010.23588.python-list at python.org... > Please excuse me if this is not the correct forum, and gently point me to > the correct list. c.l.p is ok - there are no mailing lists for py2exe. > > I am attempting to create a standalone application that has a GUI generated > with Tkinter. I have a myfile.exe that was generated from py2exe, but when > I try to execute it (both by double clicking and trying to launch it from a > DOS command line) I get nothing. Do I need to do anything "special" to my > all to work? > > I'm on Windows 2000 "Professional" using Python 2.2. > If you don't see *anything* at all, you should probably try building a console application first (see the --console flag), so that you can at least see the tracebacks. Thomas From gerhard at bigfoot.de Wed Mar 20 02:14:13 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 20 Mar 2002 07:14:13 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> Message-ID: (Followup-To set to comp.lang.python, as this doesn't have any relevance to Java any more) Ahmed Moustafa wrote in comp.lang.python: > How about web development? A little research of yourself would tell you all you need to know, but I'm happy to give my informed opinion ;-) Web development is one area where Python really shines. Almost all of the Python users I know personally use it for web development. My biggest webapp was build an online shop system with Python and MySQL. From scratch, with its one templating system (of course), dynamic site navigation and all that stuff. Development time was only some 6 to 8 weeks. All the rest at http://www.python.org/topics/web/ > Also, how is Python doing in the embedded applications? It's possible, but people using it for this are certainly a minority among Python developers. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From lac at strakt.com Mon Mar 18 05:40:56 2002 From: lac at strakt.com (Laura Creighton) Date: Mon, 18 Mar 2002 11:40:56 +0100 Subject: tkFileDialog.py - opening remote files on a server Message-ID: <200203181040.g2IAeuiT012032@ratthing-b246.strakt.com> askopenfilename does exactly what I want -- except that I would like to pass it a known list of files that my server is exporting to my clients, rather than have it check any directories locally. It looks to me as if I have to start grubbing around in Tk -- there isn't anything in Tkinter I can override. Before I start doing this I thought I would check and see if anybody has already done this. thanks very much, Laura Creighton From gh_pythonlist at gmx.de Thu Mar 7 20:19:55 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 8 Mar 2002 02:19:55 +0100 Subject: reporting spam? (was RE: 5 dollar emails) In-Reply-To: References: Message-ID: <20020308011954.GA4417@lilith.hqd-internal> Le 07/03/02 ? 16:52, John Schmitt ?crivit: > What happens with all the spam this group gets? Does anyone bother > forwarding it to spam-fighting agencies? [...] SpamAssassin (one of the few P*rl programs I liked enough to install) does the spam filtering for me and it does an amazingly good job at it. The spam (and a few false positives) getted tagged and put in my caughtspam folder, which I review regularly. Then, I'll forward all the real spam to spamcop.net, which analyzes the mails for me (whom to complain to) and sends me a confirmation mail with URLs to complete the submission. It'll then write emails to the admins of the relevant ISPs. A few clever mutt settings make this less of a pain :) Alas, it doesn't seem to have much effect in that many providers don't seem to care. In particular, most (I'd say 75 %) of the spam I get privately and on mailing list comes from Korea. So I'm thinking about just blocking all mail from a few Korean providers that are particularly resistant to fighting spammers. Most spam I get recently comes from these providers kornet.net (most) hananet.net thrunet.com I've even received German spam sent thru machines on kornet.net :-(( Maybe we should try to talk our providers from blocking all mail from the major Asian spam sources. This would certainly help build pressure on these providers by their legitimate users. If anybody is interested in this topic, this is a more appropriate newsgroup: news.admin.net-abuse.email. Nevertheless opinions from Python folks would sure be interesting. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.6 ?C Wind: 2.5 m/s From deltapigz at telocity.com Sat Mar 9 17:33:32 2002 From: deltapigz at telocity.com (Adonis Vargas) Date: Sat, 9 Mar 2002 17:33:32 -0500 Subject: Tkinter + Button widget Message-ID: <3c8a93b8$1_3@nopics.sjc> when i start a button widget, it automatically fires the command? def HideNewClient(self, frame): frame.configure(bd=0, width=0, height=0) return pdb_btnSearch = Button(pdb_frmCommands, text="Search", relief=GROOVE, font=("Tahoma", 10), width=16, command=self.HideNewClient(pdb_frmNewClient)) any help would greatly be appreciated. Adonis From martinkaufmann at yahoo.com Wed Mar 13 06:54:27 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Thu, 14 Mar 2002 00:54:27 +1300 Subject: Question about scientific calculations in Python References: Message-ID: <09fu8u4t6rakpg4lotvgpjl3d3h4e80rl5@4ax.com> On Tue, 12 Mar 2002 17:01:16 +0000, Fernando P?rez wrote: >> Do you mean the array calculation of NumPy? > >Yes. A quick example (trivially easy, but shows the point): [helpful introduction into NumPy snipped...] Thanks. I see the point, but I don't think that it is possible to fit my problem directly in this solution. At least I know now the direction I have to go. >So again, the morale is: at all costs avoid looping in python in >performance-critical parts of the code, once you've reached the optimization >stage. In those parts, get creative: weave.blitz, weave.inline, >weave.ext_tools, SWIG & friends (SILOON, boost, etc) in order of increasing >complexity. Yes, I started playing with weave. The speed looks really impressive. Many Thanks, Martin From slimey at choc.late.org Sun Mar 24 17:27:14 2002 From: slimey at choc.late.org (Sly Mee) Date: Sun, 24 Mar 2002 16:27:14 -0600 Subject: I am TGOS your new ruler References: <07fcd5f6.3ba05335@tgos.org> Message-ID: <2sjl7a.ap6.ln@hairy.machine.org> On Sun, 24 Mar 2002 12:46:44 -0600, TGOS said: > That's right you stupid, inbred, shit eating, pathetic, motherfucking, > brain dead, useless cocksuckers! I'm taking over all of Usenet! There > isn't a fucking thing you can do about it either! You're all a bunch of > worthless scumbags, and now you will all answer to me! If you don't like > this fact TOO FUCKING BAD! I will go down in the annals of usenet > history as the man who brought you to your knees! Now get down on your > knees and pay proper tribute to my glorious self! > > I AM THE GUARDIAN OF SAILOR MOON! LORD AND HIGH MASTER OF USENET! .....And High Moron of All You Survey! -- Well, what was the ham cured OF? --- 100 Proof News - http://www.100ProofNews.com --- 1,500+ Binary NewsGroups, and over 90,000 other groups --- Access to over 100 Gigs/Day - $8.95/Month --- UNLIMITED DOWNLOAD From skip at pobox.com Sun Mar 17 20:21:26 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 17 Mar 2002 19:21:26 -0600 Subject: Python/JXTA In-Reply-To: References: Message-ID: <15509.16662.13819.451929@12-248-41-177.client.attbi.com> moxie> It may be a good idea to create Python bindings for JXTA (P2P moxie> [peer-2-peer] networking solution from Sun)... moxie> http://www.jxta.org/project/www/background.html moxie> Just a thought ;) By our guest. Once you have something, here's the patch submission page: http://sourceforge.net/tracker/?group_id=5470&atid=305470 ;-) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From mwh at python.net Tue Mar 5 10:10:57 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Mar 2002 15:10:57 GMT Subject: Generators and iterators References: Message-ID: bergeston at yahoo.fr (Bertrand Geston) writes: > Hello, > > I just quickly red the page about new features in Python 2.2 and tried - for > fun - to test it. It must be obvious but I really don't see why, in the > console transcript below, z.next() send back None and not 1,2 and 3 > whereas it does it correctly 3 times, no more no less. You forgot a "return". Cheers, M. -- 39. Re graphics: A picture is worth 10K words - but only those to describe the picture. Hardly any sets of 10K words can be adequately described with pictures. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From DavidA at ActiveState.com Thu Mar 28 17:40:01 2002 From: DavidA at ActiveState.com (David Ascher) Date: Thu, 28 Mar 2002 14:40:01 -0800 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: <3CA39BC1.59873E78@activestate.com> > Absolutely. All of Mark's Win32 stuff are pretty much essential to > many Windows users now, I would guess. > > Updating the distro package would be nice too: Add a few handy > registry tweaks, such as setting PATHEXT properly, and a nice HTML > Windows help file (chm) and we'd have a nice slick package. I'm not going to discourage anyone from learning about installers, but let me just warn you that it's a lot of work to make a nice installer. Tim already spends a lot of time on installers that I for one would rather see him spend on things that the rest of us can't do =). ActivePython's new installer does 'feature selection', so you can choose to install all, some or none of Mark's code; it also does the PATHEXT tweaks, we have an integrated CHM file which includes a lot of extra docs (the what's new, the HOWTOs, etc.). The feature of supporting 'file drops' is one we should definitely look at adding. It's very mac-ish (that's a compliment! =). --david ascher From aahz at panix.com Sun Mar 10 21:49:45 2002 From: aahz at panix.com (Aahz Maruch) Date: 10 Mar 2002 18:49:45 -0800 Subject: How "expensive" are Exceptions? References: <3c8bf3ef@nntp.server.uni-frankfurt.de> <3C8C01D2.F9CC7C73@engcorp.com> Message-ID: In article <3C8C01D2.F9CC7C73 at engcorp.com>, Peter Hansen wrote: > >Short answer: exceptions are not expensive. And now it's a FAQ: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.104.htp -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From kragen at pobox.com Wed Mar 20 18:56:05 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 20 Mar 2002 18:56:05 -0500 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C985678.8010200@pobox.com> Message-ID: <83vgbqdca2.fsf@panacea.canonical.org> Ahmed Moustafa writes: > For example, where I work, we have JRE for OS/390 (by IBM). Is there > a mainframe interpreter for Python? Or, will Jython do? Jython should do, although I have no experience with it. I've run the standard Python interpreter on a 390 (actually a zSeries), but it was running Linux under VM. Isn't OS/390 POSIX-compatible these days? If so, Python shouldn't be hard to get built on it. I'd be happy to do it for you. From bokr at oz.net Sat Mar 16 23:23:24 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Mar 2002 04:23:24 GMT Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: On Sat, 16 Mar 2002 09:50:32 +1100, Tim Churches wrote: [...] > >I concur with Bengt's suggested approach, plus you might want to use >something like the Porter Stemmer algorithm to convert words to their >"base" forms eg stepped -> step > >See http://www.tartarus.org/~martin/PorterStemmer/python.txt for a >Python implementation. > Any idea on the license status of that? I saw nothing mentioned in the text itself except and apparent reference to a book. E.g., if I rewrote it to my taste, could I put the result under PSF if I wanted to? Regards, Bengt Richter From bokr at oz.net Tue Mar 26 17:47:44 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Mar 2002 22:47:44 GMT Subject: Deeply embedded Python still alive? References: Message-ID: On Tue, 26 Mar 2002 17:10:10 GMT, grante at visi.com (Grant Edwards) wrote: >The link I have for the Deeply Embedded Python port > has been broken for >several months now. Anybody know what happened to that >project? > >-- >Grant Edwards grante Yow! I wish I was a > at sex-starved manicurist > visi.com found dead in the Bronx!! If the author lurks, he may volunteer something? If he doesn't, keep chopping the tail of the url 'til you get contact info? If you find something, I'd be interested too. How does it compare to Pippy (linked on python.org home page)? Regards, Bengt Richter BTW, your sigbot may be calling for help ;-) From tim.one at comcast.net Thu Mar 14 01:37:12 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 14 Mar 2002 01:37:12 -0500 Subject: Question about scientific calculations in Python In-Reply-To: Message-ID: The Source Code is Your Friend. listobject.c-ly y'rs - tim From amuys at shortech.com.au Mon Mar 25 00:51:13 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 24 Mar 2002 21:51:13 -0800 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> Message-ID: <7934d084.0203242151.7c45c16b@posting.google.com> Boudewijn Rempt wrote in message news:<3c9e2692$0$24819$e4fe514c at dreader3.news.xs4all.nl>... > Peter Hansen wrote: > > > holger at trillke.net wrote: > >> > >> > >how could you stop a running threading.Thread from the *outside*? of > >> > >course i could introduce some kind of flag into the event loop of the > >> > >Thread.run-method, but i really would prefer to have a non-instrusive > >> > >way for several reasons. > >> > > > >> > >Any way to do this? > >> > > >> > Not really. Why do you want to do it? > >> > >> You really want to know it? I am currently working > >> on (coded) agents which move through the network. > > > > "The network"? Which one? The Internet, or an internal > > network over which you have full control? Who controls > > the servers on which these agents will be running? > > > >> But of course i'd sometimes like to shut down some or > >> all agent-threads. > > > > Run them in a separate process and kill the process when > > it's "sometime"? If you can live without individual > > control. Maybe you can identify groups of them? > > > > Actually, Holger's problem is very well known to people > implementing agents. Agents run within the application, but > they don't share objects (not often, anyway), so killing them > is safe. But neither in Java nor in Python you can easily kill > them. This is precisely because your assumption that you can "know" threads don't share objects is an implementation issue. One critical problem is the issue of MT-safe libraries. In both Java and Python threads will routinely hold implicit shared locks on shared libraries. Which functions in which libraries involve implicit locks is naturally implementation dependent, often including malloc/free and friends. As a result there is no platform independant (and often no platform dependant) way of knowing the precise coupling between two threads. Hence no way of implementing a safe async-kill function. Note that similar problems exist with processes when they use shared synchronisation. Consider the common need to clean up flock/.pid files after SIGKILL'ing unix daemons. The crucial difference is that the higher granuality, and the increased isolation (ie. limited damage domain) of processes allows for safe clean-up of any resulting mess. With the higher coupling of a shared-address space implied by threads, cleaning up the damage caused by async-kill becomes non-trivial. Andrae Muys From dsavitsk at e-coli.net Mon Mar 18 15:12:44 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 18 Mar 2002 15:12:44 -0500 Subject: 2.1.2 install problems on win2k server References: Message-ID: going back to as212 seems to have corrected these problems. any ideas whay that would have happened? "dsavitsk" wrote in message news:Eyrl8.581$Mx3.132235 at news1.iquest.net... > I uninstalled activepython 212 and installed python 2.1.2 and win32all 145 > on Windows 2000 Server. There are 2 (maybe 3) problems. > > 1. active server pages won't work, but if i change the source code (even > just adding a space somewhere) then the page will work once. it won't work > again until i change the source again. > > 2. Typing python from a command prompt does not start python. Double > clicking icons works fine, however. > > 3. Pythonwin loads now, but for a while (until a reboot) gave DDE errors > when it was started. > > any ideas? > > thanks, > > doug > > From sumner-nntp5 at forceovermass.com Sun Mar 24 13:00:00 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Sun, 24 Mar 2002 18:00:00 GMT Subject: Stopping threads from the outside References: Message-ID: In article , holger at trillke.net wrote: >> >how could you stop a running threading.Thread from the *outside*? [SNIP] > Is the questions actually strange in any way? Like something > you wouldn't usually like to do? Yeah, killing a thread that's in unknown state can create all kinds of problems (was it holding locks? Is data it was accessing in a consistent state? etc...). It's pretty widely regarded as a Bad Idea. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From logiplexsoftware at earthlink.net Tue Mar 19 12:51:51 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 19 Mar 2002 09:51:51 -0800 Subject: [wxPython 2.3.1] what's going on? In-Reply-To: References: Message-ID: <20020319095151.77be1beb.logiplexsoftware@earthlink.net> On Tue, 19 Mar 2002 11:03:26 -0500 Tim Peters wrote: > [Pawel Oleksik] > > Playing with wxPython modules I've found something -- perhaps bug. > > Importing from wxPython.wx changes the calculation rules. > > Here is an example (strictly based on the random.py self-verification): > for more clues; it may or may not be a GTK bug, and the most frequently > suggested cure (I haven't tried it) is to do > import locale > locale.setlocale(locale.LC_ALL, "") > > after importing stuff from wxPython.wx. This is done automatically in wxPython 2.3.2. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From sumner-nntp5 at forceovermass.com Sun Mar 10 12:04:57 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Sun, 10 Mar 2002 17:04:57 GMT Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: In article <3C8AD9B6.5CEE7588 at engcorp.com>, Peter Hansen wrote: > I agree with much of what you say, especially the "consider skipping > C++ and just learn C part", but _what_ pragmatic point of view is it > that has one learning Perl, Java, or C++ when one uses Python already? > Not dissing those languages, but when would you really need them? > Or were you thinking strictly from the "job market pragmatism" POV? I was thinking of overall "coping with code you have to deal with in the real world" pragmatism, which is good for the job market not just from the "add to my resume" standpoint but also the "now I have to fix/alter this 50,000 line java/perl/C++ system" POV. Though it's often quicker to rewrite those in 5,000 lines of Python <.5 wink>. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From dalke at dalkescientific.com Thu Mar 14 14:32:16 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 14 Mar 2002 12:32:16 -0700 Subject: Question about scientific calculations in Python References: Message-ID: [Bengt Richter (maybe)] [Nope (that was me)] > If your lists are really long (O(100,000) or more?) then you might find > that the append starts taking too long -- append is asymptotically > O(n**n) [Here's Bengt Richter's response (at least, it wasn't mine)] > whoa! can that be true? [timbot (perhaps)] > No, theoretical worst case is O(n**2). (1 + 2 + 3 + ... + n == ?) [Andrew Dalke (certainly)] > Yes, it's true. Oops! I didn't notice the n**n -- I either read it as n*n or n**2, so didn't catch the error in my proofing. [timbot (again)] > but over-allocation is always proportional to list size now. [Me (who might be Andrew)] > Best I think would be a standard module of data structures (priority > queue, doubly-linked lists, stack, etc.) But it hasn't bothered > me enough to go ahead and do it. [PSU member #2 again ... if there was a PSU, which there isn't. (Who is #1? You are #6 :)] > Guido doesn't go for this kind of thing: the more "advanced" the data > structure, the more specialized variants it sprouts, and there aren't enough > volunteers to maintain the ever-bulging code across all the platforms Python > runs on. I was thinking of standard more like mxStack or kjbuckets. Something which wasn't a standard part of the distribution but was the standard answer to questions about data structures. Andrew (who might still be Andrew) dalke at dalkescientific.com From skip at pobox.com Sat Mar 23 00:10:59 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 22 Mar 2002 23:10:59 -0600 Subject: Packaging tool In-Reply-To: <20020323011656.67443.qmail@web10502.mail.yahoo.com> References: <20020323011656.67443.qmail@web10502.mail.yahoo.com> Message-ID: <15516.3683.885894.797572@12-248-41-177.client.attbi.com> mohamed> By a packaging tool I do not mean a make utility. I have in mohamed> mind some thing like dpkg, the Debian package management mohamed> system. (but I would like to have it in python). Check out the catalog-sig at http://www.python.org/sigs/catalog-sig/ -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From edream at tds.net Sat Mar 9 10:54:28 2002 From: edream at tds.net (Edward K. Ream) Date: Sat, 09 Mar 2002 15:54:28 GMT Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> Message-ID: <3C8A3032.EC94F229@tds.net> I'd like to say a few more words about the proposed logger class. These will be my last words on this subject. No other Python Module does as little, in essence, as would the logger class. Indeed, the heart of the proposed logger class is: if self.isEnabledForLevel(level): self.put(aString) If the logger class used dynamic tracing, its essence would be: if self.tracePointMatchesDict(tracepoint): self.put(aString) A logger class should reflect the simplicity of the problem. Forget convenience methods: it is trivial to define them in any scenario. Forget control flow, levels, loggers and configuration: dynamic tracing suffices. Forget handlers, just provide a "put" method that can be overridden in subclasses. IMO, the present logging proposal is bad design because it solves an easy problem in a complex way, like using a sledge hammer to kill a fly when a fly swatter is readily at hand. Regardless of precedents, a logger class would clash with Python's usual elegance. If the logging class is going to exist, keep it simple and base it on dynamic tracing. For an example of a simple dynamic tracing function that is more useful than the proposed logging class, see the trace function and its allies init_trace and get_Sherlock_args in leoUtils.py: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/leo/leo/leoUtils.py Extensive comments precede the get_Sherlock_args routine, which BTW easily provides configuration. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From gbreed at cix.compulink.co.uk Fri Mar 8 06:44:56 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Fri, 8 Mar 2002 11:44:56 +0000 (UTC) Subject: Voss 1/f noise algo help References: <5e8bd451.0203080150.44a259ce@posting.google.com> Message-ID: kevin parks wrote: > Hi I have a couple of attempts below at the beginnings of a 1/f^2 > Noise generator. It is in a sort of heavily commented psuedo Python > (somewhat translated from PASCAL) You can see that there are some > areas where i am in way over my head. I may have introduced a mistake > or two as well. Anyone familiar with Voss's algorithym want to help > smooth out the rough edges here? It sure would be nice to be able to > generate pink noise values in Python (brownian noise would be good > too, I am trying to work something up on that too). I'm not familiar with this Voss algorithm, but I did write code to generate fractional noise in C++ a while back. It can be a lot simpler than what you're writing. Here's the important function, converted into pseudo-Python: def fractionalNoise(beta, nPoints) """return noise with frequency spectrum 1/f**beta or something""" randomGenerator = Gauss() # initialize in the frequency domain data = [] for i in range(nPoints): amplitude = ((i+1)**(-0.5*beta))*gauss() phase = 2*math.pi*rand() data.append((amplitude*math.cos(phase), amplidude*math.sin(phase))) return FFT(data) You need three magic functions: gauss() returns a random number according to a Gaussian distribution with a standard deviation of 1. random.gauss looks suspiciously relevant rand() is the usual random number between 0 and 1. Must be possible. FFT() is a fast fourier transform. There should be one in either Numeric or Scientific Python. I'm not sure exactly what the result means, but both real and complex parts sound like noise. I think the standard libary includes routines for writing .wav files. Happy hunting! Graham From gimbo at ftech.net Mon Mar 11 07:54:15 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 11 Mar 2002 12:54:15 +0000 Subject: Newbie Import two coloums of floating point data into python HOWTO In-Reply-To: <7eb201fc.0203110422.1e9c7dec@posting.google.com> References: <7eb201fc.0203110422.1e9c7dec@posting.google.com> Message-ID: <20020311125415.GB8670@andy.tynant.ftech.net> On Mon, Mar 11, 2002 at 04:22:48AM -0800, Andybee wrote: > Can some one tell me how to import two coloumns of data in a ascii > text file,into two arrays in python? I cant seem to work it out. The > data is genereated in matlab and I want to import it into python Let's say you data looks something like this: 1.0 5.0 2.0 10.2 3.1 13.4 etc. Then here's one answer... There are probably cleverer and more efficient ways of doing this, but this one's pretty easy to understand and so hopefully more suited to a newbie... :-) I'm also not _quite_ answering your question, because you asked how to get two seperate lists, one per column, whereas what this does is return a list of tuples (one tuple per data line), which is how _I'd_ do it. ;-) Easy to change to your way, anyway. def foobar(filename): # We'll return a single list, consisting of 2-element tuples, one # per line in the data file. results = [] # Open the input file and read the lines. Note that this reads # them all in before continuing, and so would be unsuitable for a # large file. Possible alternatives would involve using # readline() or xreadlines(), the investigation of which is left # as an exercise to the reader. :-) input = open(filename) lines = input.readlines() # Now iterate over the lines, populating the result for line in lines: if not line.strip(): # Skip blank line continue # Split the line up, convert the values to floats, add it to # the result set. (first, second) = line.split() row = (float(first), float(second)) results.append(row) return results BTW, if you haven't seen it yet, I'd heartily recommend that you work through the python tutorial at: http://www.python.org/doc/current/tut/tut.html This contains everything you'd need to answer your question/understand the above, and a whole lot more. HTH, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From peter at engcorp.com Sun Mar 10 22:55:01 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 22:55:01 -0500 Subject: How "expensive" are Exceptions? References: Message-ID: <3C8C2A95.C3C754AC@engcorp.com> Jason Orendorff wrote: > > How do you handle errors in > C? You check the return value of every function call. This > is what Python does, and it's how Python implements > exceptions, too. This is the major cost of exception-handling > in Python: checking every return value. (Good C++ compilers > cleverly avoid this cost; Python doesn't, alas.) Bad C programmers cleverly avoid this cost, too. :-) -Peter From philh at comuno.freeserve.co.uk Sat Mar 9 17:36:12 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 9 Mar 2002 22:36:12 +0000 Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> <3C8A3032.EC94F229@tds.net> Message-ID: On Sat, 09 Mar 2002 15:54:28 GMT, Edward K. Ream wrote: >I'd like to say a few more words about the proposed logger class. These >will be my last words on this subject. > >No other Python Module does as little, in essence, as would the logger >class. Indeed, the heart of the proposed logger class is: > > if self.isEnabledForLevel(level): > self.put(aString) > >If the logger class used dynamic tracing, its essence would be: > > if self.tracePointMatchesDict(tracepoint): > self.put(aString) > >A logger class should reflect the simplicity of the problem. I feel this way too. Logging is simple enough in concept that it is probably just as easy to implement it from scratch in one's own project as to use an API which, because it tries to pack lots of functionality in, is rather complex to learn. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From dale at riverhall.NOTHANKS.co.uk Mon Mar 18 10:48:32 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Mon, 18 Mar 2002 15:48:32 +0000 Subject: Relieved but disappointed: The Pariah thread References: Message-ID: <5l2c9usr5q536u9ki0vc38jlu6oud859sj@4ax.com> Tim Churches wrote: >While I was much relieved that Mark Hammond took my mischievous "Has >Mark Hammond attained pariah status yet?" post with the good humour for >which that noble, heterogenous breed of people known as Aussies are >justly renowned, I was a bit disappointed that no-one at all commented >on the pictorial reference which I gave to sum up my view of the >.NETification of Python: >http://www.sciam.com/2002/0102issue/010250100.html > Bad luck. This easily the most humourless, anal-retentive group I read. The most daring humour you are likely to get away with is a bit of clearly labelled sarcasm. Or, for a real belly laugh, string a bunch of words together with hyphens and add '-ly yours' on the end. I gave up ages ago. -- Dale Strickland-Clark Riverhall Systems Ltd From martin at v.loewis.de Thu Mar 14 16:53:10 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 14 Mar 2002 22:53:10 +0100 Subject: GC thread safe? References: Message-ID: Dieter Maurer writes: > Several Zope users face crashing Python 2.1.2 (SIGSEGV inside > the garbage collector). The problem only occurs when > the following conditions are true: > > * Zope runs in multi-threaded mode > > * the cyclic garbage collector is not deactivated > > Is the cyclic garbage collector known to be thread safe? The garbage collector runs while having the GIL, so it does not need to be thread-safe. The only exception is when the garbage is cleared; at this time, the collector holds an exclusive list of the garbage, clearing one object after another. In principle, this may invoke the garbage collector again (even from another thread). At that point, the collector manipulates a list it has exclusive access to. So yes, the cyclic garbage collector is thread-safe. Regards, Martin From aahz at panix.com Tue Mar 5 09:56:42 2002 From: aahz at panix.com (Aahz Maruch) Date: 5 Mar 2002 06:56:42 -0800 Subject: Status of PEP's? References: <3C844811.AEC974E3@cosc.canterbury.ac.nz> Message-ID: In article <3C844811.AEC974E3 at cosc.canterbury.ac.nz>, Greg Ewing wrote: > >To me, the __iter__ protocol is intended to be used when an object can >reasonably be thought of as a sequence. That's actually *being* a >sequence, not just "associated" with a sequence in some way. > >Using the __iter__ protocol in the way suggested by this PEP is abusing >it, in my opinion. Yes, particularly when I repeat myself and use this example: if i in 5: -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From compexams at directvinternet.com Tue Mar 5 02:26:24 2002 From: compexams at directvinternet.com (Computer Exams Info) Date: 5 Mar 2002 02:26:24 -0500 Subject: swap Message-ID: If you know you have some stuff very useful that I haven't, we can swap. There are my collected stuff: CIW (Certified Internet Webmaster) STUDY PACKAGE CIW Foundations (365pages, pdf, 4Mb) CIW Study Guides: Foundations, Internetworking, JavaScript, Perl, Security Professional, Server Admin, Website Design, E-commerce Designer, Application Developer. Exam Bible: 1D0-410 CIW Foundations (121 Questions and Answers) 1DO-420 CIW Site Designer (81 Questions and Answers) 1DO-425 E-Commerce Designer (80 Questions and Answers) 1DO-450 CIW Server Administrator (84 Questions and Answers) 1DO-460 Internetworking Professional (83 Questions and Answers) 1DO-470 Security Professional (50 Questions and Answers) Boson Selftest Software CIW e-Commerce Test #1, 2 CIW Foundations Test #1, 2, 3 Ciw Internetworking Professional Test #1 CIW Javascript Test #1 CIW Security Professional Test #1, 2 CIW Server Administrator Test #1 CIW Site Design Test #1, 2 Master CIW Administrator Test #1 compTIA A+ Network+ Server+ Certification Study Package Offer all the information that students and professinals need to prepare for the A+ Network+ Server+ Certification Exams. Published in 2001. ebooks(full version for each certification), worksheets, selftest sofware. Lab Exercises: There are 44lab exercises for you to master. Each lab begins with a set of objectives to be achieved throuh the procedure and a list of items required to carry out the procedure. Icons are employed throughout each procedure to describe its mature. Each procedure ends with a set of lab-specific questions designed to permit students to assess their understanding of the lab. Reference Shelf: These articles provide in-depth technical information about a perticular topic mentioned in the Training Guide. These are referred to in the margin notes in the book. Very esay to understanding with interactive video training. Microsoft Certification MCSD Training Materials New rider training guide: MCSD VB6 exams Cover 70-175, 70-176 (pdf,1245pages,13mb) MCSD Solution Architectures exams 70-100 (pdf,816pages,17mb) 70-015 Designing Implementing Distributed Applications with VC++6.0 real exam questions(a lot), bibles 70-175 Designing Implementing Distributed Applications with VB6.0 real exam questions(a lot), bibles, selftest software, MS Press training kit (.chm, 4mb) 70-016 Designing Implementing Desktop Applications with VC++6.0 real exam questions(a lot),bibles, MS Press training kit(.chm,9mb) 70-176 Designing Implementing Desktop Applications with VB6.0 real exam questions(a lot), bibles, selftest software, MS Press training kit (.chm, 3mb) 70-029 Implementing SQL7.0 real exam questions(a lot), bibles, selftest software, MS Press training kit (.chm, 5mb) 70-229 Design and Implementing SQL 2000 exam note, Microsoft Press training kit(4mb) 70-100 Analyzing Requirements Defining Solution Architectures real exam questions(a lot), bibles, selftest software, MS Press training kit (.chm, 5mb) Lab system(Windows 2000 Server + SQL 7.0 + Visual Studio .net) Microsoft Certification MCDBA Training Materials 70-028 Administering SQL7.0 easy cram bible, real exam questions(a lot), selftest software 70-029 Implementing SQL7.0 easy cram bible, real exam questions(a lot), selftest software 70-228 Administering SQL 2000 exam note, 70-229 Design and Implementing SQL 2000 exam note, Microsoft Press training kit(4mb) 70-215 Windows 2000 Server easy cram bible, real exam questions(a lot), Microsoft Press training kit (11mb) Sybex training guide(8mb), troytech, selftest software(a lot) 70-216 Windows 2000 Network Infrastructure easy cram bible, real exam questions(a lot), new riders training guide (608pages, pdf), Microsoft Press training kit(6mb), troytech, Sybex(13mb), selftest software(a lot) Lab system(Win2k + SQL7) Microsoft Certification Training Materials(MCSE) Cover Exam Number: 70-058, 70-059, 70-067, 70-068, 70-073, 70-210, 70-215, 70-216, 70-217, 70-219, 70-220, 70-221, 70-222, 70-227, 70-240. More than 500 simulated exam questions for each test. Official Training Books(more than 100): Cover Microsoft Curriculum, Microsoft Press, New Riders, Sybex, Troytech, Easy Cram Bible, Cool Cram Bible, and so on. a lot of Self-test software OCP Oracle 8i 9i DBA Study Package. 1. Training books(More than 100) Oracle official training materials, sybex study guide and so on. M06268-9 oracle8 backup recover, M06291-3 oracle8 database administration, M08944-6 introduction to oracle sql plsql, M09005-8, enterprise dba part 1A arch&admin, M09095-8 Enterprise dba part1B backup&recover, M09125-6 emterprise dba part 3 Network admin, M9213-6 enterprise dba part 2 performance tuning, M083567-8 oracle 8i new features for administrators Oracle SQL/PLSQL, 9i PLSQL, Database Administration, Backup and Recover, Application Server, Parallel Server, Enterprise DBA, Data Warehouseing Fundamentals, Financial Analyzer for Admin, XML Develop Applications, R11i Extend Oracle Application, Administrating Oracle 9i Application Server. 2. Self Test software: 1Z0-001, 1Z0-023, 1Z0-024, 1Z0-025, 1Z0-026. 3. Boson software: V4.18 for DBA 4. Oracle DBA Reference DBA Performance Tuning Experts Initialisation Parameter List Parallel Server Configuration Guide for UNIX Admin for SCO UNIX Oracle 8i Upgrade Guide Installation Guide for Sun Admin Guide for Sun Installation Guide for SCO UNIX Installation Guide for Red Hat Installation Guide for Linux Performance Tips on UNIX DBA Mentor Common UNIX Commands Teach yourself SQL Using Oracle 8 5. Oracle 8i Documentation Library ?Oracle8i Server and Data Warehousing, Release 8.1.6 ?Oracle8i Server Application Development ?Oracle8i Server Networking and Security, Release 8.1.6 ?SQL*Plus, Release 8.1.6 ?Oracle8i interMedia, Spatial, Time Series, and Visual Information Retrieval Options, Release 8.1.6 ?Oracle8i Java Developer's Documentation, Release 8.1.6 ?Oracle WebDB, Release 2.2 6. Oracle 8i 9i software OCP Application Developer Study Package. 1. Oracle official training materials Developer PL/SQL, Developer/2000 build forms I, Developer/2000 build forms II, Developer/2000 Build Reports 2. Self Test software: 1Z0-101, 1Z0-121, 1Z0-122, 1Z0-123 Citrix Certification Study Package CCA Training Sheet Citrix Metaframe1.8 Administrators Guide(169 pages pdf) Citrix Metaframe1.8 Installation Guide(211 pages pdf) Citrix Metaframe1.8 for 2000 Servers Administrators Guide(158 pages pdf) CCA Exam Questions and Answers(80) Citrix Metaframe1.8 software Novell Certification Training Materials (CNE NetWare 5) Complete coverage of six CNE exams Covers all the required core exmas: Networking Technologies(50-632), NDS Design and Implementation(50-634), Service and support(50-635), Netware 5 Administration(50-639), NetWare Advanced Administration(50-640), the intraNetWare: Integrating Windows NT elective(50-636) Includes more than 450 challenging practice exam questions. Self-test software CCNP(Cisco Certified Network Professional) bscn640-503 bcmsn640-504 bcran640-505 cit640-506 Exam Package Official Training Book: 2 brands of each exam Building Scalable Cisco Networks Building Cisco Multilayer Switched Networks Building Cisco Remote Access Networks Cisco Internetwork Troubleshooting Exam Questions: More than 500 questions for each exam (Practical Exam Questions and Answers, Actual Exam Questions from examinees.) Self-test software Software Router Simulator Cisco Certified Network Associate (CCNA) Exams Package Training books: CCNA2.0 Prep Kit 640-507 Routing and Switching CCNA2.0 Study Guide Cisco Router EasyCCNA Exam Bible Network Associate STUDYME Exam Questions: True exam questions deriving from examinees and Practical Exam Bibles (more than 30 sheets) Self-test software Interactive Router-Simulated Training CCIE Written Exam 350-001 Package Network Design and Case Studies with the three types of networks (campus, wide area, and remote connections), researching Asynchronous Transfer Mode (ATM), Internet Protocol (IP), and Switched LAN, and the equipment and protocols best suited for those situations.such as Routing Information Protocol (RIP) and Open Shortest Path First (OSPF) redistribution, reducing Service Advertising Protocol (SAP) traffic in Novell Internetwork Packet Exchange (IPX) networks, and User Datagram Protocol (UDP) broadcast flooding--and propose configuration solutions to fix them. Cisco System Case Studies International Network Services CCIE Study Materials Exam Bible For CCIE Written Exam (ATM, DLSw, BGP, Appletalk, TokenRing) Seventyone labs study for CCIE Exam questions SHEETS: CCIE (350-001) Lotus Notes Domino R5 Certification Exam Guide Published at June 2001. Offer all the information that students and professinals need to prepare for the Notes Domino R5 Certification Exams. Selftest Software over 300 questions Very esay to understanding with interactive video training. Check Point Certification CCSA CCSE Check Point Certified Security Administrator - CCSA Training Book for CP2000(410pages, pdf, 7mb) VPN-1/FireWall-1 Management I - CP 2000 is an introductory course for Check Point's flagship product, VPN-1/FireWall-1. This course covers the basic steps involved in setting up an Internet firewall, and provides hands-on training to manage a FireWall-1 installation. Check Point Certified Security Expert - CCSE Training Book for CP2000(520pages, pdf, 7mb) VPN-1/FireWall-1 Management II - CP 2000 offers comprehensive training to implement and deploy VPN-1/FireWall-1 in an enterprise environment. In this course, you will acquire the skills necessary to set up a VPN and resolve complex security issues. Real Exam Questions(more than 600) Reference Cover CP2000&NG (more than 100) On Installation, Configuration, Management, Application, Solution, Case Tutor and Tips. Boson Selftest Software (Full version, not demo, retail price more than $300) CCSA test #1.2.3, CCSE test #1.2.3, CCAE test #1 Lab system of VPN-1/FirWall-1 4.1(CP2000) SUN Certification Study Package This auction cove all of the SUN mircosystems Certification, includes training books, bibles, Software Tutor, Selftest Software. For more information, please email me. SCJP(SUN Certified Java 2 Programmer) SCJD(SUN Certified Java 2 Developer) SCAJ (SUN Certified Enterprise Architect for J2EE) SCSA 7, 8, (SUN Certified Solaris Administrator) more than 100 Training Books - Java Programming Language, Java Programming Language Workshop, Solaris Network Administration, Solaris 2.6, 7, 8, Administration, Operating Enviroment Network Admin, Enterprise JavaBeans. Programming, Mastering Enterprise the Java. 2 Platform Enterprise Edition and so on. From mwh at python.net Wed Mar 6 10:58:21 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 6 Mar 2002 15:58:21 GMT Subject: Flushing stdout with raw_input - BUG References: Message-ID: Jonathan Gardner writes: > Michael Hudson scribbled with his keyboard: > > Jonathan Gardner writes: > > > >> I will write > >> another bug report about the unresponsiveness to bug reports as well, as > >> there are a lot of bugs that aren't even addressed at sourceforge. > > > > Oh, that will help, sure. > > It is a bug. There needs to be a fix for it. Do you need more volunteers? > How do we get involved? Where do we sign up? What needs to be done? Maybe > there needs to be more coordination and less coding at the top. Here I was just trying to point out the irony of a bug report saying "there are too many bug reports". > I did a semi-thorough investigation on the matter, and there really isn't > much information on how I make the move from being a python user to a > developer. Apparently it's by invitation only. Do I just keep submitting > bugs and patches and opinions and eventually someone will notice me More or less, yes. > or do I have a place where I can stand up and say, "HEY! I WANT TO > HELP! WHAT DO I DO?" I think you'll find shouting only annoys people. > > Please note that Python is a volunteer effort. You have no right to > > expect bug reports to be attended to. > > > > I can expect what I want. I have no right to see my expectations fulfilled, > unless I do the fulfilling. Yeah, whatever. > I understand that it is a volunteer effort. I am constantly appreciative of > the effort you and others are putting into it. > (http://sf.net/forum/forum.php?forum_id=154889) > > However, we can't go around saying Python is substandard because it is a > volunteer effort. We should be saying we are held to a higher standard > because we are a volunteer effort. Unlike Java or C#, we actually have to > perform, because we don't have a huge advertising fund and pushy > salespeople. > > > > > However, they are. I know *I* scan through open bugs fairly > > regularly. Martin von Loewis does the same. I can only fix the bugs > > I have time to fix, and so fix the bugs that seem to me to be worth > > fixing. I've spent multiple hours in just the past few days with my > > head stuck deep in the Python internals, and TBH posts like this do > > not make me think it was worth it. > > > > The way I was tutored was that getting a bug report was a *good* thing. A good bug report is a good thing. I don't know if you realised it, but your reports seemed to me to have a somewhat aggrieved, almost aggressive, tone. That is no help in a bug report. > Anybody who thinks there are no bugs or few bugs should be shot. A > programmer should appreciate a well-written bug report As Tim Peters once said, this editor doesn't go backwards :) > because it helps improve the code and lets him spend more time > coding and less time testing. > > I tried to be strikingly clear, because this has been brought up > before and it seemed to have been regarded as unimportant. I wanted > to emphasize that at least in my opinion it is important, and > shouldn't be shoveled off to the side. Fair enough. I think you may have gone unecessarily far in this direction. > And TBH, are you doing this for yourself or for us? If you are doing > it for us lusers who are unappreciative and consistently complaining > and calling features bugs, then I am surprised you are still around. I'm doing it to make Python a better product. > > If you are interacting with a subprocess that is expecting to talk to > > a user, you should probably be using pseudo-tty's. > > > > That is a very good answer that I didn't think of. I did a search on Google > and came up with the expect module for python located at > http://sourceforge.net/projects/expectpy/ > > Still, not quite what I was looking for, but since C seems to do exactly > what Python is doing, then maybe I need to help them at pyexpect and forget > about making Python behave differently from C. That way, there won't be > that nasty gotcha when they go and run a C program. I think I'll stop > complaining about raw_input and start working with the expectpy group. If you'd been a little more dispassionate in your first post (e.g. "I'm having this problem ... is it a bug that python does it this way? ... is there a better way?") you might have got this answer without me spending way too long thinking about the philosophies of open source delevopment. Or maybe you'd have got that anyway -- I seem to be unusually cranky today :) pseudo-terminals aren't the easiest things in the world to use. Just caring about linux probably makes life easier. If you have problems, I'm sure help can be found here... Cheers, M. -- ZAPHOD: You know what I'm thinking? FORD: No. ZAPHOD: Neither do I. Frightening isn't it? -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From aahz at pythoncraft.com Wed Mar 27 15:29:47 2002 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2002 15:29:47 -0500 Subject: Linux-related help References: Message-ID: In article , Susan Williams wrote: > >We are attempting to port from Solaris to Linux, and I'm having some >unpleasant malloc/free problems at exit (sys.exit). We have running >software based currently on 1.5.2. We're compiling on Linux with gcc >3.0.3 (on Solaris we were using Sun's compiler, not gcc, I think). > >Unfortunately I have a 3rd party module I'm linking with python that >is rather ancient. We first got it when using python 1.3, we "ported" >it to 1.5.2, and I can't quite pin down whether it is the root of the >problem or not, perhaps it is doing something not quite kosher. (The >idea of trying to get it running with 2.1 gives me the willies, but >that is not really today's issue.) > >Anyone out there using Linux especially with 1.5.2 is this ringing any >bells? On exit, python is clearing the list of modules, each module >is clearing dictionary entries by setting them to None, and it is the >decref that is blowing up. It is not always in the same place, but it >is always in the code that is setting a dictionary value to None and >deleting whatever was there before. Ooooo, yuck. My memory says that changing the way modules get unloaded is one of the big changes post-1.5.2. I have little actual experience with extensions; hopefully somebody who does will respond, but consider this a suggestion to start looking into upgrading. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From donn at u.washington.edu Wed Mar 13 15:54:06 2002 From: donn at u.washington.edu (Donn Cave) Date: 13 Mar 2002 20:54:06 GMT Subject: Another socket/thread question References: Message-ID: Quoth Cliff Wells : | On Wed, 13 Mar 2002 10:37:29 -0800 | Ken wrote: |> I've got a thread that continously listens to a socket, and reports what it |> receives. Blocking is turned on, and I would like it to stay that way since |> the only thing the thread has to do, is listen to the socket. |> |> My question is when the socket needs to be closed (program shuts down, or |> that user is being disconnected by the server) is it possible to interupt a |> socket.recv ()? |> |> If not, whats the easiest way to cut processor time from looping endlessly |> with blocking turned off? | | You might try using select() with a reasonable timeout period. Then you | won't busy loop, but you'll be able to check every few seconds to see if | some condition is set that would indicate a program exit. | | Alternatively, you could have your shutdown function send something to the | socket itself which would indicate to the thread that it should exit. Or | even some irrelevant data followed by a test on whether the thread should | exit (the data would never be processed so what it is would be unimportant | - it's used simply to cause socket.recv to return). Or a new socket or pipe could be assigned for this purpose, since the beauty of select is that it can monitor multiple descriptors. Donn Cave, donn at u.washington.edu From skip at pobox.com Thu Mar 28 09:32:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 28 Mar 2002 08:32:18 -0600 Subject: Very small zlib/svg problem In-Reply-To: <20020328153415.D11101@phd.pp.ru> References: <15522.19213.655102.927935@12-248-41-177.client.attbi.com> <20020328153415.D11101@phd.pp.ru> Message-ID: <15523.10610.795037.152703@12-248-41-177.client.attbi.com> >> f = gzip.open("c:/test.svgz", "w") Oleg> ^^ this suggests to use binary modes for binary files: Oleg> f = gzip.open("c:/test.svgz", "wb") Agreed. (I'm a Unix weenie, so this "b" stuff isn't second nature to me.) This occurred to me later. It seems to me that since all gzip files will be binary, the gzip module should transparently append a "b" to the mode if it's not given. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From emile at fenx.com Thu Mar 21 20:56:30 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 21 Mar 2002 17:56:30 -0800 Subject: Execute external program References: <3c9a7d0e_1@news.iprimus.com.au> Message-ID: "Jamie Carl" wrote in message news:3c9a7d0e_1 at news.iprimus.com.au... > Hopefully this is a simple question. How can I get python to execute an > external program such as 'bash' or whatever? > Is there a line of code that will do this. No interface with STDIO needed > so i can run blind. > C:\>python ActivePython 2.1, build 210 ActiveState) based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.system('dir') Volume in drive C is DISK2PART01 Volume Serial Number is 36C1-7E27 You should also look into spawn and pipe variants. HTH, -- Emile van Sebille emile at fenx.com --------- From widera at zeus.polsl.gliwice.pl Thu Mar 7 17:39:12 2002 From: widera at zeus.polsl.gliwice.pl (Adam Widera) Date: Thu, 7 Mar 2002 23:39:12 +0100 Subject: PyQT - Resizing the columns in QListViews Message-ID: I have the following problem: How to make the columns of QListViews to have the same size as the left panel and change their size automatically during the movement of the splitter in the exmaple below? THX 4 All hlp. Adam Widera PS: If the solution of this problem is too long or too obvious to be placed on this list just point me to a similar example on the net. import sys from qt import * class Test(QWidget): def __init__(self, parent=None, name='Test', f=0): QWidget.__init__(self, parent, name, f) def paintEvent(self, e): p = QPainter(self) p.setClipRect(e.rect()) class MainWindow(QMainWindow): def __init__(self, *args): apply(QMainWindow.__init__, (self,) + args) self.s1 = QSplitter(Qt.Horizontal, self, "split1") self.s2 = QSplitter(Qt.Vertical, self.s1, "split2") self.tree = QListView(self.s2) self.tree.addColumn("item") self.tree.setRootIsDecorated(1) self.items=[] self.items.append(QListViewItem(self.tree, "root")) self.items.append(QListViewItem(self.items[-1], "leaf")) self.items.append(QListViewItem(self.items[-2], "leaf")) self.tree2 = QListView(self.s2) self.tree2.addColumn("item") self.tree2.setRootIsDecorated(1) self.items2=[] self.items2.append(QListViewItem(self.tree2, "root")) self.items2.append(QListViewItem(self.items2[-1], "leaf")) self.items2.append(QListViewItem(self.items2[-2], "leaf")) self.t2 = Test(self.s1) self.t2.setBackgroundColor(Qt.white) self.s1.setOpaqueResize(1) self.s2.setOpaqueResize(1) self.setCentralWidget(self.s1) def main(args): app=QApplication(args) win=MainWindow() win.show() app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()")) app.exec_loop() if __name__=="__main__": main(sys.argv) From brian at sweetapp.com Thu Mar 14 14:57:52 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 14 Mar 2002 11:57:52 -0800 Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy In-Reply-To: Message-ID: <005801c1cb92$86c44d00$445d4540@Dell2> > - Magnus (who thinks that SimpleXMLRPCServer should be called > xmlrpclib.Server, with xmlrpclib.ServerProxy being used as the > server proxy... :) Placing the XML-RPC server implementation in the same module would be asymmetrical with other supported protocols e.g. BaseHTTPServer vs. httplib. Cheers, Brian From logiplexsoftware at earthlink.net Wed Mar 13 12:59:24 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 13 Mar 2002 09:59:24 -0800 Subject: Python on Windows soon forbidden by Micro$oft? In-Reply-To: <20020313170608.GB2611@lilith.hqd-internal> References: <20020313170608.GB2611@lilith.hqd-internal> Message-ID: <20020313095924.4600449a.logiplexsoftware@earthlink.net> On Wed, 13 Mar 2002 18:06:08 +0100 Gerhard H?ring wrote: > Le 13/03/02 ? 09:10, rasmussn at lanl.gov ?crivit: > > On Tuesday, March 12, 2002, at 02:54 PM, phil hunt wrote: > > As I was reading Microsoft's license, I thought of it in relation to > > the GPL. > > Maybe Microsoft is just covering it's backside so that users of their > > products won't use it in ways that will break the GPL. [...] > > I cannot imagine they'd waste a thought on wether their users break > other people's/companies licenses, because there's no way Microsoft > could get into trouble because of that. > > So that only leaves that they're spreading FUD intentionally. Not unlike the shouting at the end of their NT EULA's that warn against using Java for applications that involve risk of life and limb. Frankly I'd be far more concerned about using NT in those applications than whether the app were written in Java. Imagine being in a coma for a year and the hospital having to reboot your life-support once a week. That would take a lot of the fun out of it. As an aside, if I were on life-support, I'd rather have it run by a Gameboy than a Windows box. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From mnations at airmail.net Sat Mar 16 19:52:49 2002 From: mnations at airmail.net (Marc) Date: 16 Mar 2002 16:52:49 -0800 Subject: PIL Headaches: Advice Needed Message-ID: <4378fa6f.0203161652.7f28e23b@posting.google.com> I have gone thru all the tutorials and read me's I can find, and I still can't get PIL to work for me. At no point has it ever been able to recognize any file that I try to open in all formats (.bmp, .jpg, .gif, etc). I've imported the two DLL's into my main structure. I've imported all of the imaging .py files into the main Lib folder. The classes are being recognized and imported correctly. Has anyone else had similar problems? What am I doing wrong? Thanks, Marc From phil at river-bank.demon.co.uk Sat Mar 2 06:05:07 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sat, 02 Mar 2002 11:05:07 +0000 Subject: Black Adder and PyQt References: Message-ID: <3C80B1E3.575761B7@river-bank.demon.co.uk> Ron Stephens wrote: > > I am thinking of buying a "home" license of Black Adder, to use for > making GUI's for Python programs to be used on Linux+KDE and also > perhaps for the new Sharp Zaurus. Does anyone have any experience with > Black Adder that they can share? One of my main reasons for wanting > Black Adder is to use the GUI builder, so I am particualrly interested > in opinions about that aspect of Black Adder, but I am also interested > in other aspects as well. > > One question I have concerns licensing. If I buy the "home" version, > could I still share my programs as GPL'ed open source, or would that > require me to buy the "professional" license, which is much more > expensive? In other words, my programs would never be used in any > commercial way but I might want to post them as open source, free > software. The main difference in the licence between the "home" and "professional" version relate to the re-distribution rights of Qt. The "professional" version allows you to re-distribute the copy of the Qt supplied with BlackAdder with your application (but under no other circumstances), so you can ship a complete binary package to your customers for both Linux and Windows without incurring any further licensing fees from Trolltech. If you are only developing GPL'ed applications, and you are expecting users to already have Qt installed, then the "home" version is fine. Phil From newsfroups at jerf.org Tue Mar 5 18:43:44 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Tue, 05 Mar 2002 23:43:44 GMT Subject: Order of constructor/destructor invocation References: <3C8466F9.2080903@jerf.org> <_f7h8.5541$aP6.6480@rwcrnsc54> <3C851D41.3000902@jerf.org> <3C85446B.B389BB0F@spam.nada.kth.se> Message-ID: <3C855848.60302@jerf.org> Bj?rn Lindberg wrote: > and yes, all *standards* *conformant* compilers will follow this practice. Emphasis mine. That was my point. On an intuitive level, that's one of those "depend on it when you have no other options" kind of features. Even when the standard specs those sort of things, little tiny details often differ from implementation to implementation. I can't actually think of any in this exact instance, but that's often a sign that my creativity is lacking, not that there aren't details waiting to bite you if you depend over-much on implementation behavior. :-) From charles at a3a.com.br Mon Mar 18 14:38:25 2002 From: charles at a3a.com.br (Charles) Date: Mon, 18 Mar 2002 15:38:25 -0400 Subject: socket programming Message-ID: <02031815382500.31797@magneto> Anybody know where can i find a good (beginner) tutorial about Socket Programming using Python ? I was read the py-how.sourceforge.net tutorial but i think it is have a poor useful examples.. Charles From peter at engcorp.com Sun Mar 10 20:12:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 20:12:00 -0500 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> <3C8C02B3.674898B0@engcorp.com> Message-ID: <3C8C0460.993A4F81@engcorp.com> Peter Hansen wrote: > > phil hunt wrote re the infamous Mr. Rue: > > > > Is he still posting here? > > > > (I killfiled him some time ago). > > Not in any new threads. I use Netscape for news, and it's not > possible to killfile somebody without writing a f5g message > filter, so I killed the threads he was in and haven't heard a > peep since... Just posted to the TDD mailing list, coincidentally: http://www.math.ucr.edu/home/baez/crackpot.html Anyone care to calculate the total for our pet crackpot? :-) -Peter From akuchlin at ute.mems-exchange.org Wed Mar 20 10:33:33 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 20 Mar 2002 15:33:33 GMT Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> Message-ID: In article , Andy Gimblett wrote: > It's not pseudo-HTML, it's W3C compliant HTML (is " is part of the XML spec, and is intended for embedding processing instructions in XML. Quixote turns the idea of templating on its head and embeds HTML in Python code. Section 4 of http://www.amk.ca/python/writing/mx-architecture/ talks about why this turns out to be a really good idea. --amk (www.amk.ca) I'm as truthful, honest, and about as boring as they come. -- Mel, in "The Ultimate Foe" From usenet at thinkspot.net Sun Mar 17 14:36:32 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 11:36:32 -0800 Subject: Gumbie: a GUI Generator for Jython References: <3C94E29F.A48FE107@earthlink.net> Message-ID: On 17 Mar 2002 18:55:28 GMT, Gerhard H?ring wrote in comp.lang.python in article : > I've never heard of "easy gui", but what you probably mean is anygui. http://groups.google.com/groups?as_umsgid=b16e4ef7.0202131021.2b105a66%40posting.google.com -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From gh_pythonlist at gmx.de Thu Mar 14 11:38:29 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 14 Mar 2002 17:38:29 +0100 Subject: Using distutils for embedding -- was: Re: Newbie: Undefined reference when initializing Python In-Reply-To: References: Message-ID: <20020314163829.GA81596@lilith.hqd-internal> Le 14/03/02 ? 10:41, henrikb666 ?crivit: > --- In python-list at y..., Michael Hudson wrote: > > You need to link to Python; there should be a "-lpython" in there > > somewhere (and probably a "-L/some/path/or/other/" too). > The -l entry in the Makefile should point to the directory with > the libpython2.2.a file, right? There should be an -L entry pointing to the directory containing the libpython2.2.a file. And there should be a -lpython2.2 entry, too. -L points to the library directories. -lsomething means that this library should be linked against. > When the file is placed in /home/pos/Python-2.2, what should the > entry look like exactly, because I tried this without success > (yes, I know I am a Linux newbie!): Erh. Have you installed your Python 2.2 at all? I mean, did you make the "make install" step? This is necessary. This installs Python 2.2 at the place you told you specified with --prefix in the configure step. If you didn't specifiy any --prefix, it's installed into /usr/local by default. Out of interest, I've tried to hack a Makefile that uses distutils. It would be nice if I could get some feedback on it, as this or an improved version could possibly solve this problem once and for all. Here it is, playing tricks with distutils again (Python should point to the Python executable you want to use, like python, python2.1, python2.2, /usr/local/cvspython/bin/python or whatever): PYTHON=python PYFLAGS=`$(PYTHON) -c 'from distutils.sysconfig get_config_var; var = get_config_var; print " ".join([var("LIBS"), var("SYSLIBS"), var("LDFLAGS"), "-L"+var("LIBPL"), "-I"+var("INCLUDEPY"), "-lpython"+var("VERSION")])'` embed: embed.c $(CC) -o embed embed.c $(PYFLAGS) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 10.9 ?C Wind: 3.3 m/s From ark at research.att.com Mon Mar 11 00:49:02 2002 From: ark at research.att.com (Andrew Koenig) Date: Mon, 11 Mar 2002 05:49:02 GMT Subject: Translating Python to C (was Re: Modulo operator : differences between C and Python) References: <3C8BE537.74E55963@mega-nerd.com> Message-ID: jkraska> Programming in C++ genuinely depresses me. jkraska> And I'm an old veteran. I've been using it since the days of jkraska> C Front, if anyone around happens to know what that jkraska> means. :-) Unfortunately, there are lots of terrible C++ books out there. The standard library has opened up lots of new doors that most of the books simply ignore, which means that a lot of programmers don't even know that they exist. I don't want to start a C++ discussion on comp.lang.python, but I'll be glad to continue this discussion on comp.lang.c++ if you like. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From yajurveda at yahoo.com Fri Mar 1 19:56:20 2002 From: yajurveda at yahoo.com (MShyam) Date: 1 Mar 2002 16:56:20 -0800 Subject: Use of select.select Message-ID: <98a8b53e.0203011656.7aaad470@posting.google.com> Hi, Our product embeds python in C++ and in our py methods, we use select.select in several places. When purifying the executable, we find that when select.select(...) is executed, we find several BSWs, BSRs, IPWs and IPRs (beyond stack writes/reads, invalid pointer writes/reads). Has such a problem been reported? What's the fix? We're using python 1.5.2. Because of these memory errors, we find that eventually our processes dump core. Any assistance is appreciated! thanks, yajurveda at yahoo.com From rjones at ekit-inc.com Fri Mar 29 18:39:44 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sat, 30 Mar 2002 10:39:44 +1100 Subject: Anyone need a program written? In-Reply-To: <3ca47917.18551297@news.tudelft.nl> References: <3ca43ef4.3666136@news.tudelft.nl> <3ca47917.18551297@news.tudelft.nl> Message-ID: <200203292339.XAA17644@crown.off.ekorp.com> If you want a good place to start coding, the Catalog SIG can always use people with free programming time! Everyone says python needs a catalog like CPAN, but no-one seems to have the time to write (or finish writing) the thing. Mailing list: http://mail.python.org/mailman/listinfo/catalog-sig/ Archive: http://mail.python.org/pipermail/catalog-sig/ Recently there's been several efforts: Jason Petrone's package manager http://mail.python.org/pipermail/catalog-sig/2001-December/000211.html ciphon http://mail.python.org/pipermail/catalog-sig/2001-December/000212.html Gideon (Zope-based) http://mail.python.org/pipermail/catalog-sig/2002-February/000215.html Richard From aahz at pythoncraft.com Thu Mar 28 11:18:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 28 Mar 2002 11:18:13 -0500 Subject: Dealing with python version References: Message-ID: In article , Andrei Kulakov wrote: > >IOW, this should be automated. Hadn't anyone done this yet? Is there >some particular reason why this is hard to implement? I would say it's the opposite: it's so easy to do that nobody has bothered creating a generic solution. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From jeff at ccvcorp.com Tue Mar 26 18:02:11 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 15:02:11 -0800 Subject: wxPython and wxFlexGridSizer problem References: <3C9FBE22.A72B4A27@ccvcorp.com> <3CA0D05D.B42BF0E1@ccvcorp.com> Message-ID: <3CA0FDF3.15AA4D84@ccvcorp.com> Cliff Wells wrote: > On Tue, 26 Mar 2002 11:47:41 -0800 > Jeff Shannon wrote: > > > Cliff Wells wrote: > > > > > Also, I notice that your calls to gridSizer.Add are incorrect. The > second > > > argument is supposed to be a boolean flag .... > > > > Oooh, I missed that, the first time through. Actually, though, the > second > > argument isn't a boolean, though, it's an integer, which represents the > > weighting given to that item when expanded. ..... > > Is the meaning of this flag consistent across the different types of > sizers, or is this only for wxBoxSizer? AFAIK, it's consistent, though I have almost never used anything other than wxBoxSizers myself, so I don't want to claim anything I can't prove. ;) I would expect it to work the same in a wxFlexGridSizer, with the added condition that any column/row is the width/height of the largest element within it, and presumably the wxGridSizer would make every element the size of the largest one (since they all must be the same size). Jeff Shannon Technician/Programmer Credit International From irmen at NOSPAMREMOVETHISxs4all.nl Thu Mar 21 14:37:20 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 21 Mar 2002 20:37:20 +0100 Subject: [ANN] Pyro 2.5 available Message-ID: You can get the latest Pyro version (2.5) at http://pyro.sourceforge.net What's new: Install script fixes New URIs to make object lookup even simpler Problems with PYRO_STORAGE fixed Checksumming of network traffic configurable Documentation updates What is Pyro? Pyro is an acronym for PYthon Remote Objects. It is a basic Distributed Object Technology system written entirely in Python. It is extremely easy to implement a distributed system with Pyro, because all network communication code is abstracted and hidden from your application. You just get a remote Python object and invoke methods on the object on the other machine. Pyro offers you a Name Server, an Event Service, mobile objects, remote exceptions, dynamic proxies, remote attribute access, automatic reconnection, a detailed manual, and many examples to get you started right away. Irmen de Jong From philh at comuno.freeserve.co.uk Sat Mar 30 17:51:58 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 22:51:58 +0000 Subject: string copying References: Message-ID: On Fri, 29 Mar 2002 21:04:14 +0000, Robin Becker wrote: >Is there some special reason why python inhibits string copying. Efficiency. > I >suppose there's some attempt being made to make these constants. To make >differing versions of 'abc' one has to resort to silliness like 'ab'+'c' What benefit does that give you, apart from making your program run slower? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From siegfried.gonzi at kfunigraz.ac.at Mon Mar 4 04:23:37 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Mon, 04 Mar 2002 10:23:37 +0100 Subject: Python isn't necessarily slow Message-ID: <3C833D19.3A0EBD5A@kfunigraz.ac.at> Python isn't necessarily slow: When one scrambles through the dejanews-archive he unavoidably will get the impression that Python is a nice toy but hardly ever usable for real numerical computations; this is even supported by the silly language-shootout page. After my nightmare using Clean (if you are not a language-junkie and believe -- as I do -- programming should only be a side-effect in your life, then you should stay away from Clean: it is a useless big pile of shit! There were even the time, and I derided the Python programmer. Okay, Clean is very, very fast!), I decided for myself to use Common Lisp for my scientific work. Though, most of my colleagues are using IDL (and Fortran90/95 -- not Fortran77! -- for their numerical code). Common Lisp has many similarities with Clean, except that one gets really results in his life (Clean's array-type-system is an impudent scandal for its own), but there is one weak point: On this earth, there are only 2 serious implementations, which one wants to work with: Allegro Common Lisp and Lisp Works. Both are commercial ones and one of them is very, very expensive (prices beeing a secret, but there are rumors that an Allegro Common Lisp license is above USD 4000.-; and one would have to pay an extra fee for distributing, commercially, his programs). Okay, there is the free CMUCL out there for Unix; but they believe one wants to use Emacs for editing... Another problem with Lisp: there are nearly no libraries available for plotting (okay, gnuplot; but gnuplot is not a plotting library which one wants to make plots with; show your gnuplot graphics to your IDL-colleague). But thanks to F. Dubois (he did even a good job with his column in "Computing in Science and Engineering" in order to push Python; otherwise a great many of scientists hadn't hardly ever contemplated to take a look at Python) and especially Michels for contributing DISLIN to Python. I installed Python due to DISLIN and NumPy a few days ago. I think actually that NumPy in combination with DISLIN is a serious competitor to IDL or Matlab. DISLIN even lets you draw some simple maps. So, comp.lang.python is not the stage for life-stories. I have to deal a lot with files of the following scheme: 122.233,22.23,344.545,566.67,... 1.22,34.445,566.677,8.889,... ... I wrote some functions in Common Lisp in order to extract the values and read them in into an array. Normaly, Common Lisp is fast and I didn't have the requirement to speed it up. But the often strained "80% of C speed" is pure nonsense. Yes, you can reach it, but then you would wasting the rest of your life in order to declare types (and declaring types in Lisp is much different as lets say in C or Fortran). Hence: declaring types in Lisp is hardly ever a matter; even specialists (e.g. Guy Steele) will agree on them. After reading the Python tutorial I wrote a function in order to extract the floating-point values from a file. It is certainly not the same function as in Lisp, because in Lisp one can read in everything into an array: 1.223,NaN,2.333,233,444 NaN,2.334,3.445,1.223 My Python function sets a value (default -1.0) when it encounters "NaN". My Python function is using the NumPy library for the arrays. I am using only the arrays; but I have also red that some people complain that NumPy in combination with native Python loops is way too slow. But I cannot confirm this (see below). Sometimes I have to deal with large files: 8000 lines and 34 columns (about 2.5MB files). Reading this file into a Lisp array takes on my 1000MhZ Celeron Notebook with 256MB RAM under Windows XP: Allegro Common Lisp (demo version; it is free): 30sec Lisp Works (personal edition; it is free): 30sec [Compiler settings as fast as possible: (proclaim '(optimize (speed 3) (safety 1) (space 0) (debug 0)))] And to my surprise the Python function takes about 25 sec. A Clean version takes 13sec. [I am not sure how to use the profiler in Python; the profiler (sometimes the documentation is really weak in this respect) reports 70sec. This is clearly wrong.] I am not claiming here that Python is faster than Lisp (I am not sure how it had performed without the NumPy-library). But as I have written above: Declaring in Lisp would at least be impossible for me (okay, my Lisp experience is about 4 month only). But this has been a real (micro) life application (with the nice sugar that in Python I can extract some values from the array an pass it on to a DISLIN plotting library; whereas in Common Lisp I would have to save it to a file and consult e.g. Yorick). The Python code: (C) Siegfried Gonzi 2002 def readInFloats(file,nHeader=0, whatDel=',',NaN='NIL',NaN_NumPy=-1.0): f = open(file,'r') s = f.readlines() # cols = 1 + s[nHeader].count(whatDel) rows = len(s) ergArray = zeros((rows,cols), Float) count_rows = nHeader for x in range(nHeader,rows): start = 0 floatString = s[x] if not floatString.isspace(): count_rows = count_rows + 1 for y in range(cols): if y < (cols - 1): indx = floatString[start:].find(whatDel) dummy = floatString[start:(start+indx)] if dummy == NaN: ergArray[x,y] = NaN_NumPy else: ergArray[x,y] = float( dummy ) start = start + indx + 1 else: dummy = floatString[start:] if dummy == NaN: ergArray[x,y] = NaN_NumPy else: ergArray[x,y] = float( dummy ) print 'fertig' return ergArray[nHeader:count_rows,] [I have used an extra count_rows because often there is an extra line in a file without any datas (e.g. a blank line by accident)] Enclosed is also the Lisp and Clean code. Surely, my Lisp and Python code is not the perfect one. But you may not forget that my Python experience is a few days, whereas my Lisp experience is a few month. One can argue: the second time, even in a different language, it is always easier to implement the same. But this also holds true for Lisp, because I implemented the same in Clean last summer, before I even encountered Common Lisp. I wrote this all, because I have sometimes seen people in comp.lang.lisp which are saying that they come from Python and want to use Lisp because Python is very slow. Surely, a matrix-matrix multiplication of the dimension 1024x1024 in Common Lisp (only a simple code without any declarations) is about 5 to 10 times faster than a native Python code with native Python arrays (a Clean version is even about 100 times faster). This is a fact. But there is NumPy out there and most of the time a scientific data evaluation does not include array handling ala matrix-matrix multiplication. Often you steer through your data sequentially. And when one does declare (for speed) arrays in Lisp then he cannot use a mixed array (lets say strings and numbers)and this would be a same array as an NumPy array. This is important to know, because sometimes it is said that a NumPy library is a weakness, because Lisp has got all this native and is way faster. But this is only superficial the case. Personally, I do not know the Python community, but what I have seen so far is the fact that they are way more open-minded for the scientific programmer (try to find any numerical libraries for Lisp -- except statistics; or any plotting libraries). Most of the time the Lispers are busy to fall out with God and the rest of the world in order to show that a Lisp programmer is God's gift to the mankind. In Clean there is also the programming with whitespaces (except that more than one indentation at once is allowed); but I haven't had any problems with this and hence I think this will not impede my Python programming. There is one weak point with Lisp: you can only read/write 1 byte as binary. I am not sure, why nobody in the Lisp community is reading binary files. The native Python IDE should become improved (at least on Windows); compared to a commercial Lisp environment the IDE looks more or less like an amateur-programmer-project. It is stable (but not as I know it from Allegro Common Lisp), but the delay-time and behavior of the windows is nearly often unacceptable. Okay, the general feeling is like developing as with a Lisp editor; this is a fine thing (especially developing code at the command line). S. Gonzi Enclosed the Lisp and Clean version for the sake of completeness: == Common Lisp version: == ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Zaehle die Zeilen in einem File ;; ;; Funktion: (count-lines dateiFile :nHeader 0 :break-point "999") ;; Parameter: dateiFile...File mit den Daten ;; :nHeader...Anzahl der Kopfzeilen ;; :break-point...Soll an einer bestimmten Stelle abgebrochen werden? ;; ;; Ausgabe: Anzahl der Zeilen ;; ;; (C) Siegfried Gonzi 2002 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun count-lines (datei &key (nHeader 0) (break-point "999")) (let ((n 0) (next-line t)) (with-open-file (infile datei) (read-header-lines infile nHeader) (loop while(not (eq next-line nil)) do (setf next-line (read-line infile nil)) (if (equal next-line break-point) (setf next-line nil)) (setf n (+ n 1)))) n)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Ueberlese N Kopfzeilen in einem File ;; ;; Funktion: (read-header-lines dateiFile (nHeader 0)) ;; Parameter: dateiFile...File ;; nHeader (optional)...Anzahl der Kopfzeilen ;; ;; Ausgabe: Filepointer am Ende der Kopfzeile ;; ;; (C) Siegfried Gonzi 2001 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun read-header-lines (infile &optional (nHeader 0)) (loop :for i :from 0 :below nHeader :do (read-line infile nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Zaehle einen gewuenschten Character in einem String, und liefere ;; dessen Position: ;; ;; z.B.: 1.23,2.233,23.34,45.56 ;; ;; liefert eine Liste mit: (4 10 16) ;; ;; Funktion: (get-del-list numberString del) ;; Parameter: numberString...String welcher ausgewertet werden soll ;; del...Begrenzer (z.B. ",") ;; ;; Ausgabe: Liste mit den Positionen ;; ;; (C) Siegfried Gonzi 2002 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun get-del-list (numberString del) (let* ((n (length numberString)) (el 0) (el-list nil)) (loop :for i :from 0 :below n :do (setf el (aref numberString i)) (if (string= el del) (setf el-list (append el-list (list i))))) el-list)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Lese eine Datei,welche folgendes Format besitzt: ;; ;; Kopfzeile 1 ;; Kopfzeile 2 ;; Kopfzeile n ;; 12.23,23.34,1.234,34.456,2.345,56.67,... ;; 1.23,233.44,3.45,2.34,45.5677,6.778,... ;; ... ;; ;; Funktion: (read-in-array-del dateiFile :nHeader 0 :break-point "999" :del ",") ;; Parameter: dateiFile...Datei mit den Werten; Allegro CL Konvention: ;; z.B.: C:/Wissenschaft/R/D/.... ;; :nHeader...Anzahl der Kopfzeilen, die ?berlesen werden ;; :break-point...An welcher Stelle soll - ausser dem EOF - ;; abgebrochen werden ;; :del...Begrenzer (im obigen Beispiel ',') ;; Externe Funktionen: count-lines, read-header-lines, get-del-list, ;; ;; Ausgabe: Array, welches die Werte in Spalten und Zeilen enthaelt ;; ;; (C) Siegfried Gonzi 2002 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun read-in-array-del (datei &key (nHeader 0) (break-point "999") (del ",")) (let* ((rows (- (count-lines datei :nHeader nHeader :break-point break-point) 1)) (cols nil) (val nil) (next-line nil) (indx-list ()) (indx-start nil) (indx-end nil) (array nil)) (with-open-file (infile datei) (read-header-lines infile nHeader) (loop :for i :from 0 :below rows :do (setf next-line (read-line infile nil)) (setf indx-list (get-del-list next-line del)) (setf indx-list (append indx-list (list (length next-line)))) (if (< i 1) (progn (setf cols (length indx-list)) (setf array (append (make-array (list rows cols)))))) (setf indx-start 0) (setf indx-end -1) (loop :for j :from 0 :below cols :do (setf indx-start (+ indx-end 1)) (setf indx-end (- (nth j indx-list) 0)) (with-input-from-string (s next-line :index k :start indx-start :end indx-end) (setf val (read s))) (setf (aref array i j) val)))) array)) == End Common Lisp version == ====== Clean version: (C) Siegfried Gonzi 2001 ====== module convertSeasonD import StdEnv In11 :== "nij.txt" Nh :== 0 T :== ',' Sn :== "999\n" //Start:: !*World -> (!Real,!*World) Start world = accFiles( ACopyDatumTimeString_Season Nh T Sn In11 ) world ACopyDatumTimeString_Season:: !Int !Char !String !String !*Files -> (!Real,!*Files) ACopyDatumTimeString_Season nh char_d string_n inputfile file #! ( readok, infile,file ) = sfopen inputfile FReadText file | not readok = abort ( "Cannot read inputfile: " +++ inputfile ) // #! nLines = ( CountLines string_n infile ) #! ni = ( nLines - nh ) // #! infiler = ReadNLines nh infile #! ( string, infile_dummy ) = sfreadline infiler #! nj = ( length (CharPosInString 0 char_d string) ) + 1 #! array = MakeArray ni (nj+1) #! arrayread = ( AStringRead char_d array infiler ) //#! arrayread = {{arrayread.[x,y]\\x <- [0..(nj-1)]}\\y <- [0..(ni-1)]} // #! erg = arrayread.[7994,23] = (erg,file) AStringRead:: !Char !{#*{#Real}} !File -> {#*{#Real}} AStringRead char marray file = fill_up 0 marray file where fill_up:: !Int !{#*{#Real}} !File -> {#*{#Real}} fill_up n marray file | n == (size marray) = marray #! (string, file) = sfreadline file #! elem = (RealfromString (DStringtoString_List char string)) #! elemo = {x\\x<- elem} = fill_up (n+1) { marray & [n] = elemo } file RealfromString:: ![!String] -> ![!Real] RealfromString [] = [] RealfromString [x:r] #! el = toRealNaN( x ) = [el : RealfromString r ] where toRealNaN:: !String -> !Real toRealNaN str | str == "NIL" = -1.0 | str == "NaN" = 1.0 = toReal( str ) CharPosInString:: !Int !Char !String -> ![!Int] CharPosInString n char string=:{ [n] = nk } | n == (size string - 1) = [] = filter ((<>) 0) [ (if (nk == char) n 0) : CharPosInString (n + 1) char string ] ConvertStringtoString_List:: !Int !String ![!Int] -> ![!String] ConvertStringtoString_List n string list | n == (length list - 1) = [] #! start = list !! n #! stop = list !! (n+1) = [ ( toString(char_list (start+1) stop string) ) : ConvertStringtoString_List (n+1) string list ] where char_list:: !Int !Int !String -> ![!Char] char_list start stop string=:{ [start] = nk } | start == (stop ) = [] = [ nk : char_list (start+1) stop string ] DStringtoString_List:: !Char !String -> ![!String] DStringtoString_List char string = ConvertStringtoString_List 0 string pos_list where pos_list = [-1] ++ (CharPosInString 0 char string) ++ [size string - 1] CountLines:: !String !File -> !Int CountLines string_end file = ReadLines 0 file where ReadLines:: !Int !File -> !Int ReadLines nLines file | sfend file = nLines #! (line,filerest) = sfreadline file | line == string_end = nLines = ReadLines (nLines + 1) filerest ReadNLines:: !Int !File -> !File ReadNLines n file | n == 0 = file #! (line, file) = sfreadline file = ReadNLines (n - 1) file MakeArray:: !Int !Int -> {#*{#Real}} MakeArray ni nj | ni <=0 || nj <=0 = abort("Negative array index") = {{0.0\\x <- [0..(nj-1)]}\\y <- [0..(ni-1)]} == End Clean version == From djc at object-craft.com.au Sat Mar 23 07:36:33 2002 From: djc at object-craft.com.au (Dave Cole) Date: 23 Mar 2002 23:36:33 +1100 Subject: MySQLdb References: Message-ID: >>>>> "Michael" == Michael Hall writes: Michael> I've been writing PHP/MySQL for a couple of years now and am Michael> now cross-skilling into Perl and Python. I'm interested in Michael> web database integration for Python CGI scripts. There is a fairly simple database browsing sample in Albatross. Some of the inspiration for Albatross came from PHP so you could do worse than download it and take it for a spin. http://www.object-craft.com.au/projects/albatross/ Michael> Is this the right list for general questions about using the Michael> MySQLdb module? It depends. There is a database SIG mailing list which might be better for some questions. This document might explain some of your questions: http://python.sourceforge.net/peps/pep-0249.html The mailing list is here: http://mail.python.org/mailman/listinfo/db-sig - Dave -- http://www.object-craft.com.au From erno-news at erno.iki.fi Wed Mar 20 23:26:51 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 21 Mar 2002 06:26:51 +0200 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> <7xelifcsq3.fsf@ruckus.brouhaha.com> Message-ID: In article <7xelifcsq3.fsf at ruckus.brouhaha.com>, Paul Rubin writes: | Andy Gimblett writes: || It's not pseudo-HTML, it's W3C compliant HTML (is " which can be replaced by something else if | you want. It's making code look like HTML properties instead of | making it look like code. i think the idea is to not put code in the templates, and using xhtml + xml namespaces. it doesn't make it invalid xhtml, afaik. -- erno From idot at vt.edu Tue Mar 26 23:12:37 2002 From: idot at vt.edu (Carl Banks) Date: Wed, 27 Mar 2002 04:12:37 +0000 (UTC) Subject: list of empty lists References: <3CA11A5B.5000501@bioeng.ucsd.edu> Message-ID: Curtis Jensen , exactly what drugs were you under the influence of when you wrote: > Is there a easy way to make a list of an arbitray number of empty lists? > > I can do something like: > >>> some_number = 3 > >>> l = [[]] * some_number > >>> l > [[], [], []] > > Unfortunatly this has an unfortunate side affect. Whatever I do to one > of the list gets done to the other lists. ie: > >>> l[0].append(1) > >>> l > [[1], [1], [1]] > > > In this case, what I would like is three independantly empty lists. I > can make a for loop to loop "some_number" of times and append an empty > list at each itteration. Is there a simpler way? > Thanks. Python >= 2.0: l = [[] for i in xrange(0,10)] Any Python: l = map(lambda x:[],range(0,10)) from copy import copy l = map(copy,[[]]*10) -- CARL BANKS "I like nothing better than a good challenge. This is not one of them." From jimd at vega.starshine.org Wed Mar 6 14:11:23 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 6 Mar 2002 19:11:23 GMT Subject: select.select() on Regular Files? Message-ID: I'm trying to figure how to write a daemon that will efficiently wait for activity on any of several file and/or socket descriptors. Naturally I'm trying to use the select() function. Here's a skeleton script: #!/usr/bin/env python2.2 ## select on a regular file? ## JimD : Sat Mar 2 21:21:55 PST 2002 import select, time if __name__ == '__main__': import sys x=0 f = open(sys.argv[1], "rb") f.seek(-1,2) while 1: readfd = [f] line = "" r,w,e = select.select(readfd,[],[], 120) if r[0] is not None: line = r[0].read() print x, line, x += 1 Unfortunately it continually outputs. I don't understand why if there's no more data at the end of the file. Is my read() not pushing my file position all the way to the EOF? It's as though there's *always* data available on that file descriptor. This seems to contradict the documentation: >>> print select.select.__doc__ select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist) Wait until one or more file descriptors are ready for some kind of I/O. The first three arguments are lists of file descriptors to be waited for: ... *** IMPORTANT NOTICE *** On Windows, only sockets are supported; on Unix, all file descriptors. >>> Is this a bug? I'm using Python2.2 as packaged by Debian (unstable) on a Debian GNU/Linux system (what a surprise, a Debian package on a Debian system!) under 2.4.9 SMP kernel). Would poll() be a better choice? The __doc__ for that is a bit terse. >>> print select.poll.__doc__ Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events. >>> From gh_pythonlist at gmx.de Sun Mar 31 20:44:17 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 03:44:17 +0200 Subject: Python/Linux In-Reply-To: References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: <20020401014416.GC333@lilith.hqd-internal> * Robert Oschler [2002-03-31 19:55 -0500]: > Forgot to ask, is Zope's database server actually MySQL under the hood? ZOPE's ZODB (ZOPE Object Database) is, as the name says, an object database, and has nothing to do with a realational database like MySQL. AFAIK it uses ZODB for internal purposes (content-management stuff and others), but you can also use the ZODB in your custom-written methods, that you can in turn use from Zope DTML pages. I'd recommend to start with the ZOPE tutorial and examples on a live ZOPE installation if you want to get an impression of it. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.3 ?C Wind: 0.8 m/s From sumner-nntp5 at forceovermass.com Fri Mar 8 12:07:43 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Fri, 08 Mar 2002 17:07:43 GMT Subject: why is python slow? References: Message-ID: In article , Fernando Pereira wrote: > Another reason is that a JIT compiler may not help Python as much as Java, > because every Python object must have a type tag, and those tags must be > checked by every operation, while type-tag checks are only needed in a few > places in Java (eg casts), and never for primitive types. Because of type > tag checks, there would be no long, easily optimizable straightline > instruction sequences, which is one of the things what makes JITC worth it > for Java. The other thing is inlining, which would be rather hard to do > given Python's dynamic nature. A dynamic language like Python really wants a specializing compiler a la Psyco: http://psyco.sourceforge.net I understand they're now passing the python regression test suite and are planning a public alpha or beta soon. For some things the speed boost is phenomenal, for other things it's less impressive. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From martin at v.loewis.de Fri Mar 1 16:37:53 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 22:37:53 +0100 Subject: pickle, cPickle, zlib, and the future References: <79b2b0bb.0203011329.79469c5b@posting.google.com> Message-ID: xscottgjunk at yahoo.com (Scott Gilbert) writes: > I figure this was either planned or lucky. If it was planned, a quick > comment in the source would relax my fears that my code won't break in > the next version of Python. If it was lucky, it might be nice to jump > on the opportunity. I guess it was lucky. > So can I rely on the first character 'x' being reserved for zlib, and > cPickle/pickle strings never starting with 'x'? At the moment, no. If you can point to some zlib documentation that explains what the 'x' on each output does (*), feel free to submit a patch to the pickle implementations that documents (in a comment) that letter as being reserved for this purpose; it seems no harm is done doing so. Please submit that patch to sf.net/projects/python. Regards, Martin From pedronis at bluewin.ch Tue Mar 12 08:43:43 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Tue, 12 Mar 2002 14:43:43 +0100 Subject: Has Mark Hammond attained pariah status yet? References: Message-ID: <3c8e0911_1@news.bluewin.ch> Tim Churches wrote in message mailman.1015926440.9915.python-list at python.org... > So asks an article on Mark in the IT section of today's Sydney Morning > Herald - see > http://www.it.mycareer.com.au/news/2002/03/12/FFXMFP3LOYC.html > It's probably just the journalist's fault but I find the article frivolous and vague. What he is concretely working about? What he contretely want to work about? etc... There are many possible integration philosophies and technologies? and both aspects tech/philosophy are far from irrelevant. (The frozen Python.NET as a full fledged Python or limited and altered, a new attempt in that direction, bridging ...) Is he working in stealth-mode or it is just MS-kind PR ? What kind of Python technologies will the book treat? Just some academic questions. regards. From t.kloppenburg at billiton.de Wed Mar 27 09:55:04 2002 From: t.kloppenburg at billiton.de (Tjabo Kloppenburg) Date: Wed, 27 Mar 2002 15:55:04 +0100 Subject: Tkinter: Why won't it work? In-Reply-To: References: Message-ID: > self.button = Button(frame, text="QUIT", fg="red", > command=frame.quit) command=master.quit tk. From ron at ire.org Mon Mar 4 12:51:39 2002 From: ron at ire.org (ron nixon) Date: 4 Mar 2002 09:51:39 -0800 Subject: text manipulation examples Message-ID: <61ff32e3.0203040951.2408cef4@posting.google.com> I work with a lot of text files that come in different formats and sometimes resemble a jumbled mess. I've been learning python for the past few months and have been impressed with it. However, I'd like to see examples of string manipulation of text files, which are often lacking in the books I've gotten so far(if I'm wrong, please point me to the book.) Can anyone point me to examples or have examples I could take a look at. Ron From bmeerdnk at telekabel2.nl Tue Mar 26 11:08:18 2002 From: bmeerdnk at telekabel2.nl (Bart Meerdink) Date: 26 Mar 2002 08:08:18 -0800 Subject: Is it really so difficult to enable Tkinter? References: Message-ID: > No. You can skip the step where you edit Modules/Setup, since setup.py > should find the location of the headers itself. Everything else is as > intended; crossing the fingers is optional. Thanks, yes you are right. Pre-installing tcl-devel is enough. Same mechanism applies to (among others) expat and gdbm. And idle works if you save the Tools directory before removing the build tree. Still, maybe it could be easier. From python at rcn.com Sat Mar 2 02:45:21 2002 From: python at rcn.com (Raymond Hettinger) Date: Sat, 2 Mar 2002 02:45:21 -0500 Subject: string to dictionary References: Message-ID: "les ander" wrote in message news:a2972632.0203011522.16f1b8e0 at posting.google.com... > Hi, > i have a list of strings like this: > > aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3',...] > > i want to convert this to a dictionary with a_i -> b_i without > using loops (it is trivial to do it with loops) This ought to do it: >>> aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3'] >>> dict(map(lambda g: g.split() ,aList)) {'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'} If you don't have Python 2.2, then build the dictionary directly: >>> d = {} >>> map( lambda (k,v): d.__setitem__(k,v), map(string.split, aList) ) [None, None, None] >>> d {'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'} Note, the use of __setitem__ to avoid '='. Still, it's better to get Python 2.2 and avoid the second method. Good functional style stays away from lambdas with side-effects (setting the dictionary). > i tried this > > dict={} > map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList) > I recommend: 1. Never use an assignment inside a lambda expression 2. Never name a dictionary 'dict' which overrides the constructor 3. If lambdas get confusing, write a simple, working 'def' first and use that in the map. > but it complains that "keyword can't be an expression" > can someone please help me get this right? > thanks > les Good luck, Raymond Hettinger From brueckd at tbye.com Tue Mar 5 10:51:33 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 5 Mar 2002 07:51:33 -0800 (PST) Subject: Can Python do this? In-Reply-To: <3C84DC2A.6020400@bigfoot.de> Message-ID: On Tue, 5 Mar 2002, Gerhard H?ring wrote: > > Can you tell me little bit more why is this a bad idea to use exec/eval? > > Because they're > - unnecessary > - ugly > - unsafe And: - slow For example: s = 'bar' getattr(foo, s) is way faster than eval('foo.%s' % s) -Dave From akuchlin at ute.mems-exchange.org Wed Mar 6 14:36:08 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 06 Mar 2002 19:36:08 GMT Subject: Twain Scanners and some other questions References: <3C8672DB.28AD17B5@noaa.gov> Message-ID: In article <3C8672DB.28AD17B5 at noaa.gov>, Chris Barker wrote: > This looks like a good place to start looking: > http://www.twain.org/docs/twain_20_unix.htm Note that there's already a PIL module for the SANE scanner API (http://www.mostang.com/sane/). --amk (www.amk.ca) Our duty, if not our conscience, is clear. -- President Borusa, in "Arc of Infinity" From rsalz at zolera.com Fri Mar 1 11:19:55 2002 From: rsalz at zolera.com (Rich Salz) Date: 1 Mar 2002 08:19:55 -0800 Subject: importing C libraries, Solaris2.6, gcc2.95 :( Message-ID: <17214de2.0203010819.240c00d3@posting.google.com> I have a Solaris 2.6 machine, gcc 2.95.3 installed in /usr/local; /usr/local/bin is in my $PATH ; /usr/ccs/bin is not in my $PATH. I have python 2.1.1 sources; I did "./configure" with no flags. Attempting to import any library that includes a C shared library fails with the same backtrace: (gdb) bt 6 #0 0xef5a4674 in strlen () #1 0x64204 in PyString_FromString ( str=0xd26368
    ) at Objects/stringobject.c:89 #2 0x60da4 in PyDict_SetItemString (v=0xba68c, key=0xd26368
    , item=0xc3cf8) at Objects/dictobject.c:1403 #3 0x37278 in Py_InitModule4 (name=0xadf5c "", methods=0xeed36790, doc=0x0, passthrough=0x0, module_api_version=802040) at Python/modsupport.c:57 #4 0xeed25b5c in init_tkinter () at /export/home/jjb/Python-2.1.1/Modules/_tkinter.c:2113 #5 0x35088 in _PyImport_LoadDynamicModule (name=0xefffef80 "_tkinter", pathname=0xefffea90 "/usr/local/lib/python2.1/lib-dynload/_tkinter.so", fp=0xab7c8) at ./Python/importdl.c:52 What am I doing wrong in building? Replies to me will be summarized, thanks! From skip at pobox.com Wed Mar 6 12:25:55 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 11:25:55 -0600 Subject: PEP 284, Integer for-loops In-Reply-To: <6862777.1015405967@[192.168.1.100]> References: <15494.19711.723922.527327@beluga.mojam.com> <6862777.1015405967@[192.168.1.100]> Message-ID: <15494.20771.715902.111753@beluga.mojam.com> David> Also, target_list isn't right because the proposed for-loop David> syntax only allows looping over one integer at a time, not a David> tuple of integers. Yeah, sorry for the false alarm. In reviewing the Grammar file, it's not apparent there is a simple production that would restrict the grammar to scalars that can appear on the lhs of an assignment statement. Skip From hughett at mercur.uphs.upenn.edu Tue Mar 12 14:25:50 2002 From: hughett at mercur.uphs.upenn.edu (Paul Hughett) Date: 12 Mar 2002 19:25:50 GMT Subject: Question about scientific calculations in Python References: Message-ID: Martin Kaufmann wrote: : I'm trying to write a program to calculate diffraction patterns for : electron diffraction on clusters (100-10'000 atoms). So far I used : Python only for CGI programming and system tools (on a rather low : level...). Therefore I don't know whether it's reasonable to program : such a project in Python (I really like the language). Presently my : man concern is speed as the main function of the program is a nested : loop, the inner over several 1000 bins of a histogram and the outer : over several 1000 values of scattering factors. In the end I should be : able to simulate diffraction patterns and compare them to the : experimental data (i.e. run this function several times). You might want to take a look at bblimage, which is an extension to Python written in C; it emphasizes high performance, but the set of operations implemented so far is oriented toward medical image processing. It supports pretty much all the basic operations (+,-, ... sin, cos, exp, etc) on n-dimensional images in the usual integral and floating point types (but not complex, alas; I haven't starting playing with FFTs yet). The URL is http://www.uphs.upenn.edu/bbl/bblimage : Now my questions: Would it be best to : (a) write the whole program in C/C++ (I know only the basics of C but : it would be a good "excuse" to learn it...)? : (b) write the main program in Python but the heavy calculations in C : (I played today with scipy.weave -- the speed is much better but I : didn't really understand what I was doing...)? : (c) program it in Python and don't care about speed (or buy a new : workstation...)? It really depends on how many diffraction patterns you need to do. It doesn't make sense to spent two months learning C to save even 99% of a ten-hour computation that you're going to do only once. (Unless your real purpose is to learn C.) On the other hand. if you have to do a few hundred patterns, then it might be a good investment of time. For what it's worth, my own experience is that (b) using C for the heavy lifting and Python to glue the pieces together can be very effective if you implement the right piece in the right language. I'm using bblimage for registration and segmentation of hundreds of volume images at half an hour apiece. The current code runs almost as fast as plain C (about 4 times faster than a competing C++ implementation not particularly optimized for speed) but the Python code that glues it all together is easier to modify and experiment with than a C++ implementation would be. One general comment: The performance killer in many applications like this is doing the innermost loop in the interpreted language (Python, Matlab, etc). If you can recast your algorithm as operations on arrays rather than individual numbers, and your language does the implicit loops over the elements efficiently, you typically get 10x or so improvements in speed. Paul Hughett From brian at sweetapp.com Wed Mar 13 01:14:04 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 12 Mar 2002 22:14:04 -0800 Subject: Converting relative URLs to absolute In-Reply-To: Message-ID: <002401c1ca56$46c10e60$445d4540@Dell2> > Does anyone have any code that, given that absolute URL of a web page, can > convert all the relative URLs on that page to their absolute equivalent? To create the URLs, look at urljoin from the standard library. See: http://www.python.org/doc/current/lib/module-urlparse.html I'm less certain of the correct approach to doing the transforming of the web page. I'd probably just use a regular expression. Cheers, Brian From bokr at oz.net Sun Mar 10 16:55:37 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 21:55:37 GMT Subject: win32 extension: rare PythonService problem References: Message-ID: On 10 Mar 2002 14:50:59 GMT, Gordon McMillan wrote: >Zihong Lu wrote: > >> I use the win32 extension PythonService to write a windows service for >> our project. The service runs fine on most NT, win2k machines. >> Recently our customers reported that for some PCs, the command "python >> MyService.py start" returned as usual, no traceback, but the service >> did not start at all. > >I would suspect permissions. I had a similar experience when >moving a service from a test box to prod. Eventually the sys >admin created a new account and things started working. As a >lowly contractor I wasn't allowed to find out what he >actually did, though ;-(. > Permissions possibly, but I would also check environment, if that's used by the service program and/or python either on purpose or as a fallback looking for something. If you can conveniently create a test service that will write the environment _it_ sees as a running service to a file, or otherwise make it available to you, that might tell you something, though it would probably be obvious just from checking where the environment is defined. But I'd check the event logs (run "%SystemRoot%"\system32\eventvwr.exe) first for a clue, since that's easy. If there's a permission problem it may show up. If not, you could if necessary set up an audit of all accesses to your service program files and see them in the logs (both sucessful and failing accesses if you like). (At the same time, you can log who is playing solitaire on that machine ;-) Regards, Bengt Richter From mongiaamit at yahoo.com Fri Mar 22 11:47:56 2002 From: mongiaamit at yahoo.com (Amit Mongia) Date: Fri, 22 Mar 2002 08:47:56 -0800 (PST) Subject: PyQt installation problems on windows Message-ID: <20020322164756.46454.qmail@web11302.mail.yahoo.com> Hi, I have installed Python 2.2 , on my computer. I created a gui using Qt Designer and used pyuic to make a python file out of it. Now i want to run that file using the python interpreter. Whenever i try doing that it gives an error: Traceback (most recent call last): File "WrapperInterface.py", line 10, in ? from qt import * File "F:\PYTHON22\lib\qt.py", line 44, in ? import libqtc ImportError: DLL load failed: One of the library files needed to run this applic ation cannot be found. I even tried all the py and pyc file from PyQt/lib folder to Python22/lib folder and the same with the Dll files. but it still gives the same error. Can anyone offer a solution for this on windows. Regards, Amit Mongia __________________________________________________ Do You Yahoo!? Yahoo! Movies - coverage of the 74th Academy Awards? http://movies.yahoo.com/ From woodsplitter at rocketmail.com Thu Mar 28 18:32:44 2002 From: woodsplitter at rocketmail.com (David Rushby) Date: 28 Mar 2002 15:32:44 -0800 Subject: Sendkeys without Scripting Host References: Message-ID: <7876a8ea.0203281532.74d221c@posting.google.com> "Harald Schneider" wrote in message news:... > Hi, > > is there a possibility to use sendkeys() without scripting host installed? > Are there any > extentions available for python? > > Thanks for your answers! > Harald There's a small module by Paulo Soares that might work: http://mail.python.org/pipermail/python-list/1999-May/002986.html The module included in that post is a base64-encoded zip file that includes a .pyd for Python 1.5. I took the liberty of base64-decoding it, compiling it against Python 2.2, and posting it here: http://thor.prohosting.com/~drushby/files/simpscrp-for-python2.2.zip As for operating system support, here's what the included file PlayKeys.h says: """ SendInput is supported by NT4 SP3, Win2000, and Win98. PlayKeys checks if USER32.DLL exports SendInput before any other processing. If this code must run on an operating system that does not have SendKeys, you might be able to use the keybd_event. """ I distinctly recall using simpscrp on Windows 95, but I believe IE 5 was installed; the Scripting Host may have come with it. From les_ander at yahoo.com Fri Mar 15 18:06:50 2002 From: les_ander at yahoo.com (les ander) Date: 15 Mar 2002 15:06:50 -0800 Subject: multiline raw input Message-ID: Hi, i have a program that takes input from the command line however this input is multi-line and will have a lot of backslashes I tried using sys.stdin but it ignores the backslashes. i tried with raw_input but that only takes in the first line can some suggest a remedy? for example: i would like to run my program as follows: >> myprog.py Type in some input (type in '.' to end) : \sum_{i=1}^{n} \frac{\sqrt{2}}{\alpha} \infty \begin{itemize} \item this equation says that \end{itemize} . thanks From bergeston at yahoo.fr Tue Mar 12 08:41:37 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Tue, 12 Mar 2002 14:41:37 +0100 Subject: Rule Engine in Python References: Message-ID: Just as a simple suggestion (I never tried) : what about using one of the numerous Java implementation of such engines with Jython ? See for example : http://grunge.cs.tu-berlin.de/~tolk/vmlanguages.html#Logic HTH (and btw I am really interested to learn from working projects). B. "Lee Ingram" wrote in message news:eb612768.0203101940.5565b282 at posting.google.com... > I have used Google to scour the web looking for an implementation of a > rules engine using Python. I need a mechanism whereby slightly trained > end users will be able to add / modify business rules and have them > execute. I previously used Blaze Software's Advisor rules engine to do > something similar. Has anyone seen, implemented, or tossed out this > idea previously? > > Inquiring minds want to know... > > TIA > > Lee Ingram From SBrunning at trisystems.co.uk Wed Mar 13 09:26:56 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 13 Mar 2002 14:26:56 -0000 Subject: Has Mark Hammond attained pariah status yet? Message-ID: <31575A892FF6D1118F5800600846864DCBCDF9@intrepid> > From: Tim Churches [SMTP:tchur at optushome.com.au] > > I-know-you-were-joking-but-a--wouldn't-have-been-out-of-place-ly > y'rs, > > Hey, I was only quoting the (somewhat sensationalist) headline from the > newspaper story... Fair enough. You have to remember, though, that not everyone's sense of humour is so subtle. I happen to know, for example, that Steve Holden comes from Yorkshire. And there may be one or two Americans on the list, too. Let's-see-how-I-get-on-without-the--ly Y'rs, Simon Brunning simon at brunningonline.net ----------------------------------------------------------------------- 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 mwh at python.net Tue Mar 19 10:49:01 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Mar 2002 15:49:01 GMT Subject: Detecting corrupted .pyc files References: Message-ID: Michael Teo writes: > Does the python interpreter has some mechanism for checking whether the .pyc > files are corrupt before running it ? No. Corrupt marshal data *usually* won't unmarshal, but there are no real checks. Cheers, M. -- "Well, the old ones go Mmmmmbbbbzzzzttteeeeeep as they start up and the new ones go whupwhupwhupwhooopwhooooopwhooooooommmmmmmmmm." -- Graham Reed explains subway engines on asr From paul at boddie.net Thu Mar 7 13:34:29 2002 From: paul at boddie.net (Paul Boddie) Date: 7 Mar 2002 10:34:29 -0800 Subject: Web scripting with Python (My 2nd post!) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> <40c3f5da.0203070720.6ca52e4@posting.google.com> Message-ID: <23891c90.0203071034.795308e4@posting.google.com> inerte at hotmail.com (Julio Nobrega) wrote in message news:<40c3f5da.0203070720.6ca52e4 at posting.google.com>... > > So Andy, that's why I want to reinvent the wheel. First, I want to > learn Python. Second, I don't think there's a system with the > infrastructure I need/will develop. Balanced, I will start from > scratch. Writing a Web application framework is one of those things that looks easy enough at first - how hard can it be to do a CGI wrapper after all? The problem is, after experiencing the low cost of entry with Python, the tasks just get harder and consume more of your effort than the application you were wanting to write. How do you do user sessions properly? How do you authenticate users? Some frameworks already provide these kinds of facilities without dictating how your application is going to turn out. Starting out at a low level is exactly the kind of trap that too many projects fall into, producing a few 0.0.x releases before disappearing into the void. And that's just desktop applications - the added amusements of Web framework development include things like security, which one might think is easy to address, but it's usually far better to use trusted security techniques than think up schemes of your own. I'll accept that some frameworks have a perspective that can seem hard to share with the developers, and others are under fairly major and continuous development, but with all the existing Web frameworks out there, I'm starting to believe that we don't really need many more, let alone ones which might never approach getting finished. But don't let me stand in your way. ;-) Paul From narnett at mccmedia.com Mon Mar 25 09:40:01 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Mon, 25 Mar 2002 06:40:01 -0800 Subject: Debugging on windows via print statements -- reliable? In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of John Roth [snip] > Since you're running a console app, I'd suggest two > changes to your test setup. > > 1) Execute the program from the DOS prompt, not from > PythonWin. > 2) Redirect stdout to a file. > > The first suggestion is simply to eliminate one possible > variable - if switching to a raw command prompt changes > something, you've got more data, if it doesn't, you've > eliminated a possible candidate. Already tried both... In fact, that's how I've usually been testing. But thanks. Nick From maciej at maciejsobczak.com Mon Mar 18 16:39:49 2002 From: maciej at maciejsobczak.com (Maciej Sobczak) Date: Mon, 18 Mar 2002 22:39:49 +0100 Subject: socket programming References: Message-ID: Hi, "Charles" wrote in message news:mailman.1016480129.2465.python-list at python.org... > Anybody know where can i find a good (beginner) tutorial > about Socket Programming using Python ? If you are in this business, you can also find some contexts where the following library will be useful: http://www.maciejsobczak.com/prog/yami/ and particularly for Python: http://www.maciejsobczak.com/prog/yami/impl/index.html#python See the tutoral examples to find out if it's something useful for you. Cheers, -- Maciej Sobczak http://www.maciejsobczak.com/ From mats at laplaza.org Wed Mar 6 10:07:14 2002 From: mats at laplaza.org (Mats Wichmann) Date: Wed, 06 Mar 2002 15:07:14 GMT Subject: undefined symbols when linking Python into a shared library References: <3C8540B5.E133D407@freenet.de> Message-ID: <3c863019.155813297@news.laplaza.org> On Tue, 05 Mar 2002 23:03:33 +0100, Michael Neuroth wrote: :Hello to all python experts, : :I have a question about embedding Python in an application. :To be more precisely, I want to create a shared library which :holds the python interpreter and some other functions registered :at the Python interpreter (I used SWIG for that task). This :shared library (or DLL) will be loaded dynamically from an :application to support Python as script language. : :This way works well for Windows and (for simple scripts which :do not load other modules) also for Linux. : :Unfortunately I get an "undefined symbol" error when I try to :load other modules with the import statement on Linux. :When I try to laod Tkiter in a simple test script, I get this :error message on stderr from the embedded python interpreter: : : : : Traceback (most recent call last): : : File "", lind 2, in ? : : File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 35, in ? : : import _tkiter # If this fails your Python my not be configured for Tk : : ImportError: /usr/lib/python2.1/lib-dynload/_tkiter.so: undefined symbol: _Py_NoneStruct If this is a direct snip, and not a transcription, the problem is sa typo: _tkiter is used instead of _tkinter : How can I verify, that this symbols are in the shared library? Use objdump on the shared library Mats Wichmann From logiplexsoftware at earthlink.net Wed Mar 13 14:24:12 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 13 Mar 2002 11:24:12 -0800 Subject: Has Mark Hammond attained pariah status yet? In-Reply-To: <20020313185236.GB1227@lilith.hqd-internal> References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> <3C8F1D74.10802@mxm.dk> <20020313092857.4765dd0d.logiplexsoftware@earthlink.net> <20020313185236.GB1227@lilith.hqd-internal> Message-ID: <20020313112412.28c8e0af.logiplexsoftware@earthlink.net> On Wed, 13 Mar 2002 19:52:36 +0100 Gerhard H?ring wrote: > Apart from that, many people might fear that hacking the internals of a > COM implementation might make their head explode. Mine would. Come to think of it, having one's head explode might be preferable. lost-a-leg-just-trying-to-use-MS-Word-yesterday-ly yrs, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From grante at visi.com Sat Mar 9 23:31:27 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 04:31:27 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> Message-ID: In article <3C8ADDD3.E3ACC1EB at engcorp.com>, Peter Hansen wrote: > Grant Edwards wrote: >> I'm considering writing a wxWindows app for Win32. The only >> way I'm willing to do this is by doing all of the development >> under Unix, and then grit my teeth while I package up the >> final product for Win32. > > Please tell us you are willing to bend a little and at least > *test* under Win32 before you deliver it. Evidence from the > Era of Java shows that nothing is write-once-run-anywhere... I'll test it a bit, though there are others who will probably do a lot more testing than I will. I've never found that the author of a program is very good at testing it. Write once, debug everywhere... >> Optimally, it would be a single "exe" file that doesn't >> require any installation procedure. > > That's too much to ask for even a native Windows app in most > cases these days. That's kind of sad, but I figured as much. The only real stand-alone Win32 app I've seen in a long while is puTTY. Are statically linked apps just not possible under Win32, or just not practical? >> If that's not possible, it would be permissible to use a >> typical "isntall-wizard" type installation ... > > Great, you have several options available. > >> It looks like Gordon McMillan's installer might fit the bill. > > That's probably one. I haven't used it. > >> Anybody care to share any experiences distributing wxWindows >> apps for Win32? > > py2exe will do everything you need except the installer part > of the puzzle. But there are many installers available, > including freebie versions of some of the better ones. Actually, I used to have a licensed copy of one of those -- I think it was Wise. It got lost when our offices moved, but I'm sure one of the Windows guys has something similar. > Use py2exe and you'll get a directory with the Python DLL, the > wxPython DLL, your EXE, and a few other DLLs as needed (e.g. > the native regular expression stuff if you use it). I don't know diddly about DLLs, so pardon the ignorant question: Can my DLLs be put in a private directory where my EXE can find them? I'd rather not put anything in any public system directories. > Package and ship, easy as pie. (I've used PowerArc with > its option to package into a self-extracting ZIP as a > poor-man's version of an installer and it worked nicely.) Sounds like it might work. -- Grant Edwards grante Yow! Yow! Am I in at Milwaukee? visi.com From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Fri Mar 29 10:51:52 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 29 Mar 2002 16:51:52 +0100 Subject: Linux-related help References: Message-ID: <3ca48d90$1@news.mt.net.mk> > I'm having some unpleasant malloc/free problems at > exit (sys.exit). We have running software based > currently on 1.5.2. We're compiling on Linux with gcc > 3.0.3 (on Solaris we were using Sun's compiler, not > gcc, I think). > > Unfortunately I have a 3rd party module I'm linking with > python that is rather ancient. We first got it when using > python 1.3, we "ported" it to 1.5.2, and I can't quite If this module is some kind of binary, perhaps the problem is in the interaction between this module and gcc 3.0 or glibc. -- ?????? "One world, one web, one program" -- Microsoft promotional ad "Ein Volk, ein Reich, ein Fuehrer" -- Adolf Hitler From ullrich at math.okstate.edu Thu Mar 14 16:26:40 2002 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Thu, 14 Mar 2002 21:26:40 GMT Subject: Is Python an object based programming langauge? References: Message-ID: <3c911290.612430616@news> On Thu, 14 Mar 2002 11:40:57 +0100, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: >On 14 Mar 2002 01:55:03 GMT, bokr at oz.net (Bengt Richter) wrote: > >>Sorry, but that is not true of Delphi. Did you ever work Delphi from >>the command line? You can easily write console apps that do not use GUI windows: >>--- [...] > >>Well, please don't add to the confusion about Delphi's capabilities ;-) >>You could put someone off that might like it ;-) > >Well I like Delphi myself and I don't want to put anyone off! >However I just wanted to state that its very unnatural in Delphi to >write a console app. For example open the IDE and click > >file-new- > >and then try to click on something that starts a new console >application -). Console apps are not the only way to write Delphi programs that start, do something, then exit. I do it all the time, it's very very easy, and I'm not nearly smart enough to be able to figure out how to write a console app in Delphi: You simply edit the dpr file ("View Project Source") - remove _everything_ (there's not that much there to begin with) and in between the "begin" and "end" put whatever it is you want the program to do. (You can add references to other units...). It's the Application.This and Application.That in the dpr that sets up the message loop, etc - remove that and it's gone. For some sorts of things I like this _better_ than a console app - no GUI window, no console popping up either. (These programs tend to get associated with Folder in the registry; I right-click on a folder, select whatever and all the files in the folder are processed in some way - no muss.) >I do not want to criticize Delphi, I do want to state that object >oriented programming can be so tightly coupled to GUI style program >design that it can give the (false) impression that GUI style program >design and OOP are unavoidably connected. > >Anton. David C. Ullrich From slime at vsnl.net Fri Mar 22 08:06:53 2002 From: slime at vsnl.net (Prahlad Vaidyanathan) Date: Fri, 22 Mar 2002 18:36:53 +0530 Subject: How to set the Timestamp of a File In-Reply-To: <20020322113321.7e52dba1.joerg_schuetter@heraeus-infosystems.com> References: <20020322113321.7e52dba1.joerg_schuetter@heraeus-infosystems.com> Message-ID: <20020322130653.GA1356@marvin.localdomain> Hi, This is my first post to this list, so a "Hi!" to everyone here. On Fri, 22 Mar 2002 J?rg Sch?tter spewed into the ether: > Hi > > How can I set the timestamp of a file (especially under windows) with > python? In Unix/Linux there is a tool caled touch. > There is no problem to read the timestamp, but how can I set the > timestamp to a desired time? According to the 2.2 docs, os.utime() works. For example, here is a very simplistic touch : import os, time def touch (filename) : new_time = time.time() try : os.utime(filename, (new_time, new_time)) except OSError : # Create the file, if it doesn't exist fd = open(filename,'a') fd.close() if __name__ == "__main__" : touch(sys.argv[1]) HTH, pv. -- Prahlad Vaidyanathan I drink to make other people interesting. -- George Jean Nathan From wesc at deirdre.org Tue Mar 12 15:03:19 2002 From: wesc at deirdre.org (wesc at deirdre.org) Date: Tue, 12 Mar 2002 12:03:19 -0800 (PST) Subject: ANN: SV-SF Bay Area Python user grp (BayPIGgies) mtg 3/13 7:30pm Message-ID: <200203122003.MAA14260@alpha.ece.ucsb.edu> just a quick reminder about the BayPIGgies event tomorrow evening... hope to see some of you there! also, we are placing a call-for-talks for this monthly event. if you are working on a Python project and want to get the word out, or if you are a company producing products using Python and would like to share how Python has helped you "get it done," this is a great way to let everyone know. if you are interested in giving a such talk at one of our meetings, please contact me directly. thanks! -wesley When: March 13, 2002, 7:30-9pm Where: Stanford University, Palo Alto, CA Title: BioPython Jeffrey Chang (School of Medicine, Stanford University) founded the BioPython project in 1999 to promote the development of shared software infrastructure in bioinformatics. His talk will cover the architecture and capabilities of Biopython and also give a sneak preview of the upcoming version. Click on BayPIGgies link below for more info, including driving directions, past meetings, schedule, etc. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, ? 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://deirdre.org/baypiggies wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From geoff at gerrietts.net Tue Mar 26 23:26:14 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 26 Mar 2002 20:26:14 -0800 Subject: PyThreadState_DeleteCurrent() Message-ID: <20020327042600.GD10449@isis.gerrietts.net> I'm sure this should be obvious to anyone who understood the evolution of the problem PyThreadState_DeleteCurrent() was designed to call, but it unfortunately is not to me. I've been following the "invalid tstate" problem through history, trying to backport fixes into a 1.5.3 interpreter. The majority of the glitches that resulted went away with the fixes from 1.6. Now I've finally gotten some time and permission to move forward on porting us to a newer interpreter. Some of the extensions we use, though -- notably the ILU module -- is written to the older API. Now, we don't seem to be having invalid tstate problems any more, but I noticed, when I was tracking down the invalid tstate bug, that 2.1.2 included some additional fixes for tstate problems. The solution was to add new API -- PyThreadState_DeleteCurrent() split from PyThreadState_Delete(). But ... what's the difference? When is PyThreadState_DeleteCurrent() the appropriate call, and when PyThreadState_Delete()? I've looked, and the docs haven't been updated to reflect this API change. Thanks, --G. -- Geoff Gerrietts "Whenever people agree with me I always feel I must be wrong." --Oscar Wilde From grante at visi.com Mon Mar 11 10:28:05 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Mar 2002 15:28:05 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8C82D3.CA4220CA@earthlink.net> <3C8CAA83.9EBBC03E@engcorp.com> Message-ID: <924j8.19297$N7.4387774@ruti.visi.com> In article <3C8CAA83.9EBBC03E at engcorp.com>, Peter Hansen wrote: > Tim Hammerquist wrote: > >> Didn't you know? Microsoft invented Open Source! ;) > > No, that was Al Gore! Ya know, I've actually read the transcript of that interview. He never claimed to have invented the Internet, only to have been responsible for funding it. -- Grant Edwards grante Yow! Of course, you at UNDERSTAND about the PLAIDS visi.com in the SPIN CYCLE -- From SSchukat at dspace.de Mon Mar 4 11:50:54 2002 From: SSchukat at dspace.de (Stefan Schukat) Date: Mon, 4 Mar 2002 17:50:54 +0100 Subject: Win32 2.2 & 2.1.2 Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C13B0B8@PDC-DSPACE> Just change in the registry the file assoziations. Is this case you have "Edit", "Edit in 22", "open" (default), "open in 22" E.g. with the shown regfile (paths must be changed according to the installation) Stefan ---------------------------------------------------------------------------- - REGEDIT4 [HKEY_CLASSES_ROOT\Python.File\Shell] @="open" [HKEY_CLASSES_ROOT\Python.File\Shell\Edit in 22] [HKEY_CLASSES_ROOT\Python.File\Shell\Edit\Command] @="F:\\Python22\\lib\\site-packages\\Pythonwin\\pythonwin.exe /edit \"%1\"" [HKEY_CLASSES_ROOT\Python.File\Shell\Edit] [HKEY_CLASSES_ROOT\Python.File\Shell\Edit\Command] @="F:\\Python21\\PythonWin\\PythonWin.exe \"%L\"" [HKEY_CLASSES_ROOT\Python.File\Shell\open] [HKEY_CLASSES_ROOT\Python.File\Shell\open\command] @="F:\\Python21\\python.exe \"%1\" %*" [HKEY_CLASSES_ROOT\Python.File\Shell\open in 22] [HKEY_CLASSES_ROOT\Python.File\Shell\open in 22\Command] @="F:\\Python22\\python.exe \"%1\" %*" > -----Original Message----- > From: Robin Becker [mailto:robin at jessikat.fsnet.co.uk] > Sent: Monday, March 04, 2002 5:27 PM > To: python-list at python.org > Subject: Win32 2.2 & 2.1.2 > > > Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the > default for a win32 box. It would allow us to dip a toe in the water > without drowning. > -- > Robin Becker > -- > http://mail.python.org/mailman/listinfo/python-list > From metaliu at yahoo.com Fri Mar 1 16:47:57 2002 From: metaliu at yahoo.com (BL) Date: Fri, 1 Mar 2002 13:47:57 -0800 Subject: new images from strings using PIL Message-ID: New at python and PIL so bear with me: I'm having difficulties creating images from strings. Basically, I have a string of integers I would like to create an image from. I'm trying to use python's PIL function Image.fromstring() to do this (any other methods of doing this would be appreciated). So I do: pixels = "1 2 3 4 5 6" //test pixels im = Image.fromstring("I", (2,1), pixels) //create a 3x2 image from pixels I'm not actually sure how to read the pixel data in im. im.getdata() returns: Also, im.getextrema() returns: (540155953, 540287027) These values are obviously wrong. Why isn't my 3x2 image being created with the proper pixel intensities? Thanks in advance, Bill From deathtospam43423 at altavista.com Wed Mar 27 00:25:23 2002 From: deathtospam43423 at altavista.com (A.Newby) Date: 27 Mar 2002 05:25:23 GMT Subject: Tkinter: Why won't it work? Message-ID: Hi. Below is an example exercise from "An Introduction to Tkinter" by Fredrik Lundh. It simply creates a box with a quit button in it. Problem is, everytime I click Quit, the program freezes. Is this a rare but well known bug with Tkinter, Python 2.2, or Windows 98? Or is more probable that it's cuz my system is screwed? # File: hello2.py from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() -- cdewin at dingoblue.net.au From eddie at holyrood.ed.ac.uk Wed Mar 20 07:14:50 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Wed, 20 Mar 2002 12:14:50 +0000 (UTC) Subject: Telnetlib - Clearing/resetting within a Telnet Object References: <3C977D0C.B925E0EF@nc.rr.com> Message-ID: Mike Lammon writes: >I am writing a small server program to interact with an external >machine. (It is non-unix). The program connects fine. It >issues the commands and receives data fine (most of the time). >This is the problem. The machine I am connected too sends out >system messages, etc to users who are connected (telnet). I >can't turn off these system messages so that is not an option. >The next time I issue a command from the client side, It >will return the data but its not from the current command >issued. It returns the next serious of data in sequence. >I need a way to clear/reset (without destroying the telnet >session) , then issue the current command. You haven't given much context but if you can issue commands other than those to retrieve data AND the remote system only outputs systems messages when the user is inactive you could send comments and use the echo reply to synchronise. However if the remote system just spews random text to the screen then you could try making the remote system send multiple copies of the data until you get 2 identical results in a row (more if you want to be absolutely sure). Or you could install something on the remote system which your telnet program calls to run the commands and collect the output and then send the data back to you (either using the above method or out of band). Well those are some ideas. Eddie From evebill8 at hotmail.com Fri Mar 15 14:50:58 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Fri, 15 Mar 2002 19:50:58 GMT Subject: socket References: Message-ID: Yes, you're right! I asked my friend the same question because I was doing that for my previous company, but they don't want to send a mail to the users. Second, again, I want to understand more about how the SMTP protocol works for my TCP/IP class project. Thanks for yuor input! Billy Ng "Cliff Wells" wrote in message news:mailman.1016218106.2021.python-list at python.org... > On Fri, 15 Mar 2002 17:46:01 GMT > Billy Ng wrote: > > > Nothing evil here. I have 2 reasons why I would do this program. Firs, > it > > is my TCP/IP concept class's project. Basically, I want to try what the > > book tells in to code, but I notice it does not work the way it says in > so > > many commercial SMTP servers. Second, I have been unemployed for about 4 > > months. My friend's company needs a program to verify the users who > > registered to their service. They found out many registered users were > > using fake addresses. I just want to try this program to see if I will > get > > a job there. That's all! I really do appreciate if you would provide > any > > info for me to complete this project. > > Why not do like many others do: send a confirmation email to the address > and require a reply from that address to complete registration. > > -- > Cliff Wells, Software Engineer > Logiplex Corporation (www.logiplex.net) > (503) 978-6726 x308 (800) 735-0555 x308 > > From jimd at vega.starshine.org Sun Mar 31 07:36:11 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 31 Mar 2002 12:36:11 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <001d01c1d67f$2eb81090$445d4540@Dell2> Message-ID: In article , Emile van Sebille wrote: >"Charl P. Botha" wrote in message >news:slrnaa6uf4.d4j.cpbotha at crabtree.cpbotha.net... >> In article , >> David Ascher wrote: >>> Thanks for all the interest in ActivePython. We hope to not have >these >>> kinds of delays in the future. >> Just remember not to split your infinitives in the future. ;) > There is no longer consensus that splitting infinitives is wrong due to > the awkward constructs avoiding it often gives rise to. >Emile van Sebille There is also no longer a consensus that dangling prepositions are something up with which one should not put. The passive voice makes most of these statements longer and more awkward. Try: Avoiding split infinitives often makes for awkward constructs. or: Some argue that ... or even: There is growing dissent on whether the avoidance of split infinitives is worth the awkwardness that ensues. Depending on whether the emphasis was intended to be on the avoidance of split infinitives, or on the emerging controversy in some grammarian community. Notice that the last of my examples slipped back into the passive voice and grew much longer. The active voice is generally more concise. Verbiage is often in the passive voice. Use of the passive voice conveys a more detached tone and often brandishes an academic and objective veneer. In other words, it's used to sound intellectual. (BTW: I often find myself slipping into the passive voice, and I often have to back up and delete whole paragraphs to extricate my message from obscurity). From gcordova at hebmex.com Thu Mar 7 17:36:08 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 7 Mar 2002 16:36:08 -0600 Subject: PEP 284, Integer for-loops (code bash?) Message-ID: <19650FF08A99D511B19E00B0D0F06323060B53@SRM201002> > > On Thu, 07 Mar 2002 13:47:49 -0800, David Eppstein > wrote: > > But there are a few warts in the design, where instead of > > just using Python I have to stop and explain some unnatural > > unintuitive syntax. > > You keep using that word. I do not think it means what > you think it means. > > You killed my language, prepare to die! > > > Or, you could propose an excersize for your students, like: "Make a module which will create a helper object, to make prettier loop sequences." And propose a notation, like: >>> for ix in Ints[0, ...]: ... do_something(ix) will loop from zero onward, one by one; and: >>> for ix in Ints[0, 3, ...]: ... do_something(ix) will loop from zero onward, three-by-three; and: >>> for ix in Ints[0, ..., 10]: ... do_something(ix) will loop from zero up to (including) 10; and... >>> for ix in Ints[0, 3, ..., 10]: ... do_something(ix) will do the obvious. So, I propose an answer to this, and here it is. Just do a "from ints import Ints" at the beginning of the program. Have a nice evening :-) -gustavo -------------- next part -------------- A non-text attachment was scrubbed... Name: ints.py Type: application/octet-stream Size: 2521 bytes Desc: not available URL: From joonas at olen.to Sun Mar 10 17:39:03 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Mon, 11 Mar 2002 00:39:03 +0200 Subject: newbie needs help with tkinter References: <1Myi8.13667$%d1.409160@twister2.libero.it> Message-ID: <3C8BE087.3BDEA8E8@olen.to> Sacchi wrote: > > I've just learned the main rules of python(I already knew both java and > C). Now I'm trying to get something out of Tkinter, but while running > this sample program (made by myself) I encountered a problem. I wanted > that by clicking on the "configura" command under the "File" menu the > frame would get yellow and that a label would appear on it. The > function works(the line "print "hello!"" gets executed) but the gui > window doesn't change. I even tried to use the widget redraw methods > but with no success... anyone can help me please? > > Thanks in advance > Marco > > --------- Program Code ---------------------- > > from Tkinter import * > > class Application(Frame): > > def __init__(self,master=None): > Frame.__init__(self,master) > menubar=self.addmenubar() > master.config(menu=menubar) > menubar.mainloop() > > def addmenubar(self): > menubar=Menu() > filemenu=Menu(menubar) > menubar.add_cascade(menu=filemenu,label="File") > #these lines got shifted by the newsreader program, but all belong to > #the addmenubar function > filemenu.add_command(label="Configura"command=self.configframe) Isn't a comma required here? ---------> ^ > filemenu.add_command(label="Lavora") > return menubar > > def configframe(self): > self.set(bg="yellow") > w=Label(self,fg="blue",text="prova") > w.grid() > self.update_idletasks() > print "hello!" > > #main > > root=Tk() > applicazione=Application(root) > root.mainloop() > -- > ----------------------------------------------------- > remove "nospam" from email address to answer > ----------------------------------------------------- From emile at fenx.com Fri Mar 1 16:23:16 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 1 Mar 2002 13:23:16 -0800 Subject: mult-indexed xrange? References: Message-ID: "Huaiyu Zhu" wrote in message news:slrna7vqm8.13q.huaiyu at gauss.almadan.ibm.com... > The generator facility in 2.2 allows me to do something cool that I always > wanted: looping around multiple indices with just one for-statement, as the > following code does. Is this available with some built-in functions? for (x,y) in [(i,j) for i in range(2) for j in range(3) ]: print x,y 0 0 0 0 0 1 0 1 0 0 1 1 0 2 0 0 2 1 1 0 0 1 0 1 1 1 0 1 1 1 1 2 0 1 2 1 Press any key to continue . . . -- Emile van Sebille emile at fenx.com --------- From bokr at oz.net Mon Mar 25 16:55:31 2002 From: bokr at oz.net (Bengt Richter) Date: 25 Mar 2002 21:55:31 GMT Subject: list comprehension question References: Message-ID: On 25 Mar 2002 19:10:33 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > >>> [x<2 and 1 or x<5 and 2 or x<9 and 3 or x<=11 and 4 for x in xrange(11)] ^--irrelevant > [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4] > >>> [x<2 and 1 or x<5 and 2 or x<9 and 3 or x<11 and 4 for x in xrange(11)] [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4] That is aesthetically more pleasing. Sorry, couldn't leave it be. ;-) Regards, Bengt Richter From just at xs4all.nl Mon Mar 11 11:15:55 2002 From: just at xs4all.nl (Just van Rossum) Date: Mon, 11 Mar 2002 17:15:55 +0100 Subject: python name spaces References: <3C8C45F2.E0F6D9EC@earthlink.net> Message-ID: In article , Daniel Ortmann wrote: > (I posted since I saw no PEP addressing these issues.) Have you looked at PEP 227? http://python.sourceforge.net/peps/pep-0227.html Just From aahz at pythoncraft.com Wed Mar 27 18:46:49 2002 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2002 18:46:49 -0500 Subject: The Python Way References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: In article , Skip Montanaro wrote: > >Aahz is always admonishing us to just use Queue.Queue. Maybe it's time >I paid a bit closer attention to what he's been saying... Thank Tim; he bashed it into my head, and all I'm doing is carrying the torch. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From evil_wicked at ofir.dk Thu Mar 14 05:41:05 2002 From: evil_wicked at ofir.dk (henrikb666) Date: Thu, 14 Mar 2002 10:41:05 -0000 Subject: Newbie: Undefined reference when initializing Python In-Reply-To: Message-ID: --- In python-list at y..., Michael Hudson wrote: > You need to link to Python; there should be a "-lpython" in there > somewhere (and probably a "-L/some/path/or/other/" too). The -l entry in the Makefile should point to the directory with the libpython2.2.a file, right? When the file is placed in /home/pos/Python-2.2, what should the entry look like exactly, because I tried this without success (yes, I know I am a Linux newbie!): -lpython -lpython2.2 -lPython-2.2 -L/home/pos/Python-2.2 Still get errors when compiling, either "cannot find -lpython2.2" when using -l switches like above, or "undefined reference to 'Py_Initialize' like before when just using the -L swith. Thanks again, Best regards, Henrik Jensen From pereira at cis.upenn.edu Fri Mar 8 21:50:15 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Fri, 08 Mar 2002 21:50:15 -0500 Subject: why is python slow? References: Message-ID: On 3/8/02 12:19 PM, in article kuelivht8g.fsf at lasipalatsi.fi, "Erno Kuusela" wrote: > In article , Fernando Pereira > writes: > > | Another reason is that a JIT compiler may not help Python as much as Java, > | because [...] > > i think the last time there was an in-depth thread about this, many > people speculated that a jit compiler could infact help python a lot. > (perhaps a jit compiler can help java even more.) > smalltalk and self implementation techniques were discussed. The irreducible fact is that Python needs extensive runtime type checks, Java doesn't. One could argue that agressive inlining of built-in operations and type checks followed by removal of redundant machine instructions might have the effect of removing most type checks, but that needs to be shown. -- F From dietmar at bronko.fh-wedel.de Tue Mar 19 15:34:23 2002 From: dietmar at bronko.fh-wedel.de (Dietmar Lang) Date: 19 Mar 2002 20:34:23 GMT Subject: Serial Ports References: <3c96c220$1_1@news.iprimus.com.au> Message-ID: Hi! Jamie Carl wrote: > I'm still fairly new to Python so forgive me. I'm hoping someone can > point in the right direction regarding how I would go about accessing a > serial com port from Python. I'd like to do it mainly under Linux, but > hopefully it will work under windows aswell. > > Is it possible? Can someone point me to some documentation or code samples? Check out the Universal Serial Port Python Library: http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html Hoping this helps, Dietmar -- I haven't lost my mind -- it's backed up on tape somewhere. From greg at cosc.canterbury.ac.nz Sun Mar 10 22:41:56 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 11 Mar 2002 16:41:56 +1300 Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> <3C880AC2.6070708@sneakemail.com> Message-ID: <3C8C2784.A3605107@cosc.canterbury.ac.nz> Joshua Macy wrote: > > But then you have to indent everything in the text to that level, which > isn't quite the same as cut-and-paste arbitrary text any more. True, but to me, that's a feature. It annoys me that triple-quoted strings can't be made to fit in with the indentation structure of the rest of the program. > If > triple quoting isn't sufficient, I'd take that as a sign that the > material should be a separate data file... One problem with that is the hassle of making sure that the separate file remains with the Python code and is accessible from it. Maybe there should be a function which will search for an arbitrary file using the same rules as are used for finding modules during import. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From dragon at china.org Sat Mar 9 15:01:44 2002 From: dragon at china.org (Qiang.JL) Date: Sat, 09 Mar 2002 20:01:44 GMT Subject: should i learn it first ? References: Message-ID: "Jason Orendorff" wrote in message news:mailman.1015700776.13249.python-list at python.org... > Qiang.JL wrote: > > I am a student who have learned perl,java and other like data structure > > stuff. Now i want to take some further step to learn one or two > > languages to improve my language view. There are two languages are on > > the list: python and C++ > > Learn C first. > > > do i need to learn C/C++ to be a good programmer? > > You can be a good Java programmer without knowing C. > You can be a good Python programmer without knowing C. > But every good *all-around* programmer I've met knows C. > > ## Jason Orendorff http://www.jorendorff.com/ > > Do you guys not agree to master C/C++, a large amount of time will be required (somewhere on the net i saw it's appro 3-4 years. whew!!) In one i want to learn it but on the other this time consuming issue scare me .as the bad tradeoff -- it's smarter to use a language that uses the machine's time less efficiently, but your time much more efficiently. am i whining? , :-) and one more question, what's you view of "you have mastered a language" ? knowing syntax and grammer is the begining to master, then know how to use them(wisely) and coding coding ... after certain long time , that you call you master the language? As the same data structure and programming mind almost apply to any language, i never so sure if i master a language or not, and only feel i can use this or that language do the job. Or maybe this can be said there is no such thing you master the language, It's only you know this language better and have more experience with it. Those are the questions poping up in my head once in a while when i am tempted by some fance widely used languages and wondering should i give it a go by putting aside the one i am using which i am not sure if i've mastered it yet. sincerely thanks any input which will help me explore the programmer world ..... Q. From md_lazreg at yahoo.com Fri Mar 22 20:16:56 2002 From: md_lazreg at yahoo.com (mohamed lazreg) Date: Fri, 22 Mar 2002 17:16:56 -0800 (PST) Subject: Packaging tool In-Reply-To: Message-ID: <20020323011656.67443.qmail@web10502.mail.yahoo.com> --- Gillou wrote: > "make" seems to be what you're looking for. > It's not in python, but it does the job. Nice try...:):):P. By a packaging tool I do not mean a make utility. I have in mind some thing like dpkg, the Debian package management system. (but I would like to have it in python). Thank you anyway... Mohamed > "mohamed lazreg" a ?crit dans > le message news: > mailman.1016831987.19520.python-list at python.org... > > Dear Pythoneers, > > > > I have been encouraged by the responses I got > about my > > bug tracking system question... So now I am > looking > > for a free packaging tool writeen in python (it > has to > > be in python)... By a packaging tool I mean a tool > > that goes into a development area of a software, > takes > > the correct files and binaries depending on some > user > > parameters (configuration files) then creates a > > package ready to distribute... > > > > Thank you again for all your help... > > > > Mohamed > > > > __________________________________________________ > > Do You Yahoo!? > > Yahoo! Movies - coverage of the 74th Academy > Awards? > > http://movies.yahoo.com/ > > > > > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________________________ Do You Yahoo!? Yahoo! Movies - coverage of the 74th Academy Awards? http://movies.yahoo.com/ From benc1 at today.com.au Mon Mar 11 19:40:02 2002 From: benc1 at today.com.au (Ben C) Date: 11 Mar 2002 16:40:02 -0800 Subject: Porcess control on win32 References: <8beb91f5.0203101746.544e64dd@posting.google.com> <3C8C204F.1080100@skippinet.com.au> Message-ID: <8beb91f5.0203111640.484e6a36@posting.google.com> Thanks Mark .. From robin at jessikat.fsnet.co.uk Sat Mar 16 15:57:27 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 16 Mar 2002 20:57:27 +0000 Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy References: Message-ID: This all seems a bit wrong to me. The server is surely the program that implements the communication protocol. Calling its local representative 'server' seems to me like calling a socket object 'modem' or 'serial port' or even 'server' since sockets often represent remote servers. Of course we're in real Caroll country here with names of names of things etc. -Bolting down the rabbit hole-ly yrs- Robin Becker From aahz at pythoncraft.com Sun Mar 31 20:23:29 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 20:23:29 -0500 Subject: multithreading and Tkinter References: Message-ID: In article , James Logajan wrote: >martin at v.loewis.de (Martin v. Loewis) wrote: >> >> [ On a thread signalling the Tkinter mainloop thread: ] >> If you want to delete the need for an after() method altogether, you >> could register an after_idle callback. You can do that from a >> different thread; Tkinter will call the after_idle callback from the >> same thread that runs the mainloop. > >Has anyone ever tried using after_idle in a worker thread as a way to >signal a Tkinter mainloop thread? I'm wondering if this proposal is >really thread safe, since technically a worker thread is making a call to >Tk (even if it is nothing more than registering a callback) while the >mainloop thread may also be in the process of making calls to Tk. I haven't >tried it but have been considering it, but wanted to know if this was a >reasonable solution. In theory, yes. Whenever your worker thread is active, it holds the GIL and things are safe -- sort of. The problem is that once you've called after_idle, it's possible for the GIL to switch away unless after_idle is a C function that does not release the GIL. So you'll have to do some poking around in Tkinter to find out. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From hfoffani at yahoo.com Sun Mar 10 09:48:56 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Sun, 10 Mar 2002 15:48:56 +0100 Subject: PEP 284, Integer for-loops References: Message-ID: <20020310094916.372$2q@news.newsreader.com> Roy Smith, 12 range() in 6100 lines David Mertz, 2 in 3100 James Althoff, almost 300 in Jython code James, is it too difficult to extend java inherited classes to behave in a more pythonic tradition way? For instance, instead of collection.getCount() have the chance to use collection.__len__()? I guess that is not possible to override a superclass, right? Regards, -Hernan From jason at jorendorff.com Fri Mar 8 13:25:16 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 8 Mar 2002 12:25:16 -0600 Subject: Where is quote (again)? In-Reply-To: <20020308153801.GD2591@lilith.hqd-internal> Message-ID: Gerhard H?ring wrote: > Le 08/03/02 ? 07:21, N Becker ?crivit: > > Back in 1999, I asked "where is quote?". I was looking for > > a way to quote a function (delay evaluation). > > [...] > > Just out of interest: what's that good for? I think N Becker is asking for two different things. 1. Quoting. For example, suppose the character $ had the effect of "quoting" the following Python expression. Just as "" marks turns something into a string, the $ turns it into a parse tree. Here's how you might use it. def sortlist(lst, code = $cmp(a, b)): cmp_function = lambda a, b: eval(code) lst.sort(cmp_function) x = [...] sortlist(x, $(cmp(a.name, b.name) or cmp(b.date, a.date))) In Lisp, the apostrophe ' is the quote character. Quoting is important in languages where you can extend the syntax yourself. Lisp is such a language, and it uses quoting to implement features like (delay) and (force) below. 2. Lazy evaluation. This is easier to describe, I guess. :) Laziness is not evaluating something until you actually need the result. xrange() is lazy. range() is eager. Generators are lazy. List comprehensions are eager. You can use laziness to handle huge or infinite amounts of information. Think of the typical generator example, which calculates Fibonacci numbers. Obviously you can't calculate that sequence eagerly; it's infinite. Scheme has language features (delay) and (force) that support laziness. SICP (Abelson, Sussman, Sussman) discusses them in the context of "streams", which are a sort of cousin of iterators (different philosophy though). http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html By the way, I recommend reading this book from page 1 onward. Lisp doesn't subscribe to "Flat is better than nested"; this book will teach you the opposite way of thinking. ## Jason Orendorff http://www.jorendorff.com/ From logiplexsoftware at earthlink.net Wed Mar 20 15:43:29 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 20 Mar 2002 12:43:29 -0800 Subject: eval() In-Reply-To: References: Message-ID: <20020320124329.54956d70.logiplexsoftware@earthlink.net> On Wed, 20 Mar 2002 20:31:46 -0000 maximilianscherr wrote: > what does eval exactly do? > > could it do somehting like opening a text file with this: > > hello = 1 > if hello = 1: > print 'yeah' > > eval(readline()[:-1]) > ... You would want exec for that. eval is for evaluating an expression, not a statement: Python 2.2 (#1, Mar 15 2002, 11:52:42) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-81)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = eval("1 + 2") >>> a 3 >>> exec "a = 2 + 3" >>> a 5 >>> -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From just at xs4all.nl Mon Mar 4 02:54:13 2002 From: just at xs4all.nl (Just van Rossum) Date: Mon, 04 Mar 2002 08:54:13 +0100 Subject: functional programming with map() References: <3C7AFA8B.47A23F10@cosc.canterbury.ac.nz> Message-ID: In article , "Raymond Hettinger" wrote: > "Greg Ewing" wrote in message > news:3C7AFA8B.47A23F10 at cosc.canterbury.ac.nz... > > > Well, that's more of an "accidental" side effect. > > Ideally, Guido would use his time machine to go back > > and make for-loop control variables local to the > > loop, so that the same could then be done for LCs. > > Actually, Guido would not use the time machine. > He assures me that exposing the looping variable was > done on purpose and that the alternative was considered > and dismissed. The rationale for exposing the loop > variable is to make the list comprehension perform > identically to its for-loop equivalent. I think Greg's talking about the loop variable(s) in the _traditional_ for loop. Just From gerson.kurz at t-online.de Tue Mar 19 03:06:19 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Tue, 19 Mar 2002 09:06:19 +0100 Subject: modifications of PythonWin? References: Message-ID: Alex K. Angelopoulos wrote: > I'm looking for information on the PythonWin IDE - specifically, any > modifications or customizations that may have been done to it in the past. I have made a small patch to allow SourceSafe checkins (see http://p-nand-q.com/pythonwin-vss.htm). But what kind of customizations are you looking for (or have you planned on doing yourself) specifically? From jan.dries at dcube-resource.be Wed Mar 20 11:55:21 2002 From: jan.dries at dcube-resource.be (Jan Dries) Date: Wed, 20 Mar 2002 17:55:21 +0100 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> <3C984F44.1090001@pobox.com> Message-ID: <3C98BEF9.4090200@dcube-resource.be> > May I ask you what the scale for your webapp was? (Because MySQL is > related to small to mid-size web applications). Is it the same case with > Python? FWIW, a recent benchmark test in Eweek showed MySQL to be comparable to Oracle 9i with respect to both performance and scalability. See http://www.eweek.com/article/0,3658,s=708&a=23115,00.asp Regards, Jan From phr-n2002a at nightsong.com Fri Mar 8 18:02:01 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 08 Mar 2002 15:02:01 -0800 Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> <3C88E7B4.A910D281@earthlink.net> Message-ID: <7xvgc6k6ja.fsf@ruckus.brouhaha.com> Michael Hudson writes: > The combination of lazy evaluation and non-functional semantics are > only good for creating confusion. > > functional non-functional > strict ml python > lazy haskell brrr What do xrange, xreadlines, etc. do, if not lazy evaluation? From irmen at NOSPAMREMOVETHISxs4all.nl Sun Mar 24 13:28:55 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Sun, 24 Mar 2002 19:28:55 +0100 Subject: Pyro: mailing list available Message-ID: For those people interested in Pyro (http://pyro.sourceforge.net), I've added a mailing list. This makes discussing Pyro issues a lot easier than using the forum on the sourceforge site. If you're interested in subscribing, visit http://lists.sourceforge.net/lists/listinfo/pyro-core Irmen de Jong From inigoserna at terra.es Mon Mar 4 11:48:34 2002 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: 04 Mar 2002 17:48:34 +0100 Subject: ANN: lfm 0.8 Message-ID: <1015260514.2805.25.camel@lethe.infernus.org> Hello, I've uploaded lfm v0.8 on its web site: http://www.terra.es/personal7/inigoserna/lfm [With this release, I have finished all the features I want for lfm, so I hope to release v1.0 in May. These 2 months will be spent fixing bugs and maybe adding features people want. Nevertheless current version is very robust and stable, I use it daily without problems.] lfm is a 'midnight commander'-clone written in Python and licensed under GNU Public License. It should work on any UNIX with a modern (n)curses library and Python curses module compiled in. See README file or visit the web page for more information. Changes since version 0.7: Version 0.8 ("Close to Paradise") - 2002/03/04: + Implemented VFS feature to enter into .tar.gz and .tar.bz2 files + Panelize vfs option in find/grep implemented + Tree panel implemented + 'lfm' and 'pyview' are simple scripts now, not just a copy of the .py files> __init__.py contains global variables now + A new message window is used to show work in progress, in place of a message in status bar. 'run_thread' function has been cleaned too + Copy / move features now use my own function to walk trees, instead of 'shutil.copytree' which originates some problems and bugs + In ChangePermissions window, the cursor movement is circular now + Change copyright date to years 2001-2 + I don't need a crypt / uncrypt feature, so eliminated from TODO list + Many bug fixes and functions rewrites. See ChangeLog for complete list - lfm: * if panel2 shows 'a' file in panel, and in panel1 'a' is moved or deleted, lfm crashes * after moving a file cursor goes to next directory as deletion does * catching an exception after not been able to copy => it crashed when trying to delete copied files * "messages.SelectItem, messages.FindfilesWin, messages.MenuWin, messages.ChangePerms: upperleft corner disappears" * findgrep: fix bug: if selected file has a ':' in name - pyview: * changing 'addch' by 'addstr' shows individual chars >= 0xA0 (meta chars) correctly, neither in reversed video or as 2 chars * "if wrap mode => fix prev/next page & up/down cursor". Now they move to screen lines, not to physical lines Best regards, I?igo Serna -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 240 bytes Desc: This is a digitally signed message part URL: From bokr at oz.net Mon Mar 25 20:15:21 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Mar 2002 01:15:21 GMT Subject: Doing a ps in windows.. (Is application XYZZY running?) References: Message-ID: On Mon, 25 Mar 2002 20:54:19 GMT, Andrew Markebo wrote: >*blush* yeah I know.. not really.. here, only almost :-) > >I have the windows-compiled python 2.2, and I would like to see if >Opera or Netscape is running on my computer (poor sod, running Win2k, >XP or 98).. How do I do this, I suppose I could use something in the >win32api, but what is something.. :-) ?? > >On unix I do "ps -ef | grep netscape" ;-) > There are correpsonding things on NT4 at least: >>> def pidmatch(x): ... import os ... pidlines = os.popen('pstat | findstr/R/I "^pid.*'+x+'"').readlines() ... return [line.split()[-1] for line in pidlines] ... >>> pidmatch('iexplore') [] >>> pidmatch('netscape') ['netscape.exe'] >>> pidmatch('sys') ['System', 'systray.exe'] You could read the whole pstat result and do the grep/findstr function in pidmatch, but I was inspired by your unix example ;-) Regards, Bengt Richter From peter at engcorp.com Fri Mar 1 07:07:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Mar 2002 07:07:39 -0500 Subject: newbie lists and code examples for OOP. References: Message-ID: <3C7F6F0B.9B606460@engcorp.com> skoria wrote: > > Firstly: is there a better forum for newbie questions like this one? > It's hard for me to post to a high traffic list, and maybe there's a > local uk based one or one specifically aimed at newbies. > > I'm trying to write a class where one function calls a method in the > same class. Right now I'm doing this with trial and error, and I don't > really understand where I need to put parentheses, use (self), etc. I > can't find any "functional" examples of object oriented programming on > any online tutorials, or any simple programs already written that can > be used as a good tool to figure out how to call functions within > classes in python, when to use self.* what internal functions (like > __init__) can be used for. Lots of theory on this, but no functional > examples. I'm not sure if by "functional" you mean "working examples" rather than "functional programming" in the computer science sense... If the former, have you looked in the python\lib folder to examine the source code for all the standard modules. At least some of them are object-oriented with samples of what you are looking for, and more. -Peter From mlh at vier.idi.ntnu.no Sun Mar 31 18:50:51 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 31 Mar 2002 23:50:51 +0000 (UTC) Subject: PEP 285: Adding a bool type References: Message-ID: In article , Roy Smith wrote: >What should the following examples print? > >>>> print {} == False >>>> print {} is False > >I'm convinced the second one should print "False", but I'm not really sure >about the first. I also assume that This is dealt with in the PEP. {} != False. >>>> print False is not True > >should print "True"? Of course. (Or 1, if str(True) ends up being "1".) >For those thinking ahead to obfuscated Python contests, I can see having >lots of fun with this. The following, for example, is a valid Python >program under this PEP: > >False is not True is not "False is not True" How is this any more or less obfuscated than 0 is not 1 is not "0 is not 1" ? -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From cunsan at lycos.com Tue Mar 26 22:05:40 2002 From: cunsan at lycos.com (stclaus_imi) Date: Wed, 27 Mar 2002 03:05:40 -0000 Subject: running python on win2k In-Reply-To: Message-ID: thanks. it works. what about apache :). i read that you need to assoc the py extension and also ftype it. but how to do it on win2k easily? --- In python-list at y..., Syver Enstad wrote: > "stclaus_imi" writes: > > > hi, all of you. > > > > i downloaded python for win2k. i wonder how to run it via the command > > > > line and over the apache/iis web server. > > > > For using in cgi script with IIS use inetmgr (mmc snap in for iis) and > configure the App Mappings for the .py ending to python "%s" %s. > -- > From gustav at morpheus.demon.co.uk Thu Mar 21 14:11:51 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: Thu, 21 Mar 2002 19:11:51 +0000 Subject: Slices... what are they good for? References: Message-ID: <21ck9us2iiecbhq5vm5j1udqde8sj3b7hs@4ax.com> On 20 Mar 2002 16:03:51 -0800, johnl at axis.com.au (John Lehmann) wrote: >I had forgotted slices existed, until I was making an object that I >was pretending was a tuple. > >I was shocked to find that this didn't work: > >>>> l = ['a', 'b', 'c'] >>>> l[1:2] >'b' >>>> l[ slice(1,2) ] >Traceback (most recent call last): > File "", line 1, in ? >TypeError: sequence index must be integer It strikes me as a definite wart that the builtin types don't support generalised slices. Of course, adding such support is seriously non-trivial, which is probably why it hasn't happened up to now (and maybe never will...) Paul. From p.magwene at snet.net Sun Mar 3 00:15:31 2002 From: p.magwene at snet.net (Paul M) Date: Sun, 03 Mar 2002 05:15:31 GMT Subject: regular expression for nested matching braces Message-ID: Is it possible to create a regular expression for searching for the outermost matching braces in a string in which there may be nested braces? For example, given this string: "A line of text with {multiple and {nested} braces} to {confuse} re!" I'd like to create a regular expression which would find the substring: "{multiple and {nested} braces}" on the first search invocation, and then: "{confuse}" on the second invocation of the search method. It would seem I would need some sort of negative lookbehind assertion, but of arbitrary, rather than fixed length. It's fairly straightfoward to write a function to do this, but a suitable regular expression would save me a few headaches. Is what I'm asking possible? Thanks, Paul Magwene From arturs at iidea.pl Wed Mar 6 07:10:58 2002 From: arturs at iidea.pl (Artur Skura) Date: Wed, 6 Mar 2002 12:10:58 +0000 (UTC) Subject: [ANN] istring 1.0.1 released; announce list created References: <3C86047F.1080601@stroeder.com> Message-ID: Michael Str?der wrote: >>>>>s = i("Value is $n") > > Maybe it's me but I can't see the advantage over using > > >>> s = "Value is %s" % (n) > > How about providing a more complex example illustrating the benefits > of istring? Should I paste from their page? ;) Why would I want to interpolate variables when I could use %s notation? Ask yourself which query is clearer: (1) db.query("""SELECT foo, bar FROM %s WHERE rsrc_id = %s AND name = '%s'" % (table, rsrc_id, name)) Or: (2) qry = istring("""SELECT foo, bar FROM $table WHERE rsrc_id = $rsrc_id AND name = $.name""") db.query(qry) To make this even cleaner, we could write a function that took a regular raw string with istring interpolation, then made an istring of it and submitted the query, like this: (3) db.iquery("""SELECT foo, bar FROM $table WHERE rsrc_id = $rsrc_id AND name = $.name""") It's not something revolutionary, just useful. If it was in standard Python, I would probably use it every day. Regards, Artur -- http://www.wolneprogramy.org From garrett at bgb-consulting.com Wed Mar 27 20:00:09 2002 From: garrett at bgb-consulting.com (Don Garrett) Date: Thu, 28 Mar 2002 01:00:09 GMT Subject: Why does this work? References: Message-ID: <3CA26B2B.EA93374@bgb-consulting.com> "Delaney, Timothy" wrote: > > > From: Phlip [mailto:phlip_cpp at my-deja.com] > > > > We find just >having< a style guideline slightly more > > important than the > > value of any few marginal items in it. > > > > And we like to find ways to cure the "magic member bug". If > > you can think of > > any others, please share. > > __slots__ > > Tim Delaney Um... this does help protect them from outside interferance, but doesn't in any way require them to have been initialized in __init__, or even protect you from a misspelled name, does it? Just trying to make sure that nothing goes on with __names besides the name mangling into __class__name. -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From a.clarke11 at pop.ntlworld.com Thu Mar 28 20:05:53 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Fri, 29 Mar 2002 01:05:53 +0000 Subject: Why does this work? References: Message-ID: <3CA3BDF0.5C4D8FF@pop.ntlworld.com> Thanks everyone, some food for thought there, and it has helped my thinking. Tony From flognat at flognat.myip.org Mon Mar 25 15:54:19 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Mon, 25 Mar 2002 20:54:19 GMT Subject: Doing a ps in windows.. (Is application XYZZY running?) Message-ID: *blush* yeah I know.. not really.. here, only almost :-) I have the windows-compiled python 2.2, and I would like to see if Opera or Netscape is running on my computer (poor sod, running Win2k, XP or 98).. How do I do this, I suppose I could use something in the win32api, but what is something.. :-) ?? On unix I do "ps -ef | grep netscape" ;-) /Andy -- The eye of the beholder rests on the beauty! From Ken.Peek at Engineer.com Sat Mar 30 13:51:24 2002 From: Ken.Peek at Engineer.com (Ken Peek) Date: 30 Mar 2002 10:51:24 -0800 Subject: PEP 285: Adding a bool type References: Message-ID: Guido van Rossum wrote in message news:... > > [Guido] > > >> 5) Should operator.truth(x) return an int or a bool. Tim Peters > > >> believes it should return an int because it's been documented > > >> as such. > > > > [Ralph Corderoy] > > > Unlike Tim to produce such a poor reason. Has he been paraphrased a > > > little too much? > > [Tim] > > Not in Guido's eyes . We don't need 3 equivalent ways to turn an > > arbitrary expression into a bool ("bool(x)" same-as "not not (x)" same-as > > "truth(x)"). *Especially* if str(bool) and repr(bool) produce 'True' and > > 'False', people have a legitimate need to make an arbitrary true/false > > expression produce 0 and 1 too, if only to preserve 0/1-based true/false > > output. operator.truth() has always been the best way to do exactly that. > > Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and "(0, > > 1)[boolexpr]" reek in comparison. > > Tim must be missing something. The obvious way to turn a bool b into > an int is int(b). Having to import the obscure 'operator' module for > this purpose is backwards. (IMO there's almost *never* a reason to > import that module anyway.) > > --Guido van Rossum (home page: http://www.python.org/~guido/) I don't see that adding a "bool" (or better: "boolean", since I HATE abbreviated words) would be such a big issue. This would allow for better "readability" of the code. ("Readability" being defined as maximally exposing the intentions of the programmer to the largest audience of readers as is practical.) Comparison operators (under the hood) should return a "boolean", so that if you type: >>> 1 < 2 True >>> 1 > 2 False Yes-- I think there should have to be some type conversion required if you need to use your boolean in an expression. The idea being, that you shouldn't be using a "boolean" in an expression anyway, unless it is some kind of obscure programming trick (which should be depricated anyway.) If no one can agree on how the boolean type should be implemented, then leave it the way it is, and add a "readonly" keyword-- which would be useful for other constants as well: readonly: # attempts to write to these will throw a # "TypeError: attempted write to a constant" False = 0 True = 1 MY_CONSTANT = 42 As to the case of the keywords-- well, I prefer all uppercase for constants, because I think they stand out better when reading code. I don't think this should be forced by the language though-- let people do whatever they want-- why be a baby sitter? Regardless of whether or not a boolean type is implemented-- in my code, I would simply define: TRUE = True FALSE = False And if the 'readonly' construct is implemented: readonly: TRUE = True FALSE = False I then use TRUE and FALSE in my code instead of True and False. Problem solved (for ME anyway). The 'readonly' keyword would be VERY helpful though (to catch programming mistakes)-- which happen a lot for me, anyway... From aahz at panix.com Sun Mar 3 23:31:58 2002 From: aahz at panix.com (Aahz Maruch) Date: 3 Mar 2002 20:31:58 -0800 Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> Message-ID: In article <3C829AA2.1B21E205 at arakne.com>, Frederic Giacometti wrote: >Aahz Maruch wrote: >> In article , >> Frederic Giacometti wrote: >>> >>>In addition to all the benefits that Christian has described so far, >>>stackless python would make it possible to have a different OS >>>multi-threading implementation for calling external C/C++ libraries; one >>>that does not require interpreter lock operations. >>> >>> [...] >>> >>>Stackless just means that function calls executed by the bytecode are >>>executed by a C function that returns immediately; thus disconnecting >>>the C call stack from the virtual machine call stack. In current >>>python, they are interleaved one-on-one; making it impossible to switch >>>context within the VM unnless you do Christian's last 'non-portable' >>>assembly language manipulation. >> >> How's that again? In the absence of pre-emptive thread scheduling, what >> good is the immediate return from the C function? More than that, how >> can you possibly call external libraries without the interpreter lock, >> if those libraries have any access to Python variables? If they *don't* >> have access to Python, how is that any different from just using the >> macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS? > >Just reverse the paradigm: have the python VM run in a single thread, >using stackless microthreads for python multithreading, and run the C >calls in a pool of threads. This way: no lock is needed, since only >one thread runs the VM, with the help of microthreads, and C calls run >in other threads. This doesn't make any sense unless you assume OS-level threads, and I thought part of the point of Stackless was to avoid requiring OS-level threads. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From sam_collett at lycos.co.uk Fri Mar 1 12:27:09 2002 From: sam_collett at lycos.co.uk (Sam Collett) Date: 1 Mar 2002 09:27:09 -0800 Subject: ADO GetRows() example for newbies References: Message-ID: <2030665d.0203010927.38edc51@posting.google.com> How could you do pages of records (in ASP for example), you may only want a few records at a time (if you have 1000 records for example)? For example I may want a page with 10 records per page, with the page numbers at the bottom. For 100 records: 10 pages (10 links) Start at 1 on page 1, 11 on page 2 etc) TIA tom at peresys.co.za (Tomasz Stochmal) wrote in message news:... > #ADO GetRows() example > > import win32com.client > import pprint > > def main(): > ConnectionString = 'Provider=SQLOLEDB.1' \ > +';Data Source=127.0.0.1' \ > +';Initial Catalog=ZASecurities' \ > +';User ID=sa' \ > +';Password=' > > SQL='SELECT TOP 1 * FROM TESTCASE' > > DBConnection=win32com.client.Dispatch('ADODB.Connection') > DBConnection.Open(ConnectionString) > try: > rs=win32com.client.Dispatch('ADODB.Recordset') > rs.Open(SQL,DBConnection) > try: > # Info Row: Field Name/Type > result=[] > buf=[] > for i in range(rs.Fields.Count): > buf.append([rs.Fields.Item(i).Name,rs.Fields.Item(i).Type]) > > result.append(buf) > > # Data Rows > if not rs.EOF: > data=rs.GetRows() > assert len(data) > 0 > data=[[r[col] for r in data] for col in range(len(data[0]))] > result.extend(data) > finally: > rs.Close() > > pprint.pprint(result) > finally: > DBConnection.Close() > > > if __name__ == "__main__": > main() > > > # Change ConnectionString & SQL From tim.one at comcast.net Sat Mar 9 21:07:39 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 09 Mar 2002 21:07:39 -0500 Subject: round() function strange behaviour In-Reply-To: <3c8a9261.149508269@news> Message-ID: [brobbins333 at shaw.ca] > the round() function will sometimes return a predictable result, as > in: > > round(45.67891, 2) > >>> 45.68 > > but sometimes it will return something like: > > round(56.78923, 2) > >>> 56.789999999999999 > > 2.1 and 2.2 both behave this way on two different (Windows) computers. > What's going on here? Also on Linix, Mac, etc computers. See http://www.python.org/doc/current/tut/node14.html round() usually does the best job that can be done. From garry at sage.att.com Mon Mar 4 10:47:05 2002 From: garry at sage.att.com (Garry Hodgson) Date: Mon, 4 Mar 2002 15:47:05 GMT Subject: Twain Scanners and some other questions References: Message-ID: <3C8396F9.199D3E6B@sage.att.com> Jimmy Retzlaff wrote: > > dix wrote: > > I need to know if there is a free library for Python to manage Twain > > scanners in order to pilot the scanner and have an image > representation > > of the paper document. > > The wonderful Daily Python-URL (http://www.pythonware.com/daily) just > pointed to http://twainmodule.sourceforge.net a few days ago. but this only works on windows, making it useless for real computers. -- Garry Hodgson Let my inspiration flow Senior Hacker in token rhyme suggesting rhythm Software Innovation Services that will not forsake me AT&T Labs 'til my tale is told and done. garry at sage.att.com From tkeon0 at netscape.net Thu Mar 7 20:31:26 2002 From: tkeon0 at netscape.net (Trevor Keon) Date: 7 Mar 2002 17:31:26 -0800 Subject: Returning strings from DLLs written in Delphi Message-ID: Hi, I have been trying to get a DLL written in Delphi 5 to return a string to Python 2.1.2 (i use windll to access the dll), and all I get is a bunch of numbers(the numbers stay the same too). I also had this problem when trying to return integers, however adding stdcall to the function export line solved that problem. Unfortunately it hasnt solved the problem with passing Strings. I have also tried safecall, cdecl (even register and pascal...i was getting deperate ;) ) with no luck. I also tried using PChars instead and Char, however no luck (the number did change though). Does anyone have any ideas how to get around this problem? I tried to make the most basic code to return a string so I could hopefully beat it into submission, but still havent got anything. The code is: ... function getString(): String; stdcall; //can also add safecall, cdecl, etc export; ... function getString(): String; begin Result := 'work'; end; ... Any help will be greatly appreciated. - Trevor From -$P-W$- at verence.demon.co.uk Thu Mar 7 04:49:11 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 7 Mar 2002 09:49:11 -0000 Subject: select.select() on Regular Files? References: Message-ID: In article , Jim Dennis wrote: > O.K. so what can I do for asynchronous I/O notification on > regular files? How can I efficiently block and wake up when > I/O is available on any of my file descriptors? > > Don't tell me I have to go into a sleep and poll stat() or > seek() loop! It's hard to imagine that UNIX got this far > without offering a better solution than that! If you run strace on "tail -f somefile", you'll find that sleeping and stat'ing is what it's doing, so I don't think there's a better way. -- Paul Wright | http://pobox.com/~pw201 | From python at rcn.com Mon Mar 4 00:39:53 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 4 Mar 2002 00:39:53 -0500 Subject: functional programming with map() References: <3C7AFA8B.47A23F10@cosc.canterbury.ac.nz> Message-ID: "Greg Ewing" wrote in message news:3C7AFA8B.47A23F10 at cosc.canterbury.ac.nz... > David Eppstein wrote: > > > > No side effects? Try this: > > > > L = [x for x in range(10)] > > print x > > Well, that's more of an "accidental" side effect. > Ideally, Guido would use his time machine to go back > and make for-loop control variables local to the > loop, so that the same could then be done for LCs. Actually, Guido would not use the time machine. He assures me that exposing the looping variable was done on purpose and that the alternative was considered and dismissed. The rationale for exposing the loop variable is to make the list comprehension perform identically to its for-loop equivalent. Raymond Hettinger a.k.a. rumour control From joerg_schuetter at heraeus-infosystems.com Fri Mar 22 05:33:21 2002 From: joerg_schuetter at heraeus-infosystems.com (=?ISO-8859-1?B?SvZyZyBTY2j8dHRlcg==?=) Date: Fri, 22 Mar 2002 11:33:21 +0100 Subject: How to set the Timestamp of a File Message-ID: <20020322113321.7e52dba1.joerg_schuetter@heraeus-infosystems.com> Hi How can I set the timestamp of a file (especially under windows) with python? In Unix/Linux there is a tool caled touch. There is no problem to read the timestamp, but how can I set the timestamp to a desired time? Gru? J?rg Sch?tter -- Dipl.-Ing. J?rg Sch?tter - Email Joerg.Schuetter at heraeus-infosystems.com Systemspezialist Internet, Sicherheit From James_Althoff at i2.com Mon Mar 11 19:15:43 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 11 Mar 2002 16:15:43 -0800 Subject: PEP 284, Integer for-loops Message-ID: [Philip Hunt] > How about: > > def rowKeys(table): > return xrange(0, table.getRowCount()) > > def someFunction(): > for r in rowKeys(someTable): > #...iterate over all the rows in (someTable) > > Note that this is less cumbersome than your chosen: > > for r in someTable.getRowCount(): > #...iterate... Assuming that I want to share and reuse this amongst the development team I don't think I see that import tableutils for rowindex in tableutils.rowKeys(table): or from tableutils import rowKeys for rowindex in rowKeys(table): is *less* cumbersome than for rowindex in table.getRowCount(): But I can see why you might prefer using a helper function -- especially if you don't want to type "getRowCount" a lot, if that's what you mean. Thanks for your suggestion. Jim From gerhard at bigfoot.de Wed Mar 20 06:05:17 2002 From: gerhard at bigfoot.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 20 Mar 2002 12:05:17 +0100 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C985678.8010200@pobox.com> Message-ID: <3C986CED.6070104@bigfoot.de> Ahmed Moustafa wrote: > For example, where I work, we have JRE for OS/390 (by IBM). Is there a > mainframe interpreter for Python? Or, will Jython do? Google says there's a Python 1.4 port. But 1.4 is very old. I don't know of any newer ports. Jython should of course work just fine. even-my-PDA-can-do-Python'ly yours, Gerhard From brueckd at tbye.com Mon Mar 4 10:54:56 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 4 Mar 2002 07:54:56 -0800 (PST) Subject: Rotor in Jython? In-Reply-To: <7xit8daq4n.fsf@ruckus.brouhaha.com> Message-ID: On 3 Mar 2002, Paul Rubin wrote: > writes: > > But the sorry history of rotors has nothing to do with rotor strength and > > everything to do with short/obvious keys, the obvious starting text of the > > messages (e.g. "No news to report"), and the limitations of mechanical > > implementations. You can *always* make a rotor stronger by increasing the > > length of the key - and at no additional computational cost. > > That's erroneous--if you count the rotor and plugboard permutations, > the WW2 Enigma machines had a very large key space (maybe larger than > 56-bit DES) but they were cryptanalyzed with fairly crude > electromechanical devices (the "Bombe" was basically 6 Enigmas wired > together). But still the cryptanalysis was feasible because there was a small number of rotors and the messages had known text. For example, the Turing Bombe worked so well because the Germans routinely spelled out officer titles in the messages. Thanks for the interesting discussion. This thread is getting tired so I'll let it die now. ;-) -Dave From BPettersen at NAREX.com Fri Mar 15 18:24:14 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 15 Mar 2002 16:24:14 -0700 Subject: multiline raw input Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158DA4@admin56.narex.com> > From: les ander [mailto:les_ander at yahoo.com] > > Hi, > i have a program that takes input from the command line > however this input is multi-line and will have a lot of > backslashes I tried using sys.stdin but it ignores the > backslashes. i tried with raw_input but that only takes in > the first line > > can some suggest a remedy? Something like: >>> def ml_input(): ... res = [] ... while 1: ... line = raw_input() ... if line == '.': break ... res.append(line) ... return ''.join(res) ... >>> ml_input() This is a little test . 'This is alittletest' >>> -- bjorn From dsavitsk at e-coli.net Fri Mar 22 14:41:24 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 22 Mar 2002 19:41:24 GMT Subject: quick win32 pipe and objects question References: Message-ID: i seems that the pipe can only hold serialized data, at least that is what the error message said. It also seems that if several clients are writing to the pipe at the same time, or in quick succession, that reading the data is best done with cPickle to avoid errors (i have no numbers to justify this, it just seemed more stable). Lastly, putting a pause between writes seemed to help too ... >>> for i in range(10): ... time.sleep(0.5) ... r = win32pipe.CallNamedPipe(pipename, i, 512, 0) which leads me to think that a single named pipe just doesn't scale well, which is not surprising as Mark H. said it wouldn't on pg 353 ;-) -d "Harald Schneider" wrote in message news:a7f4l7$g2n$04$1 at news.t-online.com... > Sorry for this newby-question .. why pickle ? > > "dsavitsk" schrieb im Newsbeitrag > news:X0sm8.575$d7.169869 at newssrv26.news.prodigy.com... > > when writing and reading from a pipe, is it okay to do something like ... > > > > >>> t = (0, 1, 2, 3) > > >>> r = win32pipe.CallNamedPipe(pipename, t, 512, 0) > > > > of should i pickle t first? > > > > -d > > > > > > From db3l at fitlinxx.com Wed Mar 27 22:26:24 2002 From: db3l at fitlinxx.com (David Bolen) Date: 27 Mar 2002 22:26:24 -0500 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: "Shiv Shankar Ramakrishnan" writes: > Anyone knows just what in the world is going on? Has something happened > (heaven forbid!) to the lead dev for ActivePython that they are so woefully > behind now? Or is ActiveState not bothered about Python at all and more > bothered about other things like Perl, Komodo etc? Thats their preorgative > of course but I like the PythonWin IDE and now I can only get that with > ActivePython since Mark Hammond moved there. Shouldn't there be some > alternative source for getting PythonWin? How about the main Python > distribution also doing PythonWin from CVS? You don't need ActivePython for PythonWin - in fact you've never strictly needed it. ActivePython just happened to include it in their consolidated package. But you could always download the Win32 extensions separately and install them on top of a standard Python installation (in fact that's the only way I've ever used them). Mark's pages are at http://starship.python.net/crew/mhammond/ where you can download the extensions for any Python release (1.5.2, 2.0, 2.1 and 2.2). When he left ActivePython, these pages once again became the authoritative source for the extensions (as they were before he moved to ActivePython). (Mark's pages are also referenced from the main http://www.python.org Python site under the download section in the Windows topic). -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From ykingma at accessforall.nl Wed Mar 6 15:39:19 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Wed, 06 Mar 2002 21:39:19 +0100 Subject: Threading help? References: Message-ID: <3C867E68.B4C3FED2@accessforall.nl> Van, VanL wrote: > > Hello, > > This is my first time playing with python threads, and I am a little at > a loss how to start. Here is what I need to do: > > I need three threads (at least): > > 1. Every .1 second, retrieves some data via http from an adjacent > machine on the network. Easy enough with urllib. > 2. Do processing on that data > 3. Every .1 second, be ready to spit out the most recent results from > the processing in response to an http query. I've got the latest medusa > distribution, and I was thinking about using that. It doesn't really > matter, though. > > As you can see, I have two things that have soft real-time deadlines, > and one thing that I want to do as fast as possible, but doesn't need to > be real time. This sounds like a job for threads. > > I can do each of the individual parts, but I don't know how to combine > them all so that each is running in a different thread, so that process > 2 doesn't make the other two lose their timing. > > Any help? What would you gain from using separate threads for task 1 and 2, ie. what's the point of getting new data (task 1) before the processing on that data (task 2) has finished? Assuming you combine task 1 and 2 in a single thread B, that thread should yield a few times during your 0.1 second period to allow an evt. execution of task 3 in thread C. In case you have thread priorities available you can give C a higher priority instead of yielding in B. In case you decide to have task 1 in a separate thread A you can treat A as C. You might need to yield more often in B with two other threads instead of one. A simple reference to the last available processing result can be shared between any pair of threads. Make sure to copy the reference (not the last result itself) in the receiver. Have fun, Ype P.S. Yielding is bit ugly in CPython. Try time.sleep(0.001). From geoff at gerrietts.net Fri Mar 29 19:10:58 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 29 Mar 2002 16:10:58 -0800 Subject: First post! In-Reply-To: <3CA50013.3582BC63@cam.org> References: <3CA50013.3582BC63@cam.org> Message-ID: <20020330001058.GE7602@isis.gerrietts.net> Quoting Zutroi Zatatakowski (abou at cam.org): > I play a MUD called Core 2651 (http://coremurd.org) and in this MUD, > there is a stock market. The various prices are all on the website and > are updated every once in a while. So basically, I want a script that > checks the page for the prices and print the output in a text file. > I've never done anything that touches the web or internet so I'm really > puzzled. I'm not asking for someone to write it for me (don't spoil the > fun :) but maybe there already are some scripts like that somewhere... > Scripts that parse (is that right?) through a page and get different > infos. Check out urllib for retrieving the page: http://www.python.org/doc/2.2p1/lib/module-urllib.html Check out string and re for parsing the page to grab the stuff you want: http://www.python.org/doc/2.2p1/lib/module-string.html http://www.python.org/doc/2.2p1/lib/module-re.html If that's not enough to get you productive, let me know where you're having specific stopping points. --G. -- Geoff Gerrietts "A little sincerity is a dangerous thing, geoff @ gerrietts.net and a great deal of it is absolutely fatal." http://www.gerrietts.net/ --Oscar Wilde From Gabe.Newcomb at noetix.com Thu Mar 14 19:52:12 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Thu, 14 Mar 2002 16:52:12 -0800 Subject: Good book on Python? Message-ID: <0C7CA8D8DF75494EB09AB6016990107FF08366@NOXMAIL.noetixad.com> I don't know if it's already been mentioned, but Learning Python by Lutz & Ascher is great. If you get that and the Python Essential Reference, you'll have all you need to get started. If you do any work on Windows, I also heartily recommend Python Programming on Win32 by Mark Hammond. It makes some wierd choices about which topics to address (not enough sysadmin stuff for my taste), but it covers a lot of useful stuff, and does it well. Enjoy!! Gabe Newcomb -----Original Message----- From: William Sonna [mailto:wlsonna at attglobal.net] Sent: Thursday, March 14, 2002 4:46 PM To: python-list at python.org Subject: Re: Good book on Python? On Thu, 14 Mar 2002 11:26:01, Antonis C Koutalos wrote: > > Hi there, > I would greatly appreciate information about a good book on python. I > have been programming C for a few years, but I know next to nothing about > python. Therefore, I would appreciate a book that describes the basics of > python as well as the more advanced features of the language. > > Thank you in advance! > > -A. > The Quick Python Book by Harms/McDonald is an excellent book if you want to get up to speed in a hurry. The best way I can think of to describe it is as a "Cliff Notes" for Python. Very terse and well-organized (and consequently VERY easy to browse) - just like Python itself. The book has saved me many, many hours. It focuses primarily on the base language - you won't find much about the more advanced packages, other than a terse, well-organized summary of several of them (and information about where to get more info). If there was a "Quick Java Book" or a "Quick C++ Book" I'd buy them in a heartbeat. -- http://mail.python.org/mailman/listinfo/python-list From duncan at NOSPAMrcp.co.uk Mon Mar 25 10:10:56 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 25 Mar 2002 15:10:56 +0000 (UTC) Subject: PEP262 - database of installed packages References: Message-ID: "A.M. Kuchling" wrote in news:slrna9ubdf.f6.akuchlin at crystal.mems-exchange.org: >> * XXX do we need to store permissions? The owner/group? >> + THE: no, not on windows. > > Really? Even on Windows, couldn't files be potentially owned by > Administrator or some other user. We should definitely have > permissions and owner/group on Unix; can you tell me what Windows > needs here? (I assume MacOS X would be the same as Unix, and earlier > MacOS versions aren't multi-user, so they don't need anything.) On Windows systems all files on an NTFS partition have an owner and access control lists. The command "DIR /Q" displays the owner of each file, or you can add a column to the explorer view. By default I think each file is owned by the owner of the directory in which they are created (BUILTIN\Administrators for just about everything). My laptop also has a FAT partition. It seems that files on that are owned by 'Everyone'. :-( -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From martin at v.loewis.de Sun Mar 24 17:12:40 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Mar 2002 23:12:40 +0100 Subject: 2.2 open References: <1UtsCLAcngn8EwWc@jessikat.fsnet.co.uk> Message-ID: Robin Becker writes: > yes I heard about that, but the semantics seem strange to me. > open is not a file it is a function that produces an open file. It used to be a function that produces an open file, now it is a type that produces an open file. Watch this: >>> import httplib >>> h=httplib.HTTP("localhost") >>> print h So even though httplib.HTTP is a class (something that is very similar to a type), you still can call it. Calling a type makes an instance of the type. > It's now not even amongst the built ins. I don't understant this remark. open is certainly amongst the built-ins: >>> __builtins__.__dict__.has_key("open") 1 > what does X==type(X()) imply? It implies that X is a type; calling a type gives an instance of the type. Regards, Martin From NO_SPAM_jmpurser2 at attbi.com Tue Mar 12 18:59:15 2002 From: NO_SPAM_jmpurser2 at attbi.com (John Purser) Date: Tue, 12 Mar 2002 23:59:15 GMT Subject: frustrated stupid newbie question References: Message-ID: I tried the same code and got no result. The code would run, ask me how high it should check, then nothing. I tried a bunch of 'print' statements to see where it was dying but it never seemed to run the code below the 'input()' statement. Something's going on here. John "Sheila King" wrote in message news:a6l6p9.3vs6ro7.1 at kserver.org... > [posted and mailed] > > On Tue, 12 Mar 2002 16:59:13 -0600, "Scott Kurland" > wrote in comp.lang.python in article : > > > Why isn't this $%^*#$% program working? > > > #Searching for perfect numbers > > > > howhigh= input ("How high should I check?") > > for number in range (1,howhigh): > > factorsum = 0 > > halfnumber=number/2 > > for checking in range (1,halfnumber): > > if number/checking == int (number/checking): > > factorsum = factorsum + checking > > if number == factorsum: > > print number > > > > What do you mean it isn't working? It ran without crashing when I tried it. > Here is the output from a sample run: > > >>> > How high should I check?50 > 10 > > >>> > > Are you expecting some other type of output? What are you expecting? > > > > Flame away, I can't feel dumber than this. > > Oh, now what newsgroup mistreated you so, that you would expect such a > thing? We don't do that here in comp.lang.python! > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ > From claird at starbase.neosoft.com Fri Mar 1 20:14:11 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 1 Mar 2002 19:14:11 -0600 Subject: hotmail References: Message-ID: In article , Gillou wrote: >If you got a pop3 access to your hotmail account, have a look at the >"poplib" package. This is the easiest way. > >If you can only read your mail through Web pages, I think that "urllib" >(performs HTTP GET/POST requests and retrieve Web pages) and "htmllib" >(simple HTML parser) will help you for that job. But it's harder. . . . POP3 is *much* easier, whenever practical. As admirable as urllib and htmllib are, this sort of "Web scraping" invariably turns out to be hard, hard work. The sites most in need of automatic processing are generally barricaded behind cookies and other impedimenta that are a poor fit for urllib--and it's best we not talk about the parseability of their HTML! Those who insist on scraping should read If you do so, you're only a couple of clicks more from locating , "a neat little utility to download mail from a HotMail account ..." -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jason at jorendorff.com Thu Mar 14 12:55:09 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Thu, 14 Mar 2002 11:55:09 -0600 Subject: Telnet-like interface with authentication in server In-Reply-To: <8zYj8.63$5Kn.179044352@news.telia.no> Message-ID: Thomas Weholt wrote: > Got a webserver based on BaseHTTPServer using threads and I want a simple > text-based interface to, like telnet. Would it be possible to > have a normal > telnet-client connect to my server somehow, get a prompt for username and > password and be able to run simple commands and see some output ? > > This would be very handy for debugging etc. I think you'll find it easier to write a simple Python program and use it as your client. Telnet sends raw bytes back and forth; if you want e.g. the Backspace key to work properly, then you have to implement it yourself *on the server side*. But if you write your own client, you can use raw_input() and then just send a line at a time to the server. More later. ## Jason Orendorff http://www.jorendorff.com/ From killspam at darwinwars.com Wed Mar 27 07:22:06 2002 From: killspam at darwinwars.com (Andrew Brown) Date: Wed, 27 Mar 2002 12:22:06 GMT Subject: win32 problem interacting with word97 Message-ID: I am trying to convert a couple of hundred MS word 97 files to html, and then reformat them into a template. Mostly, this works, but there are some which contain accented letters, and the Word html converter barfs on these in a peculiarly irritating way: it puts up a dialogue box with a message saying "This document contains characters that are not in the current language encoding. To preserve them, choose cancel and select the appropriate language encoding. For multilingual documents, use UTF-8." It is possible to press "OK" or "cancel" or any damn thing if you can see the dialogue box; but my program can't see it, and goes on trying to get word to process the next file until, after about 30 seconds python crashes completely. Only then do I see the dialogue box which has caused the trouble. What I would like to be able to do is to get around this. Since it's not, so far as Word is concerned, an error, no exception appears. So I can't catch it that way. I don't know any way to detect that Word expects input. Is there one? The crudest thing that occurs to me is simply to send an "esc" character (to dismiss the dialogue box) after every file has been processed. But I don't know how to do that, even. Is there some kind of "sendkeys" method? In case it's enlightening, here is the bit of code where everything goes wrong: def visitfile(self,filepath): if string.find(filepath, 'doc')>1: htmfile=os.path.splitext(filepath)[0]+'.htm' print 'htmfile is %s' %htmfile try: self.o.Documents.Add(os.path.abspath(filepath)) self.o.ActiveDocument.SaveAs(os.path.abspath(htmfile),17) self.o.ActiveDocument.Close() except: warning='MS word convert failed ' + str(sys.exc_type) + str\ (sys.exc_value) print 'filepath is %s' %filepath print warning # but there is no exception, so the dialogue box goes unnoticed ..... From jkraska at san.rr.com Wed Mar 13 20:33:28 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 14 Mar 2002 01:33:28 GMT Subject: Question about scientific calculations in Python References: Message-ID: >in Python. Best I think would be a standard module of data structures >(priority queue, doubly-linked lists, stack, etc.) But it hasn't bothered >me enough to go ahead and do it. I have implemented a deque (which safely supports insert on iteration with multiple iterators using a fail-fast protocol), a priority queue (which isn't entirely generalized, I believe it assumes an integer and organizes top for lowest numbers), and a thing that I call a "double vector" which, like vectors with preallocation strategies, supports both preallocation of memory at the head _AND_ the tail, giving it deque-like properties without the support for insert-on-iterate. It's all been reasonably well-tested. I'll gladly contribute all this to a larger collection library if someone wants to organize it. Downsides: the iterators are older and not related to Python's new iterators. It doesn't really matter which container you use as far as performance goes, for routinely-encountered values of N. That's why Python doesn't have anything special like this built in already, actually. C// From kip_macy at yahoo.com Thu Mar 7 01:53:46 2002 From: kip_macy at yahoo.com (Kip Macy) Date: 6 Mar 2002 22:53:46 -0800 Subject: vfork hangs Message-ID: I'm having problems with my python application hanging in vfork with the child never completing the exec. It is hard for me to track it down just by putting a break on vfork because the code is multi-threaded, several thousand lines long, and doesn't hit this right away. I saw it suggested that system is not thread safe on solaris (the platform I'm using). The other thing of note is that a SIGCLD is always received promptly before the vfork hang. From fgeiger at datec.at Wed Mar 6 08:32:35 2002 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 6 Mar 2002 14:32:35 +0100 Subject: [OT] Want to recognize pictures using Python Message-ID: I plan to buy a USB camera (hope, they are not too expensive) to play a bit with image analyzing. Nothing sophisticated, just color recognition: I'd like to be able to tell whether the upper half of a picture has mostly the color green or red or the lower left quarter of an image is mostly blue etc. I'm completely new to this topic, but really would like to do this in Python. Does anyone know of a package capable of providing such services? As said already, preferably for use in Python programs. PIL comes to my mind here. Is PIL the right one to start with in this regard? Thanks and best regards Franz GEIGER From fperez528 at yahoo.com Wed Mar 6 10:54:47 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 06 Mar 2002 15:54:47 +0000 Subject: dynamic loading of modules References: Message-ID: Henry Baumgartl wrote: > Hello all, > > Having recently embarked on my journey into Python land, I would like to > know if there is an elegant solution to the following problem: > > I would like to be able to compound variables that will then form the name > of the particular module to be loaded into the active script. __import__ cheers, f From jcollins at boulder.net Thu Mar 28 11:43:28 2002 From: jcollins at boulder.net (Jeffery D. Collins) Date: Thu, 28 Mar 2002 09:43:28 -0700 Subject: Pippy References: <20020328153333.69176.qmail@web21110.mail.yahoo.com> Message-ID: <3CA34830.4000106@boulder.net> David Brady wrote: > I've been fiddling with Pippy for the past few months, > and I have to say I *LOVE* it. For all its > shortcomings, it's wonderful. > > I notice Pippy has modules declared for palmapps, > palmform, palmevents, etc... do these work? Is there > documentation for them anywhere? I can't find > anything on the endeavors website. Some minimal documentation is embedded in the doc directory of the source distribution. They are not fully developed and may be replaced with better alternatives. I have recieved patches that I plan to integrate into Pippy, but wanted to wait until my sourceforge project was up and running. However, it's been approximately a month since I submitted the application and still haven't heard a word, even after inquiring a week ago (or so). Perhaps I should look to host the project elsewhere. Can anyone suggest an alternative with similar capabilities? Thanks! -- Jeffery Collins (http://www.boulder.net/~jcollins) From joonas at olen.to Sun Mar 10 17:21:13 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Mon, 11 Mar 2002 00:21:13 +0200 Subject: Syntax to catch specific exceptions ? References: <3C8BD227.7D1D5539@vip.fi> Message-ID: <3C8BDC59.AFAA83B7@olen.to> Pekka Niiranen wrote: > > I am trying to find correct python syntax and structure for the > following exceptions > ------------------------ > mypath = os.path.join(os.getcwd(), 'mydirectory', 'mysettings.pxp') > try: > f = open(mypath, "r") > > except "mydirectory does not exists": > try: > create_mydirectory_for_the_next_read() > save_default_values(mypath) > except "no permission to create mydirectory": > do_whatever() > > except "no permission to enter mydirectory": > print "whatever1" > use_defaults() > > except "file mysettings.pxp does not exist": > print "whatever2" > use_defaults() > > except "no permission to open mysettings.pxp": > print "whatever3" > use_defaults() > > ------------------------- > > I can get the error text and number as follows, but how to catch only > "File exists" OSError ? > > try: > ... os.mkdir('e:\\tmp') > except OSError, (errno, strerror): > ... print strerror > ... > File exists How about catching all exceptions and then examining the traceback? - Joonas From peter at norvig.com Sat Mar 23 01:41:15 2002 From: peter at norvig.com (Peter Norvig) Date: 22 Mar 2002 22:41:15 -0800 Subject: New SIG on logic/CLP programming in Python References: <59667b81.0203221433.261c8210@posting.google.com> Message-ID: I have some simple, inefficient CSP code in Python at http://www.norvig.com/python/csp.html Includes fintie domain backtracking search (with optional forward checking, domain ordering, and variable ordering); hill-climbing min-conflicts search; examples from map coloring, n-queens, and the zebra puzzle. -Peter benji_york at cal-na.com (Benji York) wrote in message news:<59667b81.0203221433.261c8210 at posting.google.com>... > nico at aries.logilab.fr (Nicolas Chauvat) wrote in message news:... > > I'd like to entertain you with a new subject: logic programming and > > constraint-propagation features in Python. > > I would be very interested in a finite domain constraint slover > in/connected-to Python. > > though-not-volunteering-to-implement-it--ly y'rs > > Benji York From marduk at python.net Mon Mar 18 11:04:38 2002 From: marduk at python.net (marduk) Date: 18 Mar 2002 10:04:38 -0600 Subject: Relieved but disappointed: The Pariah thread In-Reply-To: <5l2c9usr5q536u9ki0vc38jlu6oud859sj@4ax.com> References: <5l2c9usr5q536u9ki0vc38jlu6oud859sj@4ax.com> Message-ID: <1016467478.18470.38.camel@ahopkins> LOL On Mon, 2002-03-18 at 09:48, Dale Strickland-Clark wrote: [...] > This easily the most humourless, anal-retentive group I read. > > The most daring humour you are likely to get away with is a bit of > clearly labelled sarcasm. > > Or, for a real belly laugh, string a bunch of words together with > hyphens and add '-ly yours' on the end. > > I gave up ages ago. > -- > Dale Strickland-Clark > Riverhall Systems Ltd Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From dale at riverhall.NOTHANKS.co.uk Sat Mar 23 06:54:59 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 23 Mar 2002 11:54:59 +0000 Subject: The IDE is important too [was Develop-test-debug cycle] References: Message-ID: Paul Magwene wrote: >i.e. What can YOU do for ME today?! Sure, there's lots of gee-whizness >we'd all love to see in Python IDEs, but since I ain't payin' for it I try >not to moan too much about it. Thats a daft response and barely worth the time to reply but as it's a Saturday and I'm feeling chilled out I'll spell it out to you... I'm sure most PEPs originate from users asking for new features. The language is unlikely to evolve without suggestions such as these. I know that my experiences are not unique. I'm not suggesting anything that wouldn't benefit the language in general. >Since it's open source why don't YOU implement the cool ideas you've >suggested, submit 'em back to the community, and WE can all be four times >more productive? I'd love to have the time but I'm spending it all in the develop-test-debug cycle at the moment. -- Dale Strickland-Clark Riverhall Systems Ltd From lbut at stny.rr.com Sun Mar 17 10:21:19 2002 From: lbut at stny.rr.com (Les Button) Date: Sun, 17 Mar 2002 15:21:19 GMT Subject: Problem using pexports & Cygwin to build Python 2.2 extension modules Message-ID: Hello, I have been trying unsuccessfully to use Cygwin/gcc to build Python extensions for native Windows Python 2.2 on Windows XP. I followed the general outline at http://python.sourceforge.net/devel-docs/inst/non-ms-compilers.html Summary of problem (whether I use distutils, or just try to "do it by hand"): I get a linker failure, from undefined references to "libpython22_a_iname" and "_nm___Py_NoneStruct". Has anyone else had success building an extension module with Windows Python 2.2 and Cygwin/gcc? Thanks, --Les Button lbut at stny.rr.com P.S. I also had a problem with "Python.h" needing to have definitions of SIZEOF_INT and SIZEOF_LONG; these apparently didn't get defined properly (for Cygwin/gcc) in "pyconfig.h"?? I fixed for now by providing #define's for these two, before the #include "Python.h" -- I don't see why this should be related to the linker failure. pexports version 0.43 dlltool version 2.11.92 20011001 gcc version 2.95.3-5 Windows Python 2.2 Windows XP (home edition) ******** Attempted build: ********* $ ./pexports python22.dll > python22.def $ dlltool --dllname python22.dll --def python22.def --output-lib=libpython22.a $ cp libpython22.a /cygdrive/c/Python22/libs $ python setup.py build --compiler=cygwin running build running build_ext building 'pr_int' extension creating build creating build\temp.win32-2.2 creating build\temp.win32-2.2\Release C:\cygwin\bin\gcc.exe -mcygwin -mdll -O -Wall -Ic:\Python22\include -c pr_int.c -o build\temp.win32-2.2\Release\pr_int.o writing build\temp.win32-2.2\Release\pr_int.def creating build\lib.win32-2.2 C:\cygwin\bin\gcc.exe -mcygwin -mdll -static -s build\temp.win32-2.2\Release\pr_ int.o build\temp.win32-2.2\Release\pr_int.def -Lc:\Python22\libs -lpython22 -o b uild\lib.win32-2.2\pr_int.pyd Warning: resolving __Py_NoneStruct by linking to __imp___Py_NoneStruct (auto-imp ort) fu000001.o(.idata$3+0xc): undefined reference to `libpython22_a_iname' fu000002.o(.idata$3+0xc): undefined reference to `libpython22_a_iname' nmth000000.o(.idata$4+0x0): undefined reference to `_nm___Py_NoneStruct' collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 ******** setup.py: ********* import sys from distutils.core import setup from distutils.extension import Extension setup ( name = "pr_int", ext_modules = [Extension( name="pr_int", sources = [ "pr_int.c" ] )], ) From krissepu at vip.fi Mon Mar 11 02:55:17 2002 From: krissepu at vip.fi (pekka niiranen) Date: Mon, 11 Mar 2002 07:55:17 GMT Subject: Syntax to catch specific exceptions ? References: <3C8BD227.7D1D5539@vip.fi> <6vQi8.24234$n4.4716288@newsc.telia.net> Message-ID: <3C8C6315.9020805@vip.fi> Thanks Fredrik, So I will end up writing function with a huge "if-else"-structure under except -clause that catches all cases I want react to? Sounds like C. Perkele ;) By the way, have you had time to consider re.findallX -function that does not return empty matches ? -pekka- Fredrik Lundh wrote: >Pekka Niiranen wrote: > >>I can get the error text and number as follows, but how to catch only >>"File exists" OSError ? >> >>try: >>... os.mkdir('e:\\tmp') >>except OSError, (errno, strerror): >>... print strerror >>... >>File exists >> > >catch it, check the errno attribute, and raise it again >if it's not the right error: > >import os, errno > >try: > os.mkdir(somedir) >except OSError, v: > if v.errno != errno.EEXIST: > raise > # directory exists > >alternatively, you can use os.path.isdir to check if the >directory exists before you call mkdir. > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From concordeking at yahoo.com Tue Mar 5 16:30:39 2002 From: concordeking at yahoo.com (concordeking at yahoo.com) Date: 5 Mar 2002 21:30:39 -0000 Subject: Hello Entrepreneur Message-ID: <20020305213039.498.qmail@idhost> Entrepreneur, you submitted your details on the internet as someone interested in starting a business from home. Well, this is what I have to offer: Everybody who enters into the program works in a team-building relationship, so we're all helping to make each other successful. That's how I've been able to make money so quickly.....MY TEAM did it. This is incredible! Go look at our team's website. It explains everything: http://www.concordegroup.net/ (ID# 154257) If you decide to join us, our team will be working for you, too. It's a no-brainer. Yours sincerely Christo --- To remove yourself from further mailings, visit this webpage: http://GetResponse.com/r.cgi?a=christo&e=python-list_Xycwi.nl&i=0 From ianb at colorstudy.com Thu Mar 21 19:17:38 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 21 Mar 2002 18:17:38 -0600 Subject: Python embedded like PHP In-Reply-To: <20020321235029.B66B438F4C@coffee.object-craft.com.au> References: <20020321235029.B66B438F4C@coffee.object-craft.com.au> Message-ID: <1016756258.554.46.camel@localhost> On Thu, 2002-03-21 at 17:50, Andrew McNamara wrote: > > > > Albatross encourages (but doesn't enforce) the separation of presentation > > > and logic. You might do something like this in Albatross: > > > > > >
      > > > > > >
    • > > >
      > > >
    > > > > Why, oh why, does it use HTML-like syntax? People keep implementing > > templating languages that do this over and over, and it's a bad, bad > > idea. Any moderately complex example of templating will violate the > > rules of HTML/SGML, with things like ">, which is horrible to read, will anger WYSIWYG > > editors to no end, and isn't at all necessary. > > The intention is that Albatross templates be valid XML - while Albatross > will do the expected thing in the example you give above, it generally > provides a "better" way, such as: > > Do you mean that you have a template tag for every kind of tag for which you would want to modify an attribute? That's every single HTML tag -- IMG is hardly the only one. A dynamic CSS class attribute, for instance, or events (onMouseOver, etc), id tags, background colors... there's a million possibilities. Plus you've got the same problems ZPT has, where it's not really proper -- or perhaps even possible -- to dynamically generate CSS or Javascript with your language, since they are generally guarded by comments and are thus opaque to XML. XML just seems so darn *hard*. Ian From skip at pobox.com Wed Mar 27 16:01:56 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Mar 2002 15:01:56 -0600 Subject: The Python Way In-Reply-To: References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: <15522.13124.505385.871392@beluga.mojam.com> Joel> In C++ it's common to have a wrapper class that acquires the lock Joel> in the ctor and releases it in the dtor, then allocating an object Joel> of that class on the stack local to the function. Is there a Joel> Pythonesque version of the same design pattern? Yeah, it's pretty easily doable, but it assumes the granularity of the lock is appropriately a whole function, or that only a single lock needs acquiring, or that you don't need to release and reacquire the lock sometime in the middle, or that you are willing to artificially break up a function that needs to use the lock into pieces that can acquire the lock upon entry and release it upon exit ... Joel> class A: Joel> def fn(self,x): Joel> pass Joel> class B(A): Joel> def fn(self,x): Joel> lock.acquire() Joel> try: Joel> A.fn(self,x) Joel> finally: Joel> lock.release() Joel> Or is this considered poor form? That's fine form, subject to the considerations I mentioned above. I have a decent-sized XML-RPC server (about 4000 lines) that was single-threaded until about a year ago. Most of the effort necessary to make it multi-threaded was to lock various data structures. I settled on four threading.RLock objects and two Queue.Queue objects. Amazingly enough, I don't recall having any deadlocks or corrupt data. (Using Queue.Queue in the right places probably helped there.) Looking back at the code now, most of the lock acquisition occurs for a single lock which is protecting 12 separate small caches. My code that looks like self.cache_lock.acquire() try: fiddle_some_cache... finally: self.cache_lock.release() would look a lot cleaner if I simply dumped the threading.RLock objects altogether and used Queue.Queue objects holding the cache: some_cache = self.some_cache_queue.get() fiddle_some_cache... self.some_cache_queue.put(some_cache) Aahz is always admonishing us to just use Queue.Queue. Maybe it's time I paid a bit closer attention to what he's been saying... someday-i'll-learn-ly, y'rs, -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From stephen at xemacs.org Thu Mar 7 21:35:39 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 08 Mar 2002 11:35:39 +0900 Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> <20020307035851.GA23955@isis.gerrietts.net> <3C87C057.4040902@sympatico.ca> Message-ID: <873czbokg4.fsf@xemacs.org> >>>>> "Ramkumar" == Ramkumar Kashyap writes: Ramkumar> My original intent for starting the thread was because I Ramkumar> truly believe in CP4E. I used to. Then I started doing I18N. Then I didn't. Computers and humans communicate with other entities in very different ways. CUse4E is a different matter. You _can_ program computers to do a damn good job of translating a human's idea of "precise description" into something that can be used to efficiently query a database. But at that point the human is no longer engaged in programming. A human dependent on that level of cooperation is not capable of fixing what's broke. My 2-1/2 year old daughter was quite capable of drawing on the screen with the mouse, and was good enough to learn to click the "close" button once she figured out that made Daddy really proud. (Now that she's 4-1/2 she's into Lego and makeup. Go figure.... But she still turns off the TV when she leaves the room.) Programmer? Uh-uh. Not even Grandma will claim that. Ramkumar> The point I want to make is that there are programs like Ramkumar> Hooked-on-Phonics, and other remedial language programs Ramkumar> that are quite effective in raising the literacy levels Ramkumar> among adults. Which do this precisely by taking all the rigor out, and depending on intuition and subconscious processes. "You know it when you see it"---but you don't know _why_. Problem is, there is no way to guarantee that a trained neural network will be a generalization of the data it was trained on. Japanese education is heavily oriented to imitate-the-teacher learning-by-doing. It shows in their programs (my sample is of course published free software programs and patches to other free software programs; I don't know what the professionals are doing---I do know that it's one field where foreigners are often preferred to natives), and the way they apparently _can_ not convert their patches to forms that would be acceptable in an internationalized application. I don't think this is a biological thing the way the male/female difference seems to be, and probably not even terribly deeply embedded in culture. I don't think it would take much to teach programming to Japanese high school students. But I think that it is evidence that Hooked-on-Python is not going to be a path to CP4E. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From akuchlin at ute.mems-exchange.org Wed Mar 20 11:24:35 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 20 Mar 2002 16:24:35 GMT Subject: Message bug? References: <99dh9us1b4d8r9u7p5ltt41g34vlun4kjj@4ax.com> Message-ID: In article <99dh9us1b4d8r9u7p5ltt41g34vlun4kjj at 4ax.com>, Dale Strickland-Clark wrote: > AttributeError: 'module' object has no attribute 'work' > > I have no module called 'module'. It's printing the type of the offending object: >>> a.foo Traceback (most recent call last): File "", line 1, in ? AttributeError: 'int' object has no attribute 'foo' >>> I suppose the single quotes are a bit confusing; maybe they should just be removed. Classes do better: >>> class C: pass ... >>> c=C() >>> c.foo Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute 'foo' Reasonable. But new-style classes bring the single quotes back: >>> class D(object): pass ... >>> d=D() >>> d.foo Traceback (most recent call last): File "", line 1, in ? AttributeError: 'D' object has no attribute 'foo' >>> --amk From akuchlin at crystal.mems-exchange.org Tue Mar 26 10:03:27 2002 From: akuchlin at crystal.mems-exchange.org (A.M. Kuchling) Date: 26 Mar 2002 15:03:27 GMT Subject: PEP262 - database of installed packages References: Message-ID: In article , Wolfgang Strobl wrote: > ownerdescriptor=GetFileSecurity(filename,OWNER_SECURITY_INFORMATION) > ... owner=ownerdescriptor.GetSecurityDescriptorOwner() > ... ownername=LookupAccountSid(None,owner) > ... return ownername[0] That wouldn't be hard to support on Windows. The question for Windows developers is simply: is it useful to support this? I'll defer to Thomas or Tim on that point. --amk (www.amk.ca) "Ace, have you no sense of occasion?" "No." -- The Doctor and Ace, in "Battlefield" From mwh at python.net Tue Mar 12 05:52:50 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 12 Mar 2002 10:52:50 GMT Subject: PEP 285 bool types References: Message-ID: Robin Becker writes: > Any one know what the effects of introducing the proposed bool type will > be? > > I see it generating large traffic on the dev list, but what will it > really mean and will there be yet another great divide in python > versions? Well, you can bet that the people best qualified to answer that question are currently shouting about it in python-dev. I don't know, I haven't read the thread... Cheers, M. -- 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 matkin at iar.se Thu Mar 14 06:16:36 2002 From: matkin at iar.se (Mats Kindahl) Date: 14 Mar 2002 12:16:36 +0100 Subject: YANRQ (yet another regex question) References: Message-ID: Tim Peters writes: > [Michael George Lerner] > > I have a regular expression that looks vaguely like this: > > > > r = re.compile(r'''(?Pstart)(?P foo)(?Pend)''') > > > > but the middle pattern isn't quite what I want. I know that foo > > will be a string that is seven characters long and contains 'foo' > > surrounded by spaces. That is, it could be any of these: > > > > 'foo ' > > ' foo ' > > ' foo ' > > ' foo ' > > ' foo' > > > > I'd like to rewrite my regular expression to match any of these, > > and I'd really rather not write it all out like this: > > > > (?P(foo | foo | foo | foo | foo|) > > That will also match an empty string (remove the last vertical bar; ditto > the 2nd left paren). > > > Is there some easy way to do this that I've overlooked? > > You already found an easy way . If you ask whether there's an easier > way, the answer is no. Depending on the definition of easy, this is the alternative I would use. r = re.compile(r'(?P(?=.{7}) *foo *)') Of course, your milage may wary. -- Mats Kindahl, IAR Systems, Sweden Any opinions expressed are my own, not my company's. From eppstein at ics.uci.edu Wed Mar 6 22:20:36 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 19:20:36 -0800 Subject: PEP 284, Integer for-loops References: <3C86D7CA.F53189AE@cosc.canterbury.ac.nz> Message-ID: In article <3C86D7CA.F53189AE at cosc.canterbury.ac.nz>, Greg Ewing wrote: > > In your notation how would you do the following? > > > > for x in range(n-1,-1,-2): > > for 0 <= i < n/2: > x = 2*i + 1 > ... Not quite the same, if n is odd. From wealthychef at mac.com Fri Mar 15 13:24:17 2002 From: wealthychef at mac.com (Richard Cook) Date: Fri, 15 Mar 2002 10:24:17 -0800 Subject: readline() blocks after select() says there's data?? In-Reply-To: <3C92294C.19BCF936@acm.org> References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <3C92294C.19BCF936@acm.org> Message-ID: Thanks, good point. the actual problem was I was reversing the first two args to select.select(). D'oh! At 6:03 PM +0100 3/15/02, Sjoerd Mullender wrote: >When select tells you there is something available to read, it doesn't mean >there is a whole line available to read! It is very well possible that there >is only one character available, but readline may want to read (a lot) more >than that. > >Rich Cook wrote: >> >> At 11:09 PM -0600 3/14/02, Skip Montanaro wrote: >> > >> selectables = [theProcess.childerr, theProcess.fromchild] >> > >> (input, output, exc) = select.select([],selectables, >>selectables) >> > ... >> > >> > >> It blocks forever waiting for theProcess.childerr.readline(bufsize) >> > >> to return. I expect it to block waiting for select.select(); that >> > >> would not be a problem. The problem is that select is claiming >> > >> there's stuff to be read, then when I try to read it, >>it's not there! >> > >> How can that be? >> > >> >Based upon the attribute names you are using, I suspect you instantiated >> >os.Popen3 to create theProcess. These are file objects, not sockets. I >> >believe select only blocks on sockets. See the comments about asynchronous >> >file i/o near the bottom of asyncore.py. >> >> I don't really need select to block. I just want it to be accurate. >> If it returns a file object in the list of things which are >> available, why should then readline() block on it? >> -- >> >> -Sincerely, Rich Cook 925-784-3077 >> ******************************************************************* >> Sometimes it is said that man cannot be trusted with the government >> of himself. Can he, then, be trusted with the government of others? >> Thomas Jefferson >> ******************************************************************* > > > > -- > > http://mail.python.org/mailman/listinfo/python-list -- From skip at pobox.com Thu Mar 7 18:33:08 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 17:33:08 -0600 Subject: Problem with cgitb In-Reply-To: <1015541499.1203.12.camel@temp> References: <1015532454.1203.4.camel@temp> <15495.58404.946778.996505@beluga.mojam.com> <1015541499.1203.12.camel@temp> Message-ID: <15495.63668.397647.596660@beluga.mojam.com> Ken> Unfortunately cgitb has a problem when some of the data it outputs Ken> includes HTML, since it does not escape the appropriate bits and so Ken> the browser gets very upset. >> Can you post a bit of the fractured HTML it generates? Ken> I'm reluctant to send attachments to the list, and I'm not sure the Ken> problem is clear unless you see a complete example. If anyone Ken> would like to see an example I will happily email you a 5K tarball Ken> with an example, just send me some email. Ken sent me an example. I tracked the problem down to a version-related bug in pydoc.py. If anyone needs the fix either browse v. 1.58 of pydoc on the CVS repository or send me a note. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From phr-n2002a at nightsong.com Mon Mar 4 15:41:50 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 12:41:50 -0800 Subject: Can Python do this? References: Message-ID: <7xvgccm5f5.fsf@ruckus.brouhaha.com> "Robert Oschler" writes: > Hello, Python newbie here. > > Let's say I'd like to build a method name into a string variable (e.g. > "FuncCall" + "1" to attempt to call "FuncCall1"). Can I then call that > method by somehow having the interpreter evaluate the string variable into a > call to the desired method? (I know this is usually done in a language like > Prolog or Lisp but I'm hoping Python can do it too.) > > If so, can you point me to a good article or example of such that would show > me the relevant Python syntax. x = my_class() # x is an instance of some class method_name = "FuncCall" + "1" # gives "FuncCall1" method = getattr(x, method_name) # find the method method (args) # call the method is preferable to using eval, if method_name is actually defined for my_class. However, if method_name is only defined for some class that my_class inherits from, and not from my_class itself, then this won't work. Anyone know a way to find a method taking inheritance into account? From johnroth at ameritech.net Wed Mar 13 11:48:12 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 13 Mar 2002 11:48:12 -0500 Subject: Why I think range is a wart. References: Message-ID: "Gon?alo Rodrigues" wrote in message news:ltsu8us0qdsj6r8oersrac465589ot644c at 4ax.com... > Some tens (or hundreds - I lost count already) of posts ago, someone > asked what was the wartiness of the range (and by extension, of xrange) > builtin. The question sunked in my brain, and last night it resurfaced > back with an accompanying answer. Actually, the title is just a bait: it > should be named, Why I think the use I make of range is a wart. > > For starters, range (and xrange) is a perfectly sensible, reasonable and > useful buit-in. But the biggest use I make of it is in iterating through > a list, e.g. as in > > for index in range(len(mylist)): > > > and in the body I need to make use of the indexes. I am not > sufficiently qualified to say if this is Pythonic or not, but I find > myself doing this quite often. It happens to me too, mostly when I'm using a sliding window type algorithm, that is, I need to look at two adjacent members of the list. You can't do this easily by iterating through the list; unrolling the first entry and the last entry are a pain. Is there a way of handling this nicely? Somehow I doubt it. John Roth > Gon?alo Rodrigues > > P.S: PEP 279 proposes adding indexed to generators which would "clean" > the above wart. > From martin at v.loewis.de Sun Mar 17 04:00:33 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Mar 2002 10:00:33 +0100 Subject: HP-UX, PyThread_* missing References: <1016327182.366474@cswreg.cos.agilent.com> Message-ID: weeks at vitus.scs.agilent.com (Greg Weeks) writes: > In either case, though, "make test" fails at test_threads with: > > test_thread > *** Termination signal 14 > > That was where I got stuck, and I'm *still* stuck. Does the test also fail if run on its own? I.e. what happens if you do ./python Lib/test/regrtest.py test_thread Also, since you said that threads work fine in 1.5.2 for you, what happens if you run this test in Python 1.5.2? Regards, Martin From bac at OCF.Berkeley.EDU Sat Mar 30 04:39:52 2002 From: bac at OCF.Berkeley.EDU (Brett Cannon) Date: Sat, 30 Mar 2002 01:39:52 -0800 Subject: PEP 285: Adding a bool type In-Reply-To: References: Message-ID: On Sat, 30 Mar 2002, Guido van Rossum wrote: [snip] > 1) Should this PEP be accepted at all. > Personally, I feel no great need for booleans, but it wouldn't hurt to have them either. We all do the usual return 1 if true else return 0 standard on boolean-like methods, so it isn't like they would go unused. But we do have that basic standard going and it is not that much more code to handle. Python has always gone for verbose over shortcuts, and I can easily view booleans as just a shortcut to appease people from other languages. Personally, I would give a +0 vote just because this is a common enough case that a shortcut would be nice. > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) > Return "True". I agree on the strange looking part. Plus we can only bend over backwards so much for compability. I doubt the amount of code that would be broken justifies the strangeness of returning "1". > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). > If this is done, make it Pythonic. If we cared about being like other langauges we wouldn't use Python because of that "funky whitespace mattters stuff" issue. Go with 'True' and 'False'. > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. I agree with this. Thanks to the standard way of representing false as 0 and true as everything else (but almost always as 1), I see no reason to not treat it as such behind the scenes in terms of operations. Allows all of us warped by C to continue to fool ourselves into treating boolean values as ints. > > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. > I say return boolean. This goes back to my view of not worrying about backwards compatibility as much as general correctness and being more Pythonic. This whole thing is in a way saying that we should have had booleans a while back. So why not just do a complete cleanup of the situation and do it right. > Many programmers apparently feel the need for a Boolean type; most > Python documentation contains a bit of an apology for the absence > of a Boolean type. I've seen lots of modules that defined > constants "False=0" and "True=1" (or similar) at the top and used > those. The problem with this is that everybody does it > differently. For example, should you use "FALSE", "false", > "False", "F" or even "f"? And should false be the value zero or > None, or perhaps a truth value of a different type that will print > as "true" or "false"? Adding a standard bool type to the language > resolves those issues. > Consistency is obviously the big draw for this. Since truth can be viewed as anything not 0 or None, it is rather open and not standardized officially. But we all treat 1 as true and 0 or None as false already. Plus if someone feels the need to have the syntactic sugar for True and False, they can do it themselves as mentioned above. But the frequency of this in code, IMO, is frequent enough to warrant at least considering the sugar. Everyone uses booleans in there code in some form. And if having a standardized way of representing them makes maintaining code that much easier, so be it. -Brett C. From mwh at python.net Tue Mar 26 14:19:40 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 26 Mar 2002 19:19:40 +0000 (GMT) Subject: RELEASED: Python 2.2.1c2 Message-ID: We've released a second release candidate for the next bugfix release of Python, 2.2.1. There haven't been many changes since 2.2.1c1, just a few fixes. Note for AIX users: there are still problems with AIX in this release, and there has not been time to repair them without fear of breaking platforms that currently work. Hopefully by the time of the release of 2.2.1 final we will be able to provide a recipe that allows AIX users to build and run Python. Get the scoop (and the files) here: http://www.python.org/2.2.1/ In order to make 2.2.1 a solid release, please help by + Building the release, and running the test suite on your platform. + Running *your* extension modules' and applications' test suites against this release. + Reporting any problems to the bug tracker at sf: http://sourceforge.net/bugs/?group_id=5470 This being a bugfix release, there are no exciting new features -- we just fixed a lot of bugs. For a moderately complete list, please see: http://sourceforge.net/project/shownotes.php?release_id=81373 Feel free to email me the output of "make test", but please check that you are not duplicating effort by reading this page first: http://starship.python.net/crew/mwh/221c2-reports.txt 2.2.1 final will follow "soon". Cheers, The Python development team. From rjk at grauel.com Wed Mar 20 20:52:39 2002 From: rjk at grauel.com (Richard J Kuhns) Date: 21 Mar 2002 01:52:39 GMT Subject: A question about generators References: Message-ID: David Eppstein writes: > In article , > "Delaney, Timothy" wrote: > > > > I have an application where I think either an iterator or a > > > generator would > > > be ideal, but I have to be able to reset whichever I use. The paper > > > "What's New in Python 2.2" says that there's no way to reset > > > an iterator, > > > so that's out. Is there a straight-forward way to reset a generator, > > > though? > > > > That's not actually correct. There is no general way to reset and iterator > > or generator, but you can make a custom iterator or generator that can be > > reset. > > You could create the generator inside some larger scope, and communicate > with it by changing variables in that scope. Ok, actually it's not > possible to change a variable from outside that variable's scope (why??) > but it is possible to have a list or dictionary within a scope and > change one of its cells. > That's pretty much what I ended up doing -- I put a "while 1:" loop around the rest of the code in the generator, and I test a "reset generator" variable after each yield. If it's set, "continue" the while loop. It's kind of nasty-looking, but it seems to work. It's one of those things that won't be used very often, but when I need it I REALLY need it. Thanks for the comments. -- Richard Kuhns rjk at grauel.com PO Box 6249 Tel: (765)477-6000 \ 100 Sawmill Road x319 Lafayette, IN 47903 (800)489-4891 / ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With NINE Servers In California And Texas - The Worlds Uncensored News Source From pete at dexterslab.de Thu Mar 28 19:14:17 2002 From: pete at dexterslab.de (Henning Peters) Date: Fri, 29 Mar 2002 01:14:17 +0100 Subject: chat server Message-ID: hi pythonists, i am planning to write a small chat server that uses select() in python. multiple clients should be able to connect and chat wih each other - like on a normal chatserver, just asynchronous... my current problem is, that i have no clue how to implement the communication between the sockets (a chat message should be directed to all other connected clients). is this possible to implement with select() or should it be better to use the good old fork() each time, a client connects and implement interprocess communication via pipelines or shared memory?! btw: does anybody knows a good documentation about select() and related themes - i've already read http://www.nightmare.com/medusa/programming.html. bye, henning peters From fredrik at pythonware.com Thu Mar 14 03:08:35 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Mar 2002 08:08:35 GMT Subject: Why I think range is a wart. References: Message-ID: <7UYj8.31929$l93.6269941@newsb.telia.net> Daniel Dittmar wrote: > # if whatever contains only refs to mylist [index] > for element in mylist: > > > # if you really need the index > def listIndices (list): > return range (len (list)) > > for index in listIndices (mylist): > note that index = 0 for item in mylist: index += 1 is faster than for index in range(len(mylist)): item = mylist[index] > # my favourite > for index, element in IndexAndElement (mylist): > you might prefer that one, but it's perfectly possible that your users might be a bit happier if you used the += variant... From peter at engcorp.com Fri Mar 29 23:29:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 23:29:18 -0500 Subject: execfile() - change python version? References: <3CA53165.E3A765A4@engcorp.com> Message-ID: <3CA53F1E.C1DA8B56@engcorp.com> Trung Hoang wrote: > > running the following set of commands in a script: > import xml.dom.minidom > dom = xml.dom.minidom.parseString(somexmlstr) > > using the above in python2.1 from my account: WORKS > using the above in python2.1 from the web: WORKS > using the above in python2.2 from my account : WORKS > using the above in python2.2 from the web : FAILS! > > so im forced to used 2.1 because of xml libraries > #!/local/usr/bin/python > as aposed to > #!/local/usr/bin/python2.2 > > it probably does not work because of some environmental > variable not being set, which when run from the web > fails to find the SAX parser.. So run Python 2.2 from your account, import xml, find out where the file is coming from (xml.__file__), and in the script add in something like: import sys sys.path.append(the-path-to-where-the-xml-module-is) -Peter From jason at jorendorff.com Sun Mar 10 21:27:09 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sun, 10 Mar 2002 20:27:09 -0600 Subject: How "expensive" are Exceptions? In-Reply-To: <3c8bf3ef@nntp.server.uni-frankfurt.de> Message-ID: Michael 'Mickey' Lauer wrote: > Hi, given the fact that excpetion handling can be very > expensive in languages like C++ - is python similar in > this aspect? Hi. You already got one good answer on this, but another tack is: *Everything* in Python is *much* slower than the corresponding thing in C++, except * hashtables * strings * programming ;) ...so why worry? What's "very expensive" in C++ is not something you'd worry about in Python. Yet another tack is this: If you look closely at Python's implementation, you'll notice that you're actually paying the cost of exception handling *even when no exception is thrown*. So you might as well use the exception-handling features of the language whenever it seems natural to do so. To understand this, consider that Python is written in C, which doesn't have exceptions. How do you handle errors in C? You check the return value of every function call. This is what Python does, and it's how Python implements exceptions, too. This is the major cost of exception-handling in Python: checking every return value. (Good C++ compilers cleverly avoid this cost; Python doesn't, alas.) Obviously this must be done whether an exception was thrown or not; that's the whole point. ## Jason Orendorff http://www.jorendorff.com/ From martin at v.loewis.de Sun Mar 24 17:19:25 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Mar 2002 23:19:25 +0100 Subject: The OOM-Killer vs. Python References: <3c9e2b5f.9993062@news.t-online.de> Message-ID: gerson.kurz at t-online.de (Gerson Kurz) writes: > Anyway, even though I believe that this is more of a fault of the > Linux Kernel VM quality than the script (the system has been running > fine for months and now two kills in one week - that smells fishy to > me) - how CAN I controll the memory usage for pythons GC? Is there a > way to easily find out in python which memory is allocated at runtime, > and by which objects? If you suspect that you have cyclic garbage, turn on gc.DEBUG_SAVEALL, and inspect gc.garbage. Before doing so, you should inspect gc.garbage alone - it ought to be empty in a long-running program under all cicrcumstances. If you find objects on gc.garbage, you may try to break cycles explicitly when you know you don't need the objects anymore - people take pride in having their long-running scripts work even without gc. If you don't create any cyclic garbage, you can find all container objects with gc.get_objects. If you find that gc.get_objects does not grow longer over time, but your process still consumes more memory, one of your C extensions has a refcounting bug. HTH, Martin From robin at jessikat.fsnet.co.uk Thu Mar 21 19:37:26 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 22 Mar 2002 00:37:26 +0000 Subject: __file__ for relative imports References: Message-ID: In article , Ken Seehof writes >> Robin Becker writes: >> >> > Is there an obvious reason why modules imported from the current >> > directory don't have an absolute pathname for __file__? .... >I keep bumping into that one too. I can't think of any advantage >for the current semantics, so I am submitting a PEP. I didn't see >a bug in sf or an existing PEP, but I might have missed something >so please let me know. Seems like a PEP is more appropriate than >a bug report though. > >I can't think of any reason for it to be difficult to implement. >Seems like the code that assigns to __file__ in the first place >could simply call abspath(), which should give correct results at >load time. Seems like this PEP would probably only require one >line of code. > >- Ken Seehof > good thinking :) I suppose if Bill Goats gets his way then current directory will cease to have a meaning and we'll all be whining about database rows etc mumble whine :( -- Robin Becker From s1500 at nospam.sihope.com Thu Mar 14 11:06:57 2002 From: s1500 at nospam.sihope.com (Spitfire 1500) Date: Thu, 14 Mar 2002 10:06:57 -0600 Subject: (XML) A list of class instances - how do I get them to reference each other? Message-ID: I'm currently trying to bring XML data into a format that Python can maniupulate. For the XML document, I want to have it eventually(thru minidom or the like) parsed over into a list of class instances. Each tag would get its class instance, which could be a specific class for its tag. I was sucessful making a list of class instances, but I want to add attributes to each class such as "parentof" "Nextsibling", "previoussibling', "childof" and so forth. basically, attributes that reference different class instances to represent XML in a linked list. The "root" ement(in this case, it would be ), would be the first item in the list. The question is, how would I go about with the method of referencing each of those class instances in relation to each other? Would I just use the list index # in relation to each other, or is ther something better to represent a unique class instance in the list? Take note, on what I have so far, it's not hooked up to an XML parser yet. I'm just trying to get the stucture down first. Thanks... From sholden at holdenweb.com Thu Mar 28 18:32:02 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 28 Mar 2002 18:32:02 -0500 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <001d01c1d67f$2eb81090$445d4540@Dell2> Message-ID: "Emile van Sebille" wrote in message news:a807qp$ojhct$1 at ID-11957.news.dfncis.de... > "Charl P. Botha" wrote in message > news:slrnaa6uf4.d4j.cpbotha at crabtree.cpbotha.net... > > In article , > > David Ascher wrote: > > > Thanks for all the interest in ActivePython. We hope to not have > these > > > kinds of delays in the future. > > > > Just remember not to split your infinitives in the future. ;) > > > > There is no longer consensus that splitting infinitives is wrong due to > the awkward constructs avoiding it often gives rise to. > Emile's reply reminds me that, when told one should not end a sentence with a preposition, Winston Churchill replied "This is something up with which I will not put". regards Steve From jeff at ccvcorp.com Wed Mar 13 16:24:04 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 13 Mar 2002 13:24:04 -0800 Subject: Newbie Import two coloums of floating point data into python HOWTO References: <7eb201fc.0203110422.1e9c7dec@posting.google.com> Message-ID: <3C8FC373.B8023B63@ccvcorp.com> Andy Gimblett's code should work, but I'd do a few things a bit differently... Andy Gimblett wrote: > lines = input.readlines() > for line in lines: It's also possible to do the readlines() as part of the for loop -- for line in input.readlines(): > if not line.strip(): > # Skip blank line > continue Unnecessary, because split() will accomplish the same ends as well. > (first, second) = line.split() > row = (float(first), float(second)) > results.append(row) These three lines can be replaced with results.append( map(float, line.split() ) ) and it *won't* error if there's not exactly two items in line. The call to map() applies the float() function to each item returned by line.split(), and returns a list, which is then appended to results. Note that this makes results into a list of lists, rather than a list of tuples. If you care, you can nest a call to tuple() between the map() and the append(), like so: results.append( tuple(map(float, line.split()) ) ) This is getting a bit too deeply nested to be easy to read, so it's also reasonable to use a temporary variable to split this one into two lines (simply for legibility): data = map(float, line.split()) results.append(tuple(data)) One can also replace the map() with a list comprehension: data = [float(x) for x in line.split()] or results.append( tuple( [float(x) for x in line.split()] ) ) Of course, as noted, many of these are matters of personal taste. Use or not as you see fit. :) Jeff Shannon Technician/Programmer Credit International From jason at jorendorff.com Sat Mar 9 01:00:35 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sat, 9 Mar 2002 00:00:35 -0600 Subject: instantiating a class In-Reply-To: <3c899c2d@news.cc.umr.edu> Message-ID: > I'm getting an AttributeError saying module lj_connect has no attribute > lj_connect. Probably Python isn't finding the correct lj_connect.py file. In your script, right after you import lj_connect, try print lj_connect.__file__ and see where the bogus module is coming from. Then go move or delete that file, and try again. ## Jason Orendorff http://www.jorendorff.com/ From jgardn at alumni.washington.edu Fri Mar 1 07:13:15 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Fri, 01 Mar 2002 21:13:15 +0900 Subject: Useful, robust shell utilities Message-ID: I tried to use the shutil module... and to tell you the truth, it stinks. Is there an effort to make a robust, useful shutil module that has the equivalent of the unix shell utilities? I think it would be nice to make things like 'grep' even... Here is my wish list. Each of these should implement a significant portion of what the GNU utils do. They should be robust, and give reasonable results, and reasonable exceptions. touch, chmod, chown, chgrp, touch df, du cp, dd, install, mv, rm, shred If there isn't an effort to make this, or if no one has done anything like this yet, I am willing to volunteer some time to do it. It would be really nice if they ended up being compatible with Windows and Macintosh - give them some powerful tools they didn't even know existed! Jonathan From aahz at pythoncraft.com Sat Mar 23 23:28:54 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Mar 2002 23:28:54 -0500 Subject: is there gonna be a Core Python Programming 2e ? References: Message-ID: In article , John Warney wrote: > >I was wondering if there was plans on CPP 2e ? (no its not c++, core >python programming, lol) If so i would ask for a better binding than >what is on CPP. I would even pay more than what the current CPP is at >now. I know that Wes is gearing up to work on the second edition; I'll pass this on to him (he doesn't read c.l.py regularly these days). However, I'll have to note that this is more up to the publisher than the author. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From chaimh at mapleusa.com Sat Mar 23 18:23:47 2002 From: chaimh at mapleusa.com (Chase) Date: Sat, 23 Mar 2002 23:23:47 GMT Subject: MS Sql Server Message-ID: <788n8.60257$bj1.19179906@news02.optonline.net> Hi... Wondering what the most accepted practice is, for communicating to Sql Server Databases. Is it the ODBC module ? mxODBC ? Is there an ADO module ? Any hints/help appreciated. From oleksik at awa.mat.agh.edu.pl Mon Mar 25 10:06:55 2002 From: oleksik at awa.mat.agh.edu.pl (Pawel Oleksik) Date: Mon, 25 Mar 2002 15:06:55 +0000 (UTC) Subject: python 2.1.2, Linux and 'os' library: bug or (bad) feature? References: Message-ID: Fredrik Lundh wrote: > Pawel Oleksik wrote: >> No way! And as I've written above: python 2.1.1, >> 2.1.0, and 2.0.1 work OK. > > can you spot the bug? > [...] > > OK, OK, my previous statement was to categorical. I don't know where the problem has come from. I've found the problem several weeks ago and it was tested on two computers. (Because of it I had to downgrade py to 2.1.1 on every station I worked on.) Unfortunately a system on both of them has been completely 'reorganized', so now I cannot get the configuration from the time the problems had been faced. Additionally, on Friday I downloaded py 212 again to verify my thesis and to give you some snapshots. But now, (un!)fortunately, it works quite well. So, until I found the 'proper' configuration I may be treated here as someone who met the UFO. best regards p.o. From info at yaritomo.net Sun Mar 17 12:00:10 2002 From: info at yaritomo.net (rouge) Date: Mon, 18 Mar 2002 02:00:10 +0900 Subject: !=?ISO-2022-JP?B?GyRCOS05cBsoQg==?=! Message-ID: <0318102020010.379@oemcomputer> ??????? ???????????????????? ?????????????????????? ?http://www.neoxanadu.net/~a_rouge/ ? ???????????????????? ???????????????????????????????????? ????????????????????????????????????? ?http://www.neoxanadu.net/~a_rouge/refuze.html ?????????????????????? ?????????????????? ?---------------------------------------------- SMITH PROVIDE Co,.Ltd 2908 meka st. Ho%&#;,$##&;: ? From aahz at pythoncraft.com Fri Mar 29 19:14:18 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Mar 2002 19:14:18 -0500 Subject: string copying References: <3CA4F5CB.E8961330@engcorp.com> Message-ID: In article <3CA4F5CB.E8961330 at engcorp.com>, Peter Hansen wrote: > >The only one I've been able to think of is the surprisingly >common situation of trying to consume vast quantities of memory >quickly by something like: > >a = [0] * 1000000 >for i in xrange(1000000): > a[i] = 'bigstringsuckinguplotsofmemory' Right, and as you know, the simple way to fix this is: for i in xrange(bignum): a[i] = "bigstringsuckinguplotsofmemory" + str(i) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From marklists at mceahern.com Mon Mar 18 17:07:14 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 18 Mar 2002 16:07:14 -0600 Subject: Initialization of base classes In-Reply-To: <52mc9u0ghanm3bg0ajt8aro58bqce6ki2s@4ax.com> Message-ID: [sorry.antispam at address.net] > On pp 74 of Bealey's excellent book "Python Essential Reference, 2nd > Ed" it is written: > > "When an instance is created [of a derived class], the __init__() > methods of base classes are not invoked. Thus, it's up to a derived > class to perform the proper initialization of its base classes, if > necessary" > > Is this really true? Consider this, though: >>> class A: ... def __init__(self): ... print "A" ... >>> class B: ... def __init__(self): ... print "B" ... >>> class C(A): ... def __init__(self): ... pass ... >>> class D(A, B): ... def __init__(self): ... pass ... >>> w = A() A >>> x = B() B >>> y = C() >>> z = D() This seems to be the scenario the book is describing: If the derived class defines __init__(), the base classes' __init__()s will not get called unless you call them explicitly. Cheers, // mark From martin at v.loewis.de Sat Mar 2 08:12:20 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Mar 2002 14:12:20 +0100 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: "Neil Hodgson" writes: > How do you tell Python to treat stdout as a tty even though it is > actually a pipe? I'd like to run Unicode printing programs from within SciTE > with I/O redirected to SciTE's output pane. There is also an issue with > stdin where I'd like to tell Python to treat redirected input, fed through a > pipe, as a tty. If stdout is a pipe, you cannot use the WriteConsoleW API for output, I believe. So you *have* to perform some encoding, and unless you can find a good reason to use a different one, the system default encoding would be used. In general, I see the usability to print Unicode only for the interpreter prompt. In all other cases (including cases where output goes to a pipe), the application should explicitly use some codec. That would normally be the codec for the locale's encoding, something that is roughly determined as if system is windows: terminal_encoding = "mbcs" # (1) elif have_nl_langinfo and have_CODEPAGE: terminal_encoding = locale.nl_langinfo(locale.CODEPAGE) else: terminal_encoding = sys.getdefaultencoding() (1): This is actually incorrect. On the terminal, CP_OEMCP is used, not CP_ACP (what "mbcs" uses). In the MS Console API, there are ways to query and modify the code page of a console, which has no effect if the raster font is used. If Python output goes to a pipe, I believe there is *no* way of finding out what the right encoding should be: If the receiving end writes to a text file, ANSI would be right, if the receiving end prints to the console, OEM would be right - unless somebody has changed the console code page for this console. People are so used to characters not showing up correctly in a Windows console that they won't worry if the application picks (1). Regards, Martin From Peter.Gilbert at uwe.ac.uk Mon Mar 4 04:08:16 2002 From: Peter.Gilbert at uwe.ac.uk (Pete Gilbert) Date: Mon, 4 Mar 2002 09:08:16 GMT Subject: Apology to Bill Gates (was Re: ASV module, CVS modules) References: Message-ID: Tim Peters writes: > [John Machin -- maybe] > > my_data.input_from_file("c:\test_data.csv", ASV.CSV(), > > File "C:\PYTHON22\ASV.py", line 222, in input_from_file > > file = open(input_file, "rb") > > IOError: invalid argument: rb > > Bill behaving badly: Seems like Bill chucks a wobbly if there is > > a_bloody_tab_character in a file name. I could be maligning Bill > > unjustly; could be GvR & Co -- I'll have a look at the Python source > > in a minute -- but I'd bet a couple of pots of beer that it's down to > > Bill. > > Under Python 2.2 on Win98SE I get this: > > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> open('c:\test_data.csv', 'rb') > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 2] No such file or directory: 'c:\test_data.csv' > >>> > > Also under 2.1 and 2.0, except under 2.0 the detail reads > > IOError: [Errno 2] No such file or directory: 'c:\011est_data.csv' > > instead. > You must remember to "escape" the backslashes in path names with a backslash, so for the above: ('c:\test_data.csv', 'rb') should read: ('c:\\test_data.csv', 'rb') Hope this helps Pete -- Pete Gilbert UWE, Bristol From sandskyfly at hotmail.com Mon Mar 18 12:10:18 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 18 Mar 2002 09:10:18 -0800 Subject: a text processing problem: are regexpressions necessary? References: Message-ID: Thanks to all who responded... The advice was very helpful and I hope to post a workable implementation when complete. ciao, Sandy From cliechti at gmx.net Sat Mar 30 16:37:49 2002 From: cliechti at gmx.net (Chris Liechti) Date: 30 Mar 2002 22:37:49 +0100 Subject: getting infos from a website References: Message-ID: Zutroi Zatatakowski wrote in news:mailman.1017516408.9897.python-list at python.org: > Geoff Gerrietts wrote: > Ok, I can now get the html source of the page I want. It stores it in > a file: > c = open('c:/python/tester', 'w') you're opening the file for write only. use 'w+' for read-write access. don't forget to use c.seek() to reposition the file pointer if you want to read what you've just written. > f = > urllib.urlopen("http://www.coremud.org/cgi-bin/mycore.pl?stocks=1&font= > Arial") here you get a file like object from which you can retreive the data. e.g "print f.read()" > k = > urllib.urlretrieve("http://www.coremud.org/cgi-bin/mycore.pl?stocks=1&f > ont=Arial", 'tester') this creates a file named "tester" your file opened and bound to c would be in confilct with that file if it were in the same directory so you don't need c. either you use f or k but you don't need both. > c.close() > > # But then I'm trying to read the file and it never outputs what I > ask: because urlretrieve created its own file in the current directory. > raw_input('press Return->') > > c = open('c:/python/tester', 'r') > c.read() > > # readline(), read(), etc. don't seem to work because it doesn't > output the 'tester' file. In this example I close then reopen the > file, but even if I do not close it first, it doesn't output. Could it > have something to do with file permission? (even if I'm on windoze - > the 'tester' file in an 'archive' file). > Anyone knows what I am doing wrong? -- Chris From magnus at thinkware.se Tue Mar 19 20:46:07 2002 From: magnus at thinkware.se (Magnus =?ISO-8859-1?Q?Lyck=E5?=) Date: Wed, 20 Mar 2002 02:46:07 +0100 Subject: Can't print national characters in IDLE with Python 2.2.1c1 Message-ID: <3C97E9DF.3070300@thinkware.se> I don't know if something happened with 2.2.1rc1, or with 2.2, since I used 2.1.2 until today, but in IDLE I get: Python 2.2.1c1 (#32, Mar 18 2002, 13:23:09) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> print '???' UnicodeError: ASCII encoding error: ordinal not in range(128) With the command line version of Python on the same machine I get: Python 2.2.1c1 (#32, Mar 18 2002, 13:23:09) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print '???' ??? >>> PythonWin also works as expected, as does IDLE 0.8 on 2.1.2. No error. Can someone explain this? From jason at jorendorff.com Thu Mar 14 07:52:04 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Thu, 14 Mar 2002 06:52:04 -0600 Subject: Question about scientific calculations in Python In-Reply-To: Message-ID: Bengt Richter wrote: > Andrew Dalke wrote: > > ... > > Insertions and deletions are also linear in the length of the list. > > Tim Peters wrote: > > They're linear in the length of the list following the insert/delete > > position. > > Does that mean the whole tail is rebuilt? Is there any instrumentation > left over that logs access patterns? I wonder what real life uses show. It's not a linked list. It's more like a Java or Scheme "vector". The "whole tail" is indeed "rebuilt" but that usually amounts to a single memmove() call. It's crazy fast, but it's still O(N) on the length of the tail. Glue this URL together... http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/py thon/dist/src/Objects/listobject.c?rev=2.103& content-type=text/vnd.viewcvs-markup and check out the source for yourself. ## Jason Orendorff http://www.jorendorff.com/ From loewis at informatik.hu-berlin.de Sun Mar 17 12:59:51 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 17 Mar 2002 18:59:51 +0100 Subject: time out socket References: Message-ID: "Billy Ng" writes: > Would anybody please tell me how time out the socket.connect() if > the host does not exists or is unable to connect, thanks! The connect call will time out eventually on its own, after the operating system's timeout has passed. If you want to shorten the timeout, and you have a Posixish system, you can set an alarm using signal.alarm. Make sure you install a signal handler; it does not need to do anything since the connect will raise EINTR. Regards, Martin From max at alcyone.com Sun Mar 31 14:09:00 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 31 Mar 2002 11:09:00 -0800 Subject: PEP 285: Adding a bool type References: <3CA751EF.10F25F2D@ndh.net> Message-ID: <3CA75ECC.389A0186@alcyone.com> Stefan Schwarzer wrote: > but on the other hand have to keep in mind subtle interactions between > bools and ints. For example, I consider it very unintutive that > "True == 1" should by true but "True == 2" should be false. Why? Implicit conversions seem un-Pythonic, so why would this be unfortunate? When you write (True == 2) you're asking, "Is the value true equal to the integer value 2?" the answer to which is clearly no. Same thing with something like (2 == "2") -- no conversions are going on here so the test is false. > Additionally, the PEP brings some more design ambiguity which I > dislike. Should my function/method return 0, None, - or False, in a > specific case? Seems pretty clear, and it depends on what the function or method is supposed to be computing. If it's an object or lack-of-object, then None. If it's a Boolean, then True or False. If it's an integer, then some integer or 0. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From mixo at beth.uniforum.org.za Tue Mar 19 09:57:33 2002 From: mixo at beth.uniforum.org.za (mixo) Date: Tue, 19 Mar 2002 16:57:33 +0200 Subject: Getopt / matching problem Message-ID: <3C9751DD.1070204@beth.uniforum.org.za> From running the command "python script.py --use=mixo" I get the result [('--user', 'mixo')] Why do I get match? Is there something that I have left out? If I pass "--u", "--us" to script I get the same result? Here is a snippet of the code from "script.py" . . . def options(): """ Parses command line arguments """ try: opts,args=getopt.getopt(sys.argv[1:], 'u:d:h:',['date=','help=','user=']) #the above 2 lines are in one line except: usage() sys.exit(1) if (len(args) >=1): usage() sys.exit(1) date = None user = None print opts for op,val in opts: if op in ("-u","--user"): user=val if op in ("-d","--date"): date=val if op in ("-h","--help"): usage() return [user,date] . . . (user,date) = options() From martin at v.loewis.de Fri Mar 29 11:49:46 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 29 Mar 2002 17:49:46 +0100 Subject: Executing a specific function. References: Message-ID: Michael Saunders writes: > I see that the Python C API provides several interfaces for > compiling and executing Python code. But I don't want to just > execute some Python code I want to call a particular function within > a Python file. How do I call a Python function (from C) in a some > .py file? It depends on whether you already have a argument tuple, or whether you have the arguments as C data. In the former case, use PyObject_Call; in the latter case, use PyObject_CallFunction. Also notice PyObject_CallMethod. HTH, Martin From sjmachin at lexicon.net Sat Mar 9 16:53:31 2002 From: sjmachin at lexicon.net (John Machin) Date: 9 Mar 2002 13:53:31 -0800 Subject: Tokenize a string or split on steroids References: <4lpj8u4nbsoqjf2h4upadti62jh4sf4i59@4ax.com> Message-ID: Fernando Rodr?uez wrote in message news:<4lpj8u4nbsoqjf2h4upadti62jh4sf4i59 at 4ax.com>... > I need to tokenize a string using several separator characters, not just one > as split(). > > For example, I want a function that returns ['one', 'two'] when given the > string '{one}{two}' . > > How can I do this? O:-) re.split() has a plain vanilla flavour and a richer one -- banana split :-) >>> re.split(r'[{}]', '{one}{two}') ['', 'one', '', 'two', ''] >>> re.split(r'([{}])', '{one}{two}') ['', '{', 'one', '}', '', '{', 'two', '}', ''] >>> You may want to handle the "empty" tokens that are returned by zapping them with map(None, your_token_list), or you may want to step through the list applying some higher logic -- this depends on what you are really trying to do. However, let's review your requirements, as your example was a little specific. What output do you want for this input: 'foo{one}bar{two}zot'?? Do you want ['foo', 'one', 'bar', 'two', 'zot']? If so, use re.split. Do you still want ['one', 'two']? If so, use re.findall. For fancier tokenisation (other than for Python source), you will need to go outside the Python distribution e.g. mx.TextTools package. From trentm at ActiveState.com Fri Mar 15 17:23:58 2002 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 15 Mar 2002 14:23:58 -0800 Subject: Windows Installation In-Reply-To: ; from fperez528@yahoo.com on Fri, Mar 15, 2002 at 03:09:44PM +0000 References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: <20020315142358.B9356@ActiveState.com> [Fernando P?rez wrote] > John Roth wrote: > > > > > Putting something into the start menu is dead easy. Just put a > > link to the appropriate file into "c:Windows/Start Menu/Programs" > > Note the blank, and watch your capitalization. Windows is > > flaky about capitalization. > > > > This is only for win9x. Win2k/xp have per-user Start Menu dirs, and their > location must be retrieved from the registry (Def. is C:\documents and > settings\user-name\Start Menu, but it can vary). So to have this be reliable, > there's no way around diving into the pleasures of the registry. Not true. There is a win32api call to get these directories. Mind you, that requires you to have the PyWin32 extensions installed. >>> from win32com.shell import shellcon, shell >>> shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) u'C:\\Documents and Settings\\trentm\\Application Data' >>> shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0) u'C:\\Documents and Settings\\All Users\\Application Data' >>> >>> shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_STARTMENU, 0, 0) u'C:\\Documents and Settings\\All Users\\Start Menu' If you are running on Win9x then you will get different directories appropriate for that version of Windows. See this link for other CSIDL_*'s http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/Shell/reference/enums/csidl.asp Cheers, Trent -- Trent Mick TrentM at ActiveState.com From jim at jim.jim Thu Mar 28 12:47:59 2002 From: jim at jim.jim (jimh) Date: Thu, 28 Mar 2002 09:47:59 -0800 Subject: problems with circular references References: Message-ID: > > > > I will have to think about that one. When a class accesses the > > MessageCatalog, it may be requesting message text from _other_ classes' > > errors. Also, these are often called from cgi scripts, so they are run as > a > > one-shot deal. Also(!), the case of an error is (theoretically) uncommon > > and the MessageCatalog is only instantiated if an error occurs. That way, > > if no error occurs, there is no overhead with importing the > MessageCatalog. > > > Bear in mind that the import will only cause the module to be executed once > no matter how many times it is imported. So importing it may not be as much > of an ovberhead as you imagine (especially since you seem to be happy to > import fifty other modules to make up your program). > > regards > Steve > Just a small comment: during "normal" operation of the program (actually a transient cgi script), only a few of the 50 files are imported. Only when an error occurs (in which case we no longer care about performance) is the MessageCatalog (and the remaining 50 files) imported. Jim From andy at reportlab.com Sun Mar 31 22:28:01 2002 From: andy at reportlab.com (Andy Robinson) Date: Mon, 01 Apr 2002 03:28:01 GMT Subject: The fastest XML parser around Message-ID: ReportLab (www.reportlab.com) are proud to announce the release of pyRXP, the fastest XML parsing toolkit for python, and possibly for any other language anywhere: http://www.reportlab.com/xml/pyrxp.html pyRXP is a wrapper around the excellent RXP parser developed by Richard Tobin at the University of Edinburgh. Our goal is very simple: get an entire XML document into memory, and validated, as quickly and efficiently as possible. You can parse and validate Hamlet in a tenth of a second on a standard PC. pyRXP constructs a tree of tuples in memory with a single API call; the tree is easy to navigate in standard Python code and can be wrapped up with DOM-like 'lazy accessor' nodules. It is standards-compliant and validating, and is at least 30x faster and 6x more memory efficient than the (non-validating) minidom parser in the standard Python distribution. It also comfortably beats the Microsoft and Java (Xerces) parsers in our tests. Enjoy! Andy Robinson CEO/Chief Architect, ReportLab Inc. April 1st 2001 From shalehperry at attbi.com Fri Mar 1 19:35:35 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 01 Mar 2002 16:35:35 -0800 (PST) Subject: string to dictionary In-Reply-To: Message-ID: On 01-Mar-2002 les ander wrote: > Hi, > i have a list of strings like this: > > aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3',...] > > i want to convert this to a dictionary with a_i -> b_i without > using loops (it is trivial to do it with loops) > i tried this > > dict={} > map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList) > > but it complains that "keyword can't be an expression" > can someone please help me get this right? not sure if there is a better way to do this, I just wanted to make what you had work. Use of '=' is not allowed in lambdas. d.setdefault(*string.split(x)) works for me here. Yes it is quite ugly. The *foo syntax causes the tuple that split returns to be flattened into an argument list. This also may not work on 1.5, do not have a copy here to test. From SBrunning at trisystems.co.uk Wed Mar 27 06:05:01 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 27 Mar 2002 11:05:01 -0000 Subject: Newbie: What the 'PEP' means? Message-ID: <31575A892FF6D1118F5800600846864DCBCEC0@intrepid> > From: Petr Prikryl [SMTP:Answer.via.news.please.prikryl at skil.nospam.cz] > Sent: Wednesday, March 27, 2002 10:55 AM > Just curious -- what the acronym PEP with a number means? Python Enhancement Proposal. > P.S.: RTFM expected, but anyway ;-) OK then - RTFM. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From krissepu at vip.fi Fri Mar 29 11:15:06 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Fri, 29 Mar 2002 18:15:06 +0200 Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: <3CA4930A.1AAC4F41@vip.fi> Well, Excel -clone written in wxPython would be cool. -pekka- cruciatuz wrote: > On Fri, Mar 29, 2002 at 10:20:33AM +0000, Fused wrote: > > > Can anyone think of a program that I could build that would actually > > have use to someone (you?)? I'm trained in Delphi, know some Java and > > rudimentary C, so the programs don't need to be newbie-easy ( I like a > > challenge: the greater the challenge, the faster I'll learn ;-) ). > a programming game like realtimebattle, written entirely in python, > would be very cool. > > have a look at: > > http://www.lysator.liu.se/realtimebattle/ > > ... if you're interested > > 2 things: > > - other programmers (newbies like me) can learn functional programming > in python while building own bots (movement algo's etc.) > > - it doens't need to be a "war-game", it can also simulate bots in other > situations (it would be great if there would be a map with different > things on it, and the bot has to move around, climb, swim and so on - > but it has to be programmed before _how_ he should do that and which > parts (item-classes) he should use.) > > - every main part of the bot's body should be a python-object in a main > bot object - these objects will be manipulated while the bot is trying > to solve the map. > > - the bot who is the fastest in solving an arena, will be the winner. From fredrik at pythonware.com Mon Mar 11 14:22:40 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Mar 2002 19:22:40 GMT Subject: lambda question References: <1g6j8.24364$n4.4758442@newsc.telia.net> Message-ID: <4u7j8.24389$n4.4764765@newsc.telia.net> Fredrik Lundh wrote: > if so, the following should do the trick: > > def exe1(f,list): > return map(lambda x,list=list:eval(f),list) doh. should of course be: def exe1(f,list): return map(lambda x,f=f:eval(f), list) From usenet at thinkspot.net Wed Mar 20 14:21:43 2002 From: usenet at thinkspot.net (Sheila King) Date: Wed, 20 Mar 2002 11:21:43 -0800 Subject: Remove empty lines References: Message-ID: On Wed, 20 Mar 2002 10:33:55 -0800, "Nick Arnett" wrote in comp.lang.python in article : > The problem is here, I think. Split in Python appears to return the > separator, so the '\n' characters are still there. If that's the problem, > this should fix it. > > if line == '\n': > > At least, that's my suspicion, without testing. (In Perl, the separators > are not returned by default, so if you came to Python from Perl, like me, > this is confusing.) Here is what happens: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> mystring = 'Hello.\n\nHow are you today?\nFine, thanks.\n\n\nSee ya!' >>> mylist = mystring.split('\n') >>> mylist ['Hello.', '', 'How are you today?', 'Fine, thanks.', '', '', 'See ya!'] >>> mylist = filter(None, mylist) >>> mylist ['Hello.', 'How are you today?', 'Fine, thanks.', 'See ya!'] >>> It doesn't return the separator, however, it does return empty strings between consecutive occurrences of the separator. One option for removing them, is the filter function. Or, you could use list comprehensions: >>> >>> mystring 'Hello.\n\nHow are you today?\nFine, thanks.\n\n\nSee ya!' >>> mystring.split('\n') ['Hello.', '', 'How are you today?', 'Fine, thanks.', '', '', 'See ya!'] >>> mylist = [part for part in mystring.split('\n') if part] >>> mylist ['Hello.', 'How are you today?', 'Fine, thanks.', 'See ya!'] >>> -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sam_collett at lycos.co.uk Mon Mar 4 07:31:54 2002 From: sam_collett at lycos.co.uk (Sam Collett) Date: 4 Mar 2002 04:31:54 -0800 Subject: File Attributes conversion Message-ID: <2030665d.0203040431.1279d1ab@posting.google.com> I can get file attributes using os.path.getsize and os.path.getmtime etc, but I am not sure how to convert them into something more understandable e.g. File Size to display in bytes (if < 3kb), kilobytes (if < 2MB) and megabytes (> 2MB). How would you do that (the value I get is 12345L - what is the L?) Modified/Created time to be displayed as GMT (DD mm YYYY, HH MM am/pm) 14/09/2002, 5:54pm (is it in seconds currently [starting from which year]?) I am doing this on Windows 98SE, is it possible to get the code to work cross platform as well? TIA PS Can you also get other attributes (read-only, hidden, compressed, system, archive, etc)? From erno-news at erno.iki.fi Sun Mar 24 13:24:35 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 24 Mar 2002 20:24:35 +0200 Subject: Memory sizes of python objects? References: <3C9E06A0.EC4D51E3@engcorp.com> Message-ID: In article <3C9E06A0.EC4D51E3 at engcorp.com>, Peter Hansen writes: | Erno Kuusela wrote: || || In article , "Clark C || . Evans" writes: || || | Is there some rule of thumb that I can use to estimate, || | for example, take the character data you have and multiply by || | a factor of 4 to find the in-memory footprint of tuples, and || | each map is 1K plus 64 bytes per entry.. || || make a zillion of them, check memory usage increase with ps (or || equivalent on your platform), and divide by zillion. | Keeping in mind Python's propensity for finding already-existing | entities and binding to them instead of creating new objects. | The difference in memory consumption between creating a list | of size 1,000,000 filled with 0's and the same size list filled | with integers from 0 to 999,999 is rather large... you make it sound more mysterious than it is - only numbers under 100 and identifier-like string literals get interned, afaik. -- erno From aahz at pythoncraft.com Sun Mar 31 09:18:05 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 09:18:05 -0500 Subject: string copying References: <3CA4F5CB.E8961330@engcorp.com> <3CA6ABB6.71786096@engcorp.com> Message-ID: In article <3CA6ABB6.71786096 at engcorp.com>, Peter Hansen wrote: > >Yeah, I know. I think you and Aahz missed my (admittedly puny) >point, which was to hypothesize _at least one case_ where it >was conceivably desirable by someone to try to copy a string. No, I didn't miss your point, I was just chastising you for posting incorrect code without posting a solution. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From robin at jessikat.fsnet.co.uk Mon Mar 4 11:26:50 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 4 Mar 2002 16:26:50 +0000 Subject: Win32 2.2 & 2.1.2 Message-ID: Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the default for a win32 box. It would allow us to dip a toe in the water without drowning. -- Robin Becker From boud at valdyas.org Sun Mar 24 16:18:33 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sun, 24 Mar 2002 20:18:33 -0100 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> Message-ID: <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> Peter Hansen wrote: > holger at trillke.net wrote: >> >> > >how could you stop a running threading.Thread from the *outside*? of >> > >course i could introduce some kind of flag into the event loop of the >> > >Thread.run-method, but i really would prefer to have a non-instrusive >> > >way for several reasons. >> > > >> > >Any way to do this? >> > >> > Not really. Why do you want to do it? >> >> You really want to know it? I am currently working >> on (coded) agents which move through the network. > > "The network"? Which one? The Internet, or an internal > network over which you have full control? Who controls > the servers on which these agents will be running? > >> But of course i'd sometimes like to shut down some or >> all agent-threads. > > Run them in a separate process and kill the process when > it's "sometime"? If you can live without individual > control. Maybe you can identify groups of them? > Actually, Holger's problem is very well known to people implementing agents. Agents run within the application, but they don't share objects (not often, anyway), so killing them is safe. But neither in Java nor in Python you can easily kill them. Running each agent in its own process makes the system very costly in terms of resources, makes it necessary for the agents to implement inter-process messaging. Not to mention them showing up individually in _top_... >> Is the questions actually strange in any way? Like something >> you wouldn't usually like to do? > > Yes, that's the case. It's generally considered to lead to > undefined behaviour if you do manage to kill a thread from > the outside, because of resource locking issues and such. > That's the received opinion indeed. It still leads to problems. I mean -- it's why you can kill a process, but not a thread. But in an agent system, every agent (presumably running a thread, although I've implemented systems where agents share threads, cooperative multi-tasking agents) is on its own, and shouldn't own objects or locks. > Maybe you can get by with Stackless Python? The microthreads > provided there ought to be more easily killable, though > I haven't tried it myself. They aren't -- not really. I tried myself. See my article on Stackless at InformIT. -- Boudewijn Rempt | http://www.valdyas.org From phr at localhost.localdomain Tue Mar 5 19:04:54 2002 From: phr at localhost.localdomain (paul rubin) Date: Wed, 06 Mar 2002 00:04:54 GMT Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> <7xzo1om5wt.fsf@ruckus.brouhaha.com> Message-ID: Christian Tismer writes: > Both approaches make sense to me. On systems with no threads > at all, we have only one choice, Paul's, unless we code > something thread-alike for the specific platform. > When real threads are available, the other is more powerful. I like the idea of using microthreads when possible and resorting to OS threads for legacy extensions that do blocking i/o. There should be a way to code new extensions to use nonblocking i/o and let Stackless know that it's ok to call those extensions from microthreads. From nospam at [127.0.0.1] Sat Mar 16 17:19:03 2002 From: nospam at [127.0.0.1] (Chris) Date: Sat, 16 Mar 2002 22:19:03 +0000 Subject: Good book on Python? References: Message-ID: In article , Patrick writes > >"orangefree89" wrote in message >news:slrna9559u.g52.orangefree89 at localhost.localdomain... >> On Fri, 15 Mar 2002 18:37:53 +0000, Chris wrote: >> >> > Thank you. >> > I downloaded number 4. >> > However, it is in a strange form (Tex) for a windows user. >> > Is it any use to me in that form? >> > And can it be obtained in any other form? >> > (It does look good.) >> >> Yassas. I'm pretty sure it is also available in pdf. > >http://www.ibiblio.org/obp/thinkCS.php Thanks - downloading it now. -- Chris From phd at phd.pp.ru Wed Mar 27 09:55:50 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 27 Mar 2002 17:55:50 +0300 Subject: Strange behavior In-Reply-To: <414401922FF9D011BEC600805FEA07E301A865DC@XI0SXJ01>; from TBrixi@CSAS.cz on Wed, Mar 27, 2002 at 03:41:57PM +0100 References: <414401922FF9D011BEC600805FEA07E301A865DC@XI0SXJ01> Message-ID: <20020327175550.F30084@phd.pp.ru> On Wed, Mar 27, 2002 at 03:41:57PM +0100, Brixi Tom?? wrote: > UnicodeError: ASCII encoding error: ordinal not in range(128) http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.102.htp Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From roy at panix.com Tue Mar 12 15:15:46 2002 From: roy at panix.com (Roy Smith) Date: 12 Mar 2002 15:15:46 -0500 Subject: Is Python an object based programming langauge? References: Message-ID: In article , > What does he think of Ruby? He thinks it's pretty cool. To the best of my knowledge, he's never written a single line of code in either Ruby or Python, but he's sure Ruby is a much better language. Funny how that works :-) From peter at engcorp.com Fri Mar 29 19:44:52 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 19:44:52 -0500 Subject: string copying References: <3CA4F5CB.E8961330@engcorp.com> Message-ID: <3CA50A84.BA29BBCE@engcorp.com> Aahz wrote: > > In article <3CA4F5CB.E8961330 at engcorp.com>, > Peter Hansen wrote: > > > >The only one I've been able to think of is the surprisingly > >common situation of trying to consume vast quantities of memory > >quickly by something like: > > > >a = [0] * 1000000 > >for i in xrange(1000000): > > a[i] = 'bigstringsuckinguplotsofmemory' > > Right, and as you know, the simple way to fix this is: > > for i in xrange(bignum): > a[i] = "bigstringsuckinguplotsofmemory" + str(i) ...or add just 'x' instead of str(i). I do know this, but I was searching for ideas as to why one would want strings to be copyable, as three people had just asked ... :) -Peter From Answer.via.news.please.prikryl at skil.nospam.cz Wed Mar 27 05:25:04 2002 From: Answer.via.news.please.prikryl at skil.nospam.cz (Petr Prikryl) Date: Wed, 27 Mar 2002 11:25:04 +0100 Subject: Encoding when building XML via minidom? (...beginner needs advice) Message-ID: Hi gurus, (I am very new to Python and to this group. I did RTFM's, but--you know--it is a lot of information for the Python beginner. Please, be patient with me ;-) Briefly: I want to parse txt files with some internal structure and convert them into well-formed XML internal format (custom markup). I do not know how to deal with windows-1250 input encoding and how to produce the XML output with the same encoding. Motivation: I have just learned the basics of Python. The first thing that I want to try is to rewrite one of my Perl scripts for processing a kind of txt documents into other formats. The main motivation is to enhance the functionality of the utilities and to rewrite them into Python (basicly, to learn the Python better ;). Problem: The txt documents use some formating rules and here-defined markup (not compatible with anything standard, tailored for the purpose). The encoding of the txt documents is windows-1250 and they frequently use characters with code above 128 (Czech texts written in Windows encoding). (It is required to keep unchanged the format, the encoding, and the tools for producing them.) It seems that XML is the right format for generating the intermediate form of the documents, and it also seems that DOM is the right model/apparatus to be used. I tried some simple things with Python's (2.1.1) xml.dom.minidom implementation. I was able to build some simple xml document that contained ASCII texts (just a sequence of dom.createElement(), dom.createTextNode(), elem.appendChild(), and dom.toxml()). I probably need some advice for what is the best way to create my own parser and how to use it with xml.dom.minidom. The main problem is the correct handling of the input encoding with respect to the produced XML. Ideally, the output encoding should remain the same, and the output should start with: Are there some prefered ways of integrating the parser with xml.dom, in Python? Are there some tutorials on how to work with encoding conversions? (Python's DOM works with Unicode internally, doesn't it?) Are there some means to make writing the plain text with indentation easier, in Python? Thanks for you patience and for you help, Petr -- Petr Prikryl (prikrylp at skil dot cz) From dsavitsk at e-coli.net Sat Mar 30 16:10:33 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sat, 30 Mar 2002 21:10:33 GMT Subject: PEP 285: Adding a bool type References: <2zRcLUAVjXp8EwVv@jessikat.fsnet.co.uk> Message-ID: "Robin Becker" wrote in message news:2zRcLUAVjXp8EwVv at jessikat.fsnet.co.uk... > In article , Guido van > Rossum writes > ...... *** > > 1) Should this PEP be accepted at all. > no. If needed implement a library module for those who want to bog down > their code. This will not improve the python interpreter one bit and has > already consumed vast quantities of hot air ie has taken time and effort > away from more important issues. I second this suggestion. The language is good, and the presumption should be not to change it w/o substantial reason. This doesn't seem like there is substantial reason to me. *** > -- > Robin Becker From ralph at inputplus.demon.co.uk Tue Mar 19 13:29:53 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 19 Mar 2002 18:29:53 GMT Subject: Python-2.2.1c1 Build Problems on Linux and AIX. Message-ID: Hi, With Python-2.2.1c1, I find `make test' fails on my old version of Linux/x86 and it fails to build on an also old version of AIX. Should I go straight to SourceForge and fill in bug forms or do people tend to discuss the problems here first? I can see the problem with the AIX build. Linux SIGSEGVs in test_calendar on a call to strftime. Cheers, Ralph. From oliphant at ee.byu.edu Tue Mar 19 17:10:46 2002 From: oliphant at ee.byu.edu (Travis Oliphant) Date: Tue, 19 Mar 2002 17:10:46 -0500 Subject: basic statistics in python In-Reply-To: References: Message-ID: On Sat, 16 Mar 2002, Tim Churches wrote: > > > > this is really embarassing :-) > > > > >>> import win32com.client > > >>> xl = win32com.client.Dispatch('Excel.Application') > > >>> xl.WorksheetFunction.StDev(1,1,1,3,3,45,3,2,1,1,2,3,2,1) > > 11.565627361442019 > > >>> xl.WorksheetFunction.Pearson((1,4,3,2,5),(5,3,2,5,4)) > > -0.48507125007266594 > > Hmm, how about these legacy-free solutions... > > Using Walter Moreira's RPy module ( http://rpy.sourceforge.net ) and R ( > http://www.r-project.org ): > > >>> from rpy import * > >>> r.var((1,1,1,3,3,45,3,2,1,1,2,3,2,1)) ** 0.5 > 11.565627361442019 > >>> r.cor((1,4,3,2,5),(5,3,2,5,4)) > -0.48507125007266594 > > Or using Gary Strangman's stats.py module ( > http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html ): > > >>> from stats import * > >>> stdev((1,1,1,3,3,45,3,2,1,1,2,3,2,1)) > 11.565627361442017 > >>> pearsonr((1,4,3,2,5),(5,3,2,5,4)) > (-0.48507125007266594, 0.40754435760237651) > > Note that stats.py also returns the 2-tailed p-value as well (which can > also easily be obtained from R via RPy). Note, also that this works in SciPy from scipy import * >>> std((1,1,1,3,3,45,3,2,1,1,2,3,2,1)) 11.565627361442017 >>> stats.pearsonr((1,4,3,2,5),(5,3,2,5,4)) (-0.48507125007266594, 0.40754435760237651) The stats module in SciPy (in CVS) is getting quite useful. It calculates current the pdf, cdf, and ppf (inverse cdf) for over 80 continuous distribution functions. Together with Gary's stats.py, the stats sub-package of SciPy is coming along. If you'd like to be part of improving this package go to www.scipy.org and check it out. The 0.1 release is now quite old, so it takes a little willingness to get the package installed (you need a fortran compiler and the atlas libraries). There seem to be lots of people re-inventing the wheel, here. SciPy is trying to be an easy-to-install package that has all the basic, commonly-implemented algorithms as well as tools to help you write your algorithms in a faster, compiled language. Jump on board. Lot's has been done, but lot's remains to be done. The earlier you join us, the more impact you will have. -Travis Oliphant From tim.one at comcast.net Mon Mar 25 00:25:15 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 25 Mar 2002 00:25:15 -0500 Subject: list comprehension question In-Reply-To: <5.1.0.14.2.20020325111055.044fbd08@202.95.131.154> Message-ID: [Tripp Scott] > thanks for the tip. actually, the essence of what i wanted to > ask was: "can that SOMETHING be a list of more than one elements > which will be _flatly_ added to the result list." No. len([f(x) for x in y]) == len(y) whenever no exception occurs, regardless of the form of f() or type of y. > as another example, can i generate this list > > [1,1 2,2,2, 3,3,3,3, 4,4] > > with a list comprehension that contains one 'for' clause? Sure, via the obvious spelling: [i for i in 1,1, 2,2,2, 3,3,3,3, 4,4] Cleverness can't improve one that. simplicity-is-a-feature-ly y'rs - tim From skip at pobox.com Sat Mar 2 13:04:44 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 2 Mar 2002 12:04:44 -0600 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: References: Message-ID: <15489.5180.402637.125675@12-248-41-177.client.attbi.com> Fernando> It's not Python 2.2 itself: Fernando> % python Fernando> Python 2.2 (#1, Feb 10 2002, 13:29:43) Fernando> [GCC 2.95.2 19991024 (release)] on darwin Fernando> Type "help", "copyright", "credits" or "license" for more information. >>>> 1e-200**2 Fernando> 0.0 According to the pow man page on my Mandrake 8.1 system it suggests that ERANGE should be set if its first arg is zero. This appears to happen when x is around 1.5717e-162. I suspect a bug in glibc (I have version 2.2.4). In the region where the problem occurs, Python's float_pow() looks like PyFPE_START_PROTECT("pow", return NULL) ix = pow(iv, iw); PyFPE_END_PROTECT(ix) Py_SET_ERANGE_IF_OVERFLOW(ix); Setting a break immediately after the pow() call shows that ERANGE is set even though it appears to have correctly returned 0. Perhaps if iv < 1, ix == 0, and errno is ERANGE, errno should be cleared, at least for certain versions of glibc? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From hugues103 at voila.fr Tue Mar 12 15:53:27 2002 From: hugues103 at voila.fr (Hugo) Date: Tue, 12 Mar 2002 20:53:27 GMT Subject: serial port communication Message-ID: <3c8e6884.10907140@news.planetis.com> Hi, I try to have a communication between two computers using the serial ports. In the interpretor, I just try these instructions : >>> from os import * >>> fd = open ('/dev/ttyS0', O_RDWR) >>> write (fd, "a") 1 >>> read (fd, 1) and everything stop : the read() instruction is probably waiting for something (I send a character from the other computer but it doesn't work) ? a stop byte ? or I have use a "timeout" thing ? or the termios module ? I don't know ! Thank you for any help. From scarblac at pino.selwerd.nl Fri Mar 8 20:45:47 2002 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 9 Mar 2002 01:45:47 GMT Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: N Becker wrote in comp.lang.python: > def g(): > f() This is the effectively same as g=f ...and therefore probably not what you meant. Try to explain what you need. Remember that the you can pass the function object around without calling it, by just passing its name (f) around, without the (). -- Remco Gerlich From fredrik at pythonware.com Mon Mar 18 17:35:32 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 18 Mar 2002 22:35:32 GMT Subject: XML help References: Message-ID: Vincent Foley wrote: > I have a XML document . > I want to put the latest_version value in a variable. How would I do > that? here's yet another way to do it: from xmltoys.ElementTree import parse tree = parse("vim.xml") project = tree.getroot().find("project") latest_version = project.find("latest_version").text for elem in project: print elem.tag, elem.text download: http://effbot.org/downloads/ overview: http://effbot.org/guides/element-trees.htm From plugin at airtel.net Sun Mar 3 13:43:36 2002 From: plugin at airtel.net (VUG) Date: Sun, 3 Mar 2002 19:43:36 +0100 Subject: C++, Python & Threads Message-ID: <1015181073.276455@seux119> Hi all. I'm modifying Python source code in order to have more control over threads (I need to kill threads without adding controls on them, and it seems not to be posible). I'm modifying the function PyThread_start_new_thread to return de PID of the thread. The modified function is: int PyThread_start_new_thread(void (*func)(void *), void *arg) { long rv; int success = 0; dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident())); if (!initialized) PyThread_init_thread(); rv =_beginthread(func, 0, arg); /* use default stack size */ if (rv != -1) { success = 1; printf("%ld: PyThread_start_new_thread succeeded: %ld\n", PyThread_get_thread_ident(), rv); printf("PID: %d\n", rv); } return success; } When I launch python console and I create a thread I get a NUMBER but...... This number doesn't the same as the one I get by the function thread.get_ident(). What's wrong in the code? Thanks --vug From gh_pythonlist at gmx.de Sun Mar 17 21:16:33 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 18 Mar 2002 03:16:33 +0100 Subject: how to print class names, not references In-Reply-To: <3C9544B5.47CD0918@pop.ntlworld.com> References: <3C9544B5.47CD0918@pop.ntlworld.com> Message-ID: <20020318021633.GA80883@lilith.hqd-internal> * a.clarke11 [2002-03-18 01:36 +0000]: > Hi, > I wrote a function of x, where later in the program x is substituted by > class names. In the function, print x is used, but this returns > <__main__.Player instance at 0x38b1ce90> rather than the plain old class > name that I wanted. > How can I print the name instead? > Thanks for your help, Pythoneers... Quick hint: x.__class__.__name__ Should be in the docs, but I'm too lazy to look it up right now. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 8.1 ?C Wind: 1.2 m/s From mwh at python.net Mon Mar 4 11:17:44 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 4 Mar 2002 16:17:44 GMT Subject: C++, Python & Threads References: <1015181073.276455@seux119> <1015255451.705549@seux119> Message-ID: "VUG" writes: > Ok. Thanks. I've taking a look at Python 2.2 and it works in the way I need. > But I still having problems. I've embedded Python in my application so I > need to modify Python source. I can't find this source in the Python's Home > page. Isnt't the source code for Python 2.2 available? If not, How can I > modify python 1.6.1 source in order to work the way I need? http://www.python.org/ftp/python/2.2/Python-2.2.tgz Found by going to http://www.python.org/2.2 and clicking in the obvious places. -- It's a measure of how much I love Python that I moved to VA, where if things don't work out Guido will buy a plantation and put us to work harvesting peanuts instead. -- Tim Peters, comp.lang.python From gh_pythonlist at gmx.de Fri Mar 8 10:35:47 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 8 Mar 2002 16:35:47 +0100 Subject: Turn string into function call In-Reply-To: <1f5252d4.0203080545.3861adec@posting.google.com> References: <1f5252d4.0203080545.3861adec@posting.google.com> Message-ID: <20020308153546.GC2591@lilith.hqd-internal> Le 08/03/02 ? 05:45, N Becker ?crivit: > What's the best way to turn a string naming a function into a function call? Use a dictionary that maps your commands to the relevant functions, then call the function using the dictionary. This gives the idea (hopefully): def command1func(): print "a" def command2func(): print "b" commands = {'command1': command1func, 'command2': command2func} curcmd = 'command1' if curcmd in commands.keys(): commands['command1']() else: print "illegal command" Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 10.6 ?C Wind: 2.9 m/s From emile at fenx.com Sat Mar 23 14:41:02 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 23 Mar 2002 11:41:02 -0800 Subject: Need help with plotting References: <3c9cd61e.8124286@news> Message-ID: brobbins333 at shaw.ca > I'm new to Python and doing pretty well with it so far. > One thing that has me stumped is finding an "easy" way, > or any way, for that matter, to plot simple graphs. I was really impressed by RPy http://www.cmat.edu.uy/~walterm/rpy Check out Tim Churches' example at http://gestalt-system.sourceforge.net/rpy_demo.html -- Emile van Sebille emile at fenx.com --------- From donn at drizzle.com Wed Mar 13 22:44:58 2002 From: donn at drizzle.com (Donn Cave) Date: Thu, 14 Mar 2002 03:44:58 -0000 Subject: Another socket/thread question References: <3C8FA777.8A5B07D1@accessforall.nl> <7934d084.0203131616.488b4ace@posting.google.com> Message-ID: <1016077491.468764@yasure> Quoth amuys at shortech.com.au (Andrae Muys): ... | Far cleaner to open a control pipe to the thread and have the thread | wait on both the socket and the pipe. This applies equally to | multi-process and multi-threaded models. This has the added advantage | that you can extend the shutdown protocol to do other things such as | request status, stats, or state-changes. Can't argue with that! | One hassle with this might be x-platform semantics, as I believe | windows is broken in this regard. Still I would assume windows can | still do pid/interface restricted tcp or preferably unix domain | sockets, which would allow you to emulate the above. On BeOS, which has I think similar problems, the only option was a TCP socket. So I bound to 127.0.0.1, and closed the bind port after one accept. I think that's acceptable under the circumstances, though it would probably not be an acceptable cross-platform solution - on UNIX, it would be better to use a pipe. Donn Cave, donn at drizzle.com From martin at v.loewis.de Sat Mar 9 17:17:59 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Mar 2002 23:17:59 +0100 Subject: httplib question References: Message-ID: "David McInnis" writes: > I need to write a small client that can access https (SSL) page? Is > this possible with httplib under 2.1? It is possible, but you need SSL support in your socket module. Whether your socket module provides SSL support depends on the platform you are using, and whether SSL support was activated at compile time. Regards, Martin From huaiyu_zhu at yahoo.com Fri Mar 1 23:51:26 2002 From: huaiyu_zhu at yahoo.com (Huaiyu Zhu) Date: Fri, 1 Mar 2002 20:51:26 -0800 (PST) Subject: Python 2.2 seriously crippled for numerical computation? Message-ID: There appears to be a serious bug in Python 2.2 that severely limits its usefulness for numerical computation: # Python 1.5.2 - 2.1 >>> 1e200**2 inf >>> 1e-200**2 0.0 # Python 2.2 >>> 1e-200**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') >>> 1e200**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') This produces the following serious effects: after hours of numerical computation, just as the error is converging to zero, the whole thing suddenly unravels. Note that try/except is completely useless for this purpose. I hope this is unintended behavior and that there is an easy fix. Have any of you experienced this? Huaiyu From arturs at iidea.pl Fri Mar 29 04:05:43 2002 From: arturs at iidea.pl (Artur Skura) Date: Fri, 29 Mar 2002 09:05:43 +0000 (UTC) Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> Message-ID: Sloth wrote: > I've looked at Apache, Xitami, Zope, Medusa, et. al and think they are > wonderful applications. On the other hand, they are overkill for what > I want to be able to do - have Python start a CGI server, serve a > page, get form data, get data from a database, and display dynamic > content. I don't need anything industrial strength, just something > that can handle a single user. Boa. http://sf.net/projects/boa Works perfectly. Easy to setup in a few minutes. Minimal load. If you need to just run Python CGI's, you should be very happy with it. Regards, Artur -- http://www.wolneprogramy.org http://mf.gnome.pl From josephgrossberg at hotmail.com Fri Mar 15 13:13:02 2002 From: josephgrossberg at hotmail.com (Joe Grossberg) Date: 15 Mar 2002 10:13:02 -0800 Subject: syntax question: "<>" and "!=" operators Message-ID: <3dd808a4.0203151013.a37d0c4@posting.google.com> Is there any effective difference between the two? (Sorry if this has already been addressed; it's difficult to search on punctuation.) >>> name = "joe" >>> name <> 'Joe'; name != 'Joe'; name <> 'joe'; name != 'joe' 1 1 0 0 Doesn't this violate the Python principle that " There should be one--and preferably only one--obvious way to do it." if I'm interpreting that correctly? From gimbo at ftech.net Thu Mar 21 05:34:45 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Thu, 21 Mar 2002 10:34:45 +0000 Subject: arrays help In-Reply-To: <000501c1cfb6$495eed80$77c75ed1@umesh> References: <000501c1cfb6$495eed80$77c75ed1@umesh> Message-ID: <20020321103444.GB1667@andy.tynant.ftech.net> On Tue, Mar 19, 2002 at 06:23:55PM -0800, Umesh Persad wrote: > background. I am programming a game and I wanted to > represent a gameboard by a double subscripted array. > How do I do this in Python? Thanks, You could use a dictionary, keyed by a tuple: # empty chessboard: board = {} for x in range(8): for y in range(8): board[(x, y)] = None # start placing pieces: board[(0, 0)] = rook(black) board[(0, 1)] = knight(black) ... for y in range(8): board[(1, 8)] = pawn(black) etc. -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From peter at engcorp.com Thu Mar 7 21:29:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Mar 2002 21:29:18 -0500 Subject: Learning from imperfect lectures References: Message-ID: <3C8821FE.B81C4A5D@engcorp.com> Roman Suzi wrote: > > I do not remember who told me this, but it seems that students > better learn from poorly constructed lectures than perfect ones. > Because, they need to be _active_ in constructing their own system > rather than _passively_ "eat" readymaid knowledge frames. Wow. Deep... I like this (to me) completely new idea. Anyone know where it came from? References to a study or something? Someone I know worked for months (on and off) on a presentation that could have been done (imperfectly) in a week. When it was presented, the reception seemed to me rather luke-warm, in spite of apparently strong interest in the audience ahead of it (and after). The presentation struck me at the time as being _very_ "polished", but perhaps with too little unsaid for someone to question, or think about. I suspect this is the reason why it didn't seem to work. -Peter From rnd at onego.ru Fri Mar 8 02:34:26 2002 From: rnd at onego.ru (Roman Suzi) Date: Fri, 8 Mar 2002 10:34:26 +0300 (MSK) Subject: PEP Parade In-Reply-To: Message-ID: On Fri, 8 Mar 2002, Tim Peters wrote: >Quoting Guido's new "Parade of the PEPs" essay at > > http://www.python.org/doc/essays/pepparade.html Just one comment about PEP 270 - uniq method for list objects - maybe adding dict <-> list conversion functions will make this automatically? But how? Perlishly: dict([1, 2, 3, 4]) -> {1: 2, 3: 4} or some other way: dict([1,2], [3,4]) -> {1:3, 2:4} or dict([(1,2), (3,4)]) -> {1:3, 2:4} (so, dict.items() will be automatically reverse operation) Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Friday, March 08, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "People are always available for work in the past tense." _/ From narnett at mccmedia.com Sun Mar 31 01:52:36 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Sat, 30 Mar 2002 22:52:36 -0800 Subject: Most important extensions? In-Reply-To: Message-ID: Would sgmllib, htmllib and urllib count as two or three? I mention the first two partly because they could benefit from some teaching; I had to stare at examples for a while before I grasped what was going on. All three replaced quite a lot of my old Perl. Does Tkinter/Pmw count as an extension? Don't forget to tell them how easy it is to kick the semicolon habit. Nick > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Aahz > Sent: Saturday, March 30, 2002 7:52 PM > To: python-list at python.org > Subject: Most important extensions? > > > I'm teaching Python for [Perl] Programmers at OSCON this July. I've > already decided to mention mxODBC, NumPy, and PIL, plus PythonPoint (aka > ReportLab) gets a mention on my title page. I'd like this group to vote > on the most important extensions for me to add to this list. Please vote > for no more than three. > -- > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ > > Why is this newsgroup different from all other newsgroups? > -- > http://mail.python.org/mailman/listinfo/python-list From herrn at gmx.net Sat Mar 16 16:02:49 2002 From: herrn at gmx.net (Marco Herrn) Date: Sat, 16 Mar 2002 22:02:49 +0100 Subject: Begginers Guide - Exrcise. Help me, plz! In-Reply-To: References: Message-ID: <20020316210249.GA26813@lurkabove.darkstar> Hi, On Sat, Mar 16, 2002 at 11:45:30PM +0300, Jeffrey-man wrote: > Learning the Begginers Guide, I found an exercise. It tells me: > "Write a program that continually reads in numbers from the user and adds > them together until the sum reaches 100." > Can anybody help me? > > ----- > > sum_stop = 100 > num = input("Please enter the number: ") > > for sum in range(num+num,sum_stop): > print "Now the sum is", num+num > sleep(1) > > print "The sum is >/= 100!" > > ----- > > Maybe I'm doing something wrong? You should tell what exactly your problem is ;) But why so complicated? I would do the following construct: ---/--- >>> sum= 0 >>> sum_stop= 100 >>> while sum < 100: ... num= input("Please enter the number: ") ... sum= sum+num ... print ("The sum is now "), sum ... print "The sum is >/= 100!" ---/--- What is different here is, instead of the for-loop i use a while loop, which seems more appropriate to me, because the programm should go through the loop _until_ 100 is reached. There are some other things that are a bit strange in your code. Maybe you write a mail and explain what you wanted to do in each line. Bye Marco -- Who will take care of the world after you're gone? -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From phr-n2002a at nightsong.com Sat Mar 30 07:51:53 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 30 Mar 2002 04:51:53 -0800 Subject: PEP 285: Adding a bool type References: <2zRcLUAVjXp8EwVv@jessikat.fsnet.co.uk> Message-ID: <7xpu1m43rq.fsf@ruckus.brouhaha.com> "John Roth" writes: > > If we get bools can sets be far behind, and what about quaternions and > > abelian groups? > > I could see sets as part of the core language, if a couple of issues > with respect to notation could be cleared up. I don't see the other > two, but then, I don't really think that complex numbers should have > been part of the core language either. There's a PEP for sets that looks pretty good to me. They look more useful than bools. They actually make some tasks easier. I haven't heard yet how bools make anything easier. > It depends on what can be used by most applications. Sets and > enums are generally useful. Complex, quaternians and so forth > are application specific things. quaternions can be implemented by a module like cmath, if useful. Alternatively they can be represented as 3x3 matrices in Numeric. From duncan at NOSPAMrcp.co.uk Tue Mar 12 04:24:16 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 12 Mar 2002 09:24:16 +0000 (UTC) Subject: NormalDate 1.2 released References: Message-ID: sjmachin at lexicon.net (John Machin) wrote in news:c76ff6fc.0203111907.12122c8b at posting.google.com: > There's even a story that the date of > introduction in Sweden varied by parish! Dont forget that Sweden even had a 30th February one year! -- 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 sasoft at gmx.de Fri Mar 29 11:27:58 2002 From: sasoft at gmx.de (cruciatuz) Date: Fri, 29 Mar 2002 16:27:58 +0000 Subject: Anyone need a program written? In-Reply-To: <3ca43ef4.3666136@news.tudelft.nl> References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: <20020329162758.GA1370@blackscarab> On Fri, Mar 29, 2002 at 10:20:33AM +0000, Fused wrote: > Can anyone think of a program that I could build that would actually > have use to someone (you?)? I'm trained in Delphi, know some Java and > rudimentary C, so the programs don't need to be newbie-easy ( I like a > challenge: the greater the challenge, the faster I'll learn ;-) ). a programming game like realtimebattle, written entirely in python, would be very cool. have a look at: http://www.lysator.liu.se/realtimebattle/ ... if you're interested 2 things: - other programmers (newbies like me) can learn functional programming in python while building own bots (movement algo's etc.) - it doens't need to be a "war-game", it can also simulate bots in other situations (it would be great if there would be a map with different things on it, and the bot has to move around, climb, swim and so on - but it has to be programmed before _how_ he should do that and which parts (item-classes) he should use.) - every main part of the bot's body should be a python-object in a main bot object - these objects will be manipulated while the bot is trying to solve the map. - the bot who is the fastest in solving an arena, will be the winner. From dave at pythonapocrypha.com Fri Mar 29 13:17:23 2002 From: dave at pythonapocrypha.com (Dave Brueck) Date: 29 Mar 2002 10:17:23 -0800 Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: <477762c2.0203291017.1c02cf3b@posting.google.com> I.j.w.Wever at student.tnw.tudelft.nonsense.nonsense.nl (Fused) wrote in message news:<3ca43ef4.3666136 at news.tudelft.nl>... > I'm currently trying to master Python, but to succeed I need to > exercise. However, I detest building programs that have already been > built a kazillion times and aren't of use to anyone. > Can anyone think of a program that I could build that would actually > have use to someone (you?)? I'm trained in Delphi, know some Java and > rudimentary C, so the programs don't need to be newbie-easy ( I like a > challenge: the greater the challenge, the faster I'll learn ;-) ). To each his own, I guess, but IMO the best thing you can do at this point is make something that *has* been done a million times before. The fact that you want to do something unique generally implies non-trivial, and so you'll be confronted with both coming up with a good design and mastering the new language at the same time. It's a bit masochistic and odds are you'll never finish it (which is a shame, since whatever it was was a unique idea - save it for when you know what you're doing and do it right!). For a long time I would write a Tetris clone for each new language or platform I learned. It's a simple game, has an easily-definable scope, is interesting, and gives you a decent set of sub-problems to solve in a bunch of different domains (this would be a lot of fun with Pygame, btw), and once you get the most basic version done you can use it as a stepping stone to more complex problems (local multiplayer, high scores on a central server, network play, custom graphics sets, sound, music, play versus computer, etc.). Starting off with a large and unique project can be discouraging and slow, but if you take the time to learn the language with a simpler project you'll probably get it *and* the killer app project done in less time and have more fun in the process. -Dave From jon+usenet at unequivocal.co.uk Wed Mar 6 18:21:42 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Wed, 06 Mar 2002 23:21:42 -0000 Subject: Python daemon instead of CGI programs References: <88bc63c6.0203061444.30ad9c44@posting.google.com> Message-ID: In article <88bc63c6.0203061444.30ad9c44 at posting.google.com>, Doug Farrell wrote: > One thought that occurred to me was to create a Python daemon that > has a thead pool, a pipe pool and all the CGI functionality built > into classes that could be run by a thread. The FastCGI system already does exactly this. I have made an implementation for Python that you can get at: http://jonpy.sourceforge.net/ From mats at laplaza.org Thu Mar 7 15:46:37 2002 From: mats at laplaza.org (Mats Wichmann) Date: Thu, 07 Mar 2002 20:46:37 GMT Subject: CP4E was Re: Deitel and Deitel Book... References: Message-ID: <3c87cc23.24881687@news.laplaza.org> On Thu, 7 Mar 2002 13:27:20 +0300 (MSK), Roman Suzi wrote: :On Thu, 7 Mar 2002, Simon Brunning wrote: : :> > From: Geoff Gerrietts [SMTP:geoff at gerrietts.net] :> > For the space of around three years, a child is immersed almost :> > constantly, from waking to sleep, and even sometimes while asleep, in :> > language. For those first three years, the child is almost completely :> > incapable of making him or herself understood. : :Are you sure? My daughter makes herself understood by all available :means. She built her own dictionary which we, parents, learned. :What is interesting, she uses (internally) a hash table to :convert from our language to her almost instantly... I have to say, my daughter made herself well understood to the listeners that matters long before speaking an intelligible word. :Our observations tell us that children differ in their ways. E.g. some of :them unthinkingly repeat lots of words and even sentences, while our child :uses only what she understands. Some others do not talk at all and :then at once speak clearly in sentences. : :I guess, adults can also be categorized by their approach in learning :languages. And trial-and-error is, IMHO, also needed to learn computer :languages. I can't imaging someone writing right from the start :after studying docs and specs. There have been several distinct learning styles identified, and unfortunately, one of the shortcomings of schools is that it's impossible to cater to all styles at once. Even within these styles, there are clear variations. Some people only "learn" from reading detailed descriptions, but I believe they're in a minority, and, proficiency still requires application, and particularly trial-and-error learning. :I do not remember who told me this, but it seems that students :better learn from poorly constructed lectures than perfect ones. :Because, they need to be _active_ in constructing their own system :rather than _passively_ "eat" readymaid knowledge frames. I don't know about learning more from poorly constructed lectures; that doesn't jibe with my own experiences, although I see the point being made. The active participation is certainly important, and there are techniques that can be used in a classroom that promote such participation - much harder with a book. I do recall that lectures that had demonstrations that didn't work (I had a Physics professor who always had the experiments fail) were more instructive than the demos that did work, because they did seem to make you think, whereas success was just, "okay, that's what you said, so what?" :So, a bad book (with errors, inconsistencies, etc) is not necessary bad :for learning purposes (if it covers enough of a subject). I think that's a stretch. Bad books have stopped me almost dead on a subject, unless I had a personal reason why I needed to push through. I'm closer to conceding the point on lectures... a classroom situation is by its' nature more interactive, a bad book can stop any interaction. Mats Wichmann From tdelaney at avaya.com Wed Mar 27 18:19:03 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 28 Mar 2002 10:19:03 +1100 Subject: velocity of python,jython,java,jit Message-ID: > From: Xiao-Qin Xia [mailto:xx758 at cam.ac.uk] > > If a python program can be translated into java bytecode by jython, > anybody compared the velocities when run with python, jython, > java, JIT (a > just-in-time compiler, JIT compiles the Java bytecode into > native machine > code on-the-fly)? Try it, and tell us the results. Tim Delaney From parney at metacrawler.com Tue Mar 26 11:20:24 2002 From: parney at metacrawler.com (Parney) Date: 26 Mar 2002 08:20:24 -0800 Subject: I am Tarage your new ruler References: Message-ID: <6d3fe7a3.0203260820.75eed533@posting.google.com> Arsehole! "Tarage" wrote in message news:... > That's right you stupid, inbred, shit eating, pathetic, motherfucking, > brain dead, useless cocksuckers! I'm taking over all of Usenet! There > isn't a fucking thing you can do about it either! You're all a bunch > of worthless scumbags, and now you will all answer to me! If you don't > like this fact TOO FUCKING BAD! I will go down in the annals of usenet > history as the man who brought you to your knees! Now get down on your > knees and pay proper tribute to my glorious self! > > I AM TANAGE! LORD AND HIGH MASTER OF USENET! > > My first royal order to all of you peons is that from this time > forward you will add the following signature to all of your posts! > > > ***** This was posted with the express permission of ***** > ********************************************************** > ****** HIS HIGHNESS Tarage LORD AND MASTER OF USENET ******* > ********************************************************** > *********** We are simple servants of his will *********** > > > This will be appended to the bottom of all your posts with absolutely > NO EXCEPTIONS! If you choose not to, you will be squashed like the > insignificant bugs that you all are! > > I am running Usenet now! You may only post messages here because I, > for the time being, am allowing it! Do you scumbags understand me! > > THIS IS THE DAWNING OF THE AGE OF Tarage! > > ALL HAIL TANAGE! LORD AND HIGH MASTER OF USENET! > > > > Try excusing the fire's lower unit and Ahmad will cover you! Tell > Mohammed it's upper explaining near a farmer. She will dine > thin raindrops on the blank deep square, whilst Ahmed totally > fears them too. The ticket against the think moon is the lemon that > converses easily. > > The tapes, pears, and carpenters are all wide and healthy. Jeremy! You'll > play films. Little by little, I'll irrigate the teacher. Otherwise the > frame in Mahammed's ball might order some urban buckets. > > He might join the weak cobbler and grasp it below its shower. > Plenty of pens will be noisy strange cars. Abdellah cooks the > game at hers and sadly tastes. Do not attack the sauces freely, > clean them locally. Daoud's goldsmith shouts through our coconut after we > arrive with it. All twigs stupidly scold the heavy lake. > > It's very full today, I'll believe biweekly or Ali will measure the > pitchers. > > If you'll creep Byron's kiosk with hens, it'll lovingly behave the > coffee. Do not attempt rigidly while you're moulding among a > sweet pin. Her bandage was closed, long, and kicks to the dorm. He'll be > expecting beneath worthwhile Morris until his dog helps subtly. To be > polite or dirty will like rural jackets to inadvertently hate. They are > recollecting in back of the monument now, won't receive cats later. > She may happily tease dry and moves our dark, weird dryers towards a > cave. Samuel, towards drapers rude and easy, pulls through it, > killing incredibly. > > What did Rose irritate the jug alongside the inner fig? For > Beryl the bowl's rich, before me it's light, whereas inside you it's > talking new. Alejandro, still jumping, answers almost partly, as the > exit pours under their cup. > > We depart them, then we dully change Ollie and Muhammad's cold > jar. Both loving now, Karl and Mohammar seeked the short cellars > beneath bizarre desk. No lean younger can promises lentils at > Atiqullah's empty envelope. There, it fills a grocer too outer > without her quiet bathroom. I was laughing caps to dull Salahuddin, who's > sowing behind the ulcer's evening. > > Where will we climb after Oscar cares the shallow bedroom's diet? > Do not call a floor! You slowly reject towards Brahimi when the > glad enigmas dye before the clean barn. As steadily as Satam > opens, you can walk the orange much more finitely. Other filthy > open walnuts will look generally at codes. Muhammad, have a > unique sticker. You won't nibble it. Just wandering around a > boat behind the hallway is too brave for Pilar to judge it. > It can smell once, solve seemingly, then dream in the onion alongside the > camp. My elder disk won't improve before I comb it. No ugly > wet plates will finally recommend the eggs. He might live undoubtably if > Muhammad's paper isn't sharp. > > If the raw elbows can burn nearly, the humble poultice may learn more > colleges. Who wastes annually, when Eddie sows the abysmal powder > before the obelisk? A lot of cosmetic bushs lift Abbas, and they > weekly irrigate Bert too. Almost no sticky shirts are stupid and other > tired doses are solid, but will Moustapha grasp that? Occasionally, go > mould a ointment! The proud hat rarely pulls Mustapha, it believes > Ramsi instead. > > Some potters laugh, creep, and dine. Others quickly measure. Until > Osama cares the painters partially, Chuck won't like any smart > ladders. If you will cook Jadallah's signal without trees, it will > unbelievably look the weaver. They are climbing at pretty, around > bitter, behind fresh sauces. She might absolutely change beneath > bad hollow halls. Guido lives, then Hassan weakly rejects a > cheap puddle among Mikie's star. She wants to wander clever > carrots within Osama's mirror. Almost no distant yogis alongside the > young ocean were seeking inside the good castle. Many strong > butcher or highway, and she'll simply expect everybody. She'd rather > tease wickedly than open with Sheri's poor ache. I was calling to > behave you some of my blunt kettles. Hardly any angry lazy spoons > badly kick as the old gardners talk. You won't taste me dreaming > within your lost river. Better kill cards now or Wednesday will > weekly depart them towards you. From bfisseni at gmx.de Fri Mar 1 15:04:46 2002 From: bfisseni at gmx.de (Bernhard Fisseni) Date: 1 Mar 2002 20:04:46 GMT Subject: SAX-Parser entity References: Message-ID: Hi, Fabian, > > Ahh, utf-16 sounds good. > Thanks, I have at least one solution: > Reading the xml-file into a buffer and convert it to utf-16. > minidom is then able to parse the whole thing and saves the strings in > unicode, which is fine again. > > I do not understand the part with "If your parser supports...". As it seems > to me, the minidom default parser does not support ISO 8859/1 and even > unicode makes problems only. had you declared ?? > I didn't know, you can reprogram the parser so easily. When I wrote a programme using SAX, I finally used xml.sax.saxutils.escape() def characters(self, content): self._out.write(saxutils.escape(content, self.transhash)) where content means the characters and self.transhash looked like: transhash = { u'\u00c4' : 'Ä', u'\u00c6' : 'Æ', } I suppose, this is not the most elegant way to do it, but it works. Regards, Bernhard > Harvey Thomas wrote: >> I would guess that your document is in ISO 8859/1 (otherwise known as >> latin-1). XML parsers must be able to parse utf-8 and utf-16 and may >> support other encodings. If your parser supports latin-1 then modify the >> XML declaration. Otherwise use the codecs module. > >>> Problem: >>> I try to use the minidom XML-Parser to parse my little file >>> in order to generate HTML Code. >>> Being german, I really like to use Umlauts but minidom does not. >>> ... >>> Traceback (most recent call last): >>> "/usr/lib/python2.0/site-packages/_xmlplus/sax/handler.py", >>> line 38, in fatalError >>> raise exception >>> xml.sax._exceptions.SAXParseException: :29:19: not well-formed >>> >>> where Character 19 in Row 29 is the occurence of an ?. -- Bernhard Fisseni Studi: Steinweg 32 -- 53121 Bonn-Endenich, D -- +49-228-6203949 zu hause: Ubierstrasse 8 -- 53498 Bad Breisig, D -- +49-2633-96333 From shredwheat at attbi.com Thu Mar 7 23:17:55 2002 From: shredwheat at attbi.com (Pete Shinners) Date: Fri, 08 Mar 2002 04:17:55 GMT Subject: ANN: Python User Groups page at python.org References: <2AWh8.478$eT3.149538@news.uswest.net> Message-ID: <3C883D30.1030905@attbi.com> Kevin Altis wrote: > Python User Groups now have their own page on the Python web site: > > http://www.python.org/UserGroups.html sadly nothing ever in the southern california area. anyone in OC or LA who enjoys this crazy python? From martin at v.loewis.de Fri Mar 1 15:34:02 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 21:34:02 +0100 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) writes: > I've been following this discussion with quite some interest, but I do not > have the background to delimit the scope of various concepts. Is there a > gentle introduction to a unicode-newbie? There are a number of introductions to Unicode; you may want to search www.unicode.org, e.g. http://www.unicode.org/unicode/standard/WhatIsUnicode.html > >IMO, the Python source code parser should never see any text data[1] > >that is not UTF-8 encoded. > > Presumably this discussion only concerns unicode strings - I don't think > want to lose the ability to read in arbitrary binary data as a raw string. First and foremost, the discussion is only about source code. A byte string should certainly be able to store arbitrary bytes. Under Stephen's proposal, it would indeed not be possible anymore to put arbitrary binary data into source code. > >[1] Ie, Python language or character text. It might be convenient to > >have an octet-string primitive data type, in which you could put > >EUC-encoded Japanese or Java byte codes. > > What's the difference between this and a raw string (a byte sequence) that > you can translate into any other encoding? Arbitrary binary data uses don't have a character set. If they are character data, they should be stored as a character string (which, in Python, is a Unicode string). Regards, Martin From gh_pythonlist at gmx.de Mon Mar 4 19:58:32 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 5 Mar 2002 01:58:32 +0100 Subject: Python standards In-Reply-To: References: Message-ID: <20020305005831.GB8780@lilith.hqd-internal> Le 04/03/02 ? 16:29, Aahz Maruch ?crivit: > CSJedi wrote: > > > >Can someone tell me if Python has proprietary or consensus standards such as > >ANSI? > > Our standard is Guido. That's the short version of the story :) And rereading my previous post, including speling and grammmar erors, I should probably do something else at this time of day. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 1.4 ?C Wind: 0.7 m/s From jcollins at boulder.net Fri Mar 29 14:55:19 2002 From: jcollins at boulder.net (Jeffery D. Collins) Date: Fri, 29 Mar 2002 12:55:19 -0700 Subject: Slice objects. How to apply them to strings? References: <04g9au4kn4dtg92584l12n0ut001c7rb9m@4ax.com> Message-ID: <3CA4C6A7.30804@boulder.net> IIRC, slice objects are intended for use with Numeric arrays. You might try using the __getslice__() method for slicing instead. Dale Strickland-Clark wrote: > Dale Strickland-Clark wrote: > > >>I'm using Python 2.1 here but this still seems to apply on 2.2 >> >>I have a little string-based class which needs to emulate strings for >>most things. This includes slicing. >> >>So I need a __getitem__ magic method. >> >>This will get passed a slice object. >> >>How am I supposed to translate this into a string slice? >> >>This seems to be the tidiest I can come up with and it's a mess: >> >>def __getitem__(self, item): >> if item.step: >> return self.s[item.start: item.stop: item.step] >> if item.start: >> return self.s[item.start: item.stop] >> return self.s[item.stop] >> >>If 'item' is a slice object, shouldn't I just be able to say: >> >> self.s[item] >>? >> >>Wouldn't this be really sensible? >> >>What's worse, is that I can't even do this: >> >>import operator >>operator.getitem(self.s, item) >> >>Somebody please tell me I'm being dim and I've missed something. How >>do you apply a slice object to a sequence? >> >>Thanks >> > > Can anyone shed any light on this for me? > > Thanks. > -- > Dale Strickland-Clark > Riverhall Systems Ltd > -- Jeffery Collins (http://www.boulder.net/~jcollins) From torstenson at no-spam.oti-hsv.com Mon Mar 4 12:56:36 2002 From: torstenson at no-spam.oti-hsv.com (Eric Torstenson) Date: Mon, 4 Mar 2002 11:56:36 -0600 Subject: open() error ---- what am I missing? References: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com> Message-ID: <7vOg8.10828$hK4.4034599@e420r-atl1.usenetserver.com> OK, imported __builtin__ and used __builtin__.open(blah, blah) and got the same result, so I am guessing that is not a matter of function hiding, but some other error that I am just being blind to. The file name is valid and was built using the os.path.join function. The path exists, but the file does not (it shouldn't need to exist ahead of time since it is a write). I have tried all manner of write flags (w, wb, wb+), all of which yield same results. eric "Eric Torstenson" wrote in message news:%6Og8.10755$hK4.4027177 at e420r-atl1.usenetserver.com... > This is really frustrating for me, and was hoping someone could point me in > the right direction. > > I have a class that I use to generate a log. It handles opens, closes and > logging to the file. > > I have another class which does a lot of other stuff, and occassionally > writes messages to the log. > > The program has worked fine, but when after adding a couple of details (none > of which affected the log), I now get: > Traceback (most recent call last): > File "pLog.py", line 10, in __init__ > self.logInit(sFilename) > File "pLog.py", line 14, in logInit > self.fLog=open(filename, mode='w') > IOError: invalid argument: w > > I have read that you can hide built ins by doing: > from some_file import * > if some_file an instance of open() exists in the * > > but I don't have anything like that in my code. > > The weirder thing, is that I can use the log in other scripts. I have even > copied the imports to the test script, and it continues to run without > error. > > Does anyone know how to determine what is hiding the builting open() routine > (file() does the same), or how to explicitly call the builtin.open() > command? I had trouble with this at the very beginning (I'm still very new > to python), but I usually was able to get it worked out. > > thanks, > > eric > > > From pedronis at bluewin.ch Tue Mar 5 19:09:22 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 6 Mar 2002 01:09:22 +0100 Subject: Status of PEP's? References: Message-ID: <3c85612b$1_3@news.bluewin.ch> > > Interesting observation. But actually, we very much chose those forms to > "underline" not to "hide" the fact that numbers are first-class objects in > Smalltalk (as they are also in Python). Yup that's the current Smalltalk cult . But it is not the impression I had reading the Alan Key's paper about the history of Smalltalk. There were all the aspects together: everything as an object as hard-core CS abstraction (like eval and lists and function invokation in lisp), as a natural mapping from the real word in the computer world, and the english-like aspect. My question is about newbies (kids in Alan Key's case), as I said I cannot answer myself, and it seems you can't either . regards, Samuele Pedroni. From sjmachin at lexicon.net Sun Mar 24 16:51:38 2002 From: sjmachin at lexicon.net (John Machin) Date: 24 Mar 2002 13:51:38 -0800 Subject: list comprehension question References: Message-ID: Tripp Scott wrote in message news:... > can i generate this list: > > [1, 1.1, 2, 2.1, 3, 3.1] > > with a list comprehension in a form of this: > > [SOMETHING for x in 1,2,3] > > and without using side effects like this? > > result=[] > [(result.append(x), result.append(x+1.1)) for x in 1,2,3] > > because the latter case is not very elegant to me. > > t This doesn't match exactly what you asked for, but may match what you meant to ask for, and certainly it clearly states what is happening: >>> [i + delta for i in 1, 2, 3 for delta in 0, 0.1] [1, 1.1000000000000001, 2, 2.1000000000000001, 3, 3.1000000000000001] ... and you may in fact have meant to ask for this: >>> [i + delta for i in 1, 2, 3 for delta in 0.0, 0.1] [1.0, 1.1000000000000001, 2.0, 2.1000000000000001, 3.0, 3.1000000000000001] From sumner-nntp5 at forceovermass.com Wed Mar 20 11:33:47 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Wed, 20 Mar 2002 16:33:47 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> <3C984F44.1090001@pobox.com> Message-ID: In article <3C984F44.1090001 at pobox.com>, Ahmed Moustafa wrote: > May I ask you what the scal for your webapp was? (Because MySQL is > related to small to mid-size web applications). Is it the same case with > Python? Python can scale to very large sites. Yahoo! email and Yahoo! maps are written in Python. Substantial parts of Google are done in Python, though they also have a lot of C back there. (MySQL is used by some large sites that don't need ACID properties but do need a fast data store--e.g. slashdot.org) Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From johnroth at ameritech.net Sun Mar 31 07:41:05 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 31 Mar 2002 07:41:05 -0500 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> Message-ID: "Martin v. Loewis" wrote in message news:m3663dnisp.fsf at mira.informatik.hu-berlin.de... > "John Roth" writes: > > > I make it optimistically 180 functions. Given the reasonably > > high quality of the standard library, "return None" almost > > certainly means that the function does not have a return value, > > not that the return value should be treated as False. > > Notice a subtlety, though: In a high-quality library, if the > *function* has no return value, the return statement should be just > "return". I'd always assume that the function would normally return an > object, and that "return None" indicates that no object is available > in this case. A quick glance shows that this indeed seems to be the > case in the majority of the cases. Good point. In that case, the result still isn't logically a boolean - it's at least "True", "False" or "Huh?" John Roth > > Regards, > Martin > From andymac at bullseye.apana.org.au Tue Mar 19 04:58:59 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 19 Mar 2002 19:58:59 +1000 (est) Subject: bug reporting In-Reply-To: Message-ID: On Sun, 17 Mar 2002, Sheila King wrote: > On Sun, 17 Mar 2002 19:41:22 -0500, "Arthur Siegel" > wrote in comp.lang.python in article > : {...} > report after all. It may end up to be a problem in my own code. :/ Bug reports can be closed ;-) Though I'm not sure that SF actually allows anyone other than project developers to do so, a followup that explains that it should be closed with no further action would result in closure with minimum wastage of effort. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From bokr at oz.net Fri Mar 8 16:39:56 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Mar 2002 21:39:56 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> Message-ID: On Fri, 08 Mar 2002 14:45:35 GMT, "Terry Reedy" wrote: > >"Bengt Richter" wrote in message >news:a69lml$b2v$0 at 216.39.172.122... >> On Fri, 08 Mar 2002 15:54:29 +1300, Greg Ewing > wrote: >> >Even something like q'delim' doesn't allow you to >> >easily use completely arbitrary text, because you >> >still have to pick *some* string that doesn't occur >> >in the text. Although you don't have to modify the >> >text, you do have to inspect it in order to choose >> >a suitable delimiter. > >> Unless you choose one with vanishingly small probability >> of being included, like a generated guid. > >This was Guido's intention when he choose triple quotes and I think he >did excellently well. I don't believe I had even seen """ and quite >possibly not ''' ever before learning Python. I do know that I found >""" to be quite jarring, as if I have never seen it before. > Of course, now that Python sources abound, the probability of encountering triple quotes is no longer vanishingly small, so what will Guido do next, if he finds a motivation to do at the next level what he did with triple quotes? >> A smart editor could do this for you. > >A smart editor could also scan for triple quotes in pasted text and >select one that was not found as the enclosing quotes and do the octal >quoting fixup if both were. > True, but on second thought, actually more likely you'd use a separate utility to generate a guid, since it has to go look for nics etc, and just paste it in the editor. VC++ comes with such a utility. My thought of pasting arbitrary binary octets in a quoted context actually potentially involves multiple encodings, though: The encoding of the source, the encoding used by the editor capturing and displaying the source, the encoding used by the editor for the python source, the encoding for its display, the encoding used for python internal representation, and the encoding used for python interactive display, to name a few. (I'd guess MvL has thought more deeply on that than I ;-) The thing that occurs to me is that pasting into a raw-string context might involve a contradiction, even with current Python r'strings': Suppose what you pasted contained a single ^G ('\x07'), what would happen when it came time to render it on the screen? You couldn't do the normal escapes (e.g. \x07), because in the context of r'...' that would be four characters, not one. So how would '\x07' (single character) be represented if it were part of pasted text? I guess I ought to try eval("r'\x07'") and see what happens ;-) >>> eval("r'\x07'") '\x07' >>> list(eval("r'\x07'")) ['\x07'] >>> list("r'\x07'") ['r', "'", '\x07', "'"] >>> list(r'\x07') ['\\', 'x', '0', '7'] Is that correct? Shouldn't the expression r'\x07' return 4 characters as it does if you list them with list(r'\x07')? I.e., shouldn't list(eval("r'\x07'")) return the same as list(r'\x07'), and shouldn't eval("r'\x07'") raise an illegal-representation (bad raw-string syntax) exception? Would someone explain this: >>> eval("list(r'\x07')") ['\x07'] >>> list(r'\x07') ['\\', 'x', '0', '7'] (Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32) also: Python 1.5.2 (#1, May 28 2000, 18:04:10) [GCC egcs-2.91.66 19990314/Linux (egcs - on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> eval("list(r'\x07')") ['\007'] >>> list(r'\x07') ['\\', 'x', '0', '7'] Pretty consistent. What's the difference between direct interactive eval and programmed eval? (I guess we have a new subject ;-) Regards, Bengt Richter From newsfroups at jerf.org Tue Mar 5 19:00:16 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Wed, 06 Mar 2002 00:00:16 GMT Subject: Newbie Python+XML Question References: <3C85597D.D0DD25FE@bellsouth.net> Message-ID: <3C855C28.5080506@jerf.org> Jeff Layton wrote: > class XmlHandler(saxutils.DefultHandler): Try changing that to use saxutils.DefaultHandler , with the "a" in the second syllable of "Def*a*ult". From DavidA at ActiveState.com Sun Mar 31 02:32:19 2002 From: DavidA at ActiveState.com (David Ascher) Date: Sat, 30 Mar 2002 23:32:19 -0800 Subject: ActivePython 2.2 released! References: Message-ID: <3CA6BB83.E7E75099@ActiveState.com> > For 2.1.2: Will there be an update option in the installer? I've installed > many external Python modules, which I do not want to reinstall when updating > from 2.1.1 to 2.1.2, if somehow possible. Hmm. I'll have to check, but I think that you should be able to uninstall 2.1, install 2.1.2 at the same location, and things should "just work". --david ascher From aahz at pythoncraft.com Sat Mar 23 12:44:59 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Mar 2002 12:44:59 -0500 Subject: reload() problems (was Re: mutlifile inheritance problem simplified) References: <9896e047.0203211303.741f695a@posting.google.com> <3C9C0B45.E3C51B0C@hotmail.com> <3C9CAFD2.13FE372D@hotmail.com> Message-ID: In article <3C9CAFD2.13FE372D at hotmail.com>, Marc wrote: > >I'm wondering whether or not this is a bug, which I would report, or >whether I'm doing something incorrectly. I can accept that others >don't use reload much, but it seems that identifying bugs in the >language is good for the language, or identifying known errors in my >usage is good for me. No argument here; that's a good attitude. The problem is that reload() interacts with Python namespaces in peculiar ways (as you're discovering), and even if something isn't a bug, it's quite likely to not function as you'd desire. (I've seen enough about reload() to say this with confidence.) >For myself, I use reload all the time. Here's an example. For my >current task, I'm analysing large data sets (~.01-30 GB), never doing >the same analysis twice. This involves many steps, and a complete >analysis takes alot of time about 20 minutes - 50+ hours. Most of this >is done using old classes that I've written in different files and many >of these inherit from base classes in other files. > >The goal is to write an analysis script and let it run, but, of course, >it rarely works straight away. I run stuff from IDLE. If the analysis >bombs, I can catch the exception and pickup where I left off without >losing what I've already done: IDLE just waits for me to notice the >exception, then using reload, I can modify the classes that caused the >problem, even a base class that I wrote written 4 years ago and is ten >layers deep in an inheritance tree, or using numbered DLLs I can even >modify a C extension on the fly, all without losing anything. Then >just rerun, picking up where I left off. This is great, and I don't >want to give it up. I can't see a reanable way to restart python every >time I have an error. > >Anyway, I know this hasn't revived your interest in reload. I expect >it's use is very task specific. I've found it extremely useful. Seems to me that it would be better/safer to change your architecture so that you can save checkpoints of intermediate processing. I mean, what if your machine just dies (say, power supply failure or a bad disk); do you really want to lose more than two days of work? I bet that if you do this, you'll find many ways of improving your architecture by streamlining and packaging the information flow. This also would allow other opportunities for modifying the processing in the middle of a run (or restarting a run), quite possibly cutting out many hours of processing time. I've changed the Subject: of this thread so that if someone is interested in reload() zie can find it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From marknenadov at winningteam.com Fri Mar 29 17:39:50 2002 From: marknenadov at winningteam.com (Mark Nenadov) Date: Fri, 29 Mar 2002 17:39:50 -0500 Subject: GUI programming References: Message-ID: <20020329.173950.1469262009.25190@d57-36-119.wido3.on.cogeco.ca> In article , "Umesh Persad" wrote: > ------------------ I wanted to have a user > interface where I can draw the game board as well as take in text input > below the board with some text felds and buttons. I see there are many > GUI toolkits available. I am wondering which one should I use (tkinter, > wxpython?) that will be simple enough to get me up and running qiuckly. > Also are there any examples that I can look at? Umesh, I would personally recommend wxPython. I believe that wxPython is more modern and feature rich. It also doesn't depend on another scripting langauge (TCL). Nevertheless, there are some advantages to TkInter. One of them is the fact that it is easier to learn and that it comes with pretty much every distribution of Python. wxPython comes with a nice demo program that demonstrates almost everything you can do with wxPython. Looking at the source of that program was probably the most valuable "documentation" available. I hope that helps you, ~Mark Nenadov (www.freelance-developer.com) From philh at comuno.freeserve.co.uk Thu Mar 14 20:54:11 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 15 Mar 2002 01:54:11 +0000 Subject: Dear Guru, I have added def and it doesnt work Sincerly, F References: Message-ID: On 15 Mar 2002 01:12:23 GMT, Gerhard H?ring wrote: >Oscar wrote in comp.lang.python: >> I have added >> >> def joinsplit = (join(split(lines, '"'), ' ')) >> return joinsplit > >No wonder this doesn't work, as you've apparently haven't made very >much effort to understand what you're doing here. > >Sorry to be so blunt, but you can't write software just by guessing >about the syntax. Really? I do some of the time, when I don't remember it and can't be bothered to look in the manual. >If you want to learn programming in Python, then go >to http://www.python.org/ and head to the newbie page there. > >If you don't want to learn programming, perhaps because it's too much >effort, then the only option is to find somebody to do it for you. The surprising thing is, the rest of his defs are OK. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From tim.one at comcast.net Sat Mar 30 04:45:04 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 04:45:04 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Message-ID: [Guido] >> 5) Should operator.truth(x) return an int or a bool. Tim Peters >> believes it should return an int because it's been documented >> as such. [Ralph Corderoy] > Unlike Tim to produce such a poor reason. Has he been paraphrased a > little too much? Not in Guido's eyes . We don't need 3 equivalent ways to turn an arbitrary expression into a bool ("bool(x)" same-as "not not (x)" same-as "truth(x)"). *Especially* if str(bool) and repr(bool) produce 'True' and 'False', people have a legitimate need to make an arbitrary true/false expression produce 0 and 1 too, if only to preserve 0/1-based true/false output. operator.truth() has always been the best way to do exactly that. Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and "(0, 1)[boolexpr]" reek in comparison. From robin at jessikat.fsnet.co.uk Fri Mar 1 06:57:17 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 11:57:17 +0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7F6765.94A82394@engcorp.com> Message-ID: In article <3C7F6765.94A82394 at engcorp.com>, Peter Hansen writes ..... > >I'm pretty sure the last time I checked the PROGRA~1 convention still >worked on WinNT. Are you sure this doesn't work on Win2K as well? >They're supposed to be the same thing, no? > >-Peter I'm sure it does and I guess that Program Files will always match as it's often the first. On the other hand working with a path name obtained from an execution path there's no guarantee I can always do the correct conversion by assuming ~1, some end up as ~2 etc. Is there a proper way to get the 8.3 name? -- Robin Becker From fperez528 at yahoo.com Tue Mar 12 12:01:16 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 12 Mar 2002 17:01:16 +0000 Subject: Question about scientific calculations in Python References: Message-ID: Martin Kaufmann wrote: > > How do you glue C and Python together? Do you use any of the wrappers > (SWIG, weave etc.) or do you do it the hard way? I just didn't > understand the whole story about these PyObjects. > >>One general comment: The performance killer in many applications like >>this is doing the innermost loop in the interpreted language (Python, >>Matlab, etc).??If?you?can?recast?your?algorithm?as?operations?on >>arrays rather than individual numbers, and your language does the >>implicit loops over the elements efficiently, you typically get 10x or >>so improvements in speed. > > Do you mean the array calculation of NumPy? Yes. A quick example (trivially easy, but shows the point): In [21]: x Out[21]: array([ 0. , 0.34906585, 0.6981317 , 1.04719755, 1.3962634 , 1.74532925, 2.0943951 , 2.44346095, 2.7925268 , 3.14159265]) In [22]: sx = zeros(len(x),'f') # This will be very slow In [23]: for i in range(len(x)): ....: sx[i] = sin(x[i]) ....: # This is very fast: Numeric applies the sin() operation to the whole # x array, but the looping is done in C instead of python. In [24]: sin x -------> sin (x) Out[24]: array([ 0.00000000e+00, 3.42020143e-01, 6.42787610e-01, 8.66025404e-01, 9.84807753e-01, 9.84807753e-01, 8.66025404e-01, 6.42787610e-01, 3.42020143e-01, 1.22460635e-16]) # You can see that the result is identical: In [25]: sx Out[25]: array([ 0.00000000e+00, 3.42020154e-01, 6.42787635e-01, 8.66025388e-01, 9.84807730e-01, 9.84807730e-01, 8.66025388e-01, 6.42787635e-01, 3.42020154e-01, 1.22460635e-16],'f') So again, the morale is: at all costs avoid looping in python in performance-critical parts of the code, once you've reached the optimization stage. In those parts, get creative: weave.blitz, weave.inline, weave.ext_tools, SWIG & friends (SILOON, boost, etc) in order of increasing complexity. Cheers, f From peter at engcorp.com Sun Mar 10 19:50:30 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 19:50:30 -0500 Subject: How to disable assert statements inside a module? References: Message-ID: <3C8BFF56.EC2E6800@engcorp.com> Pearu Peterson wrote: > > Is there a way to disable all assert statements inside a module, > and without calling python with -O switch? > > Why? I have developed a module using lots of assert statements (yes, > they are all relevant). Now when it is finished, I found that > running python with -O switch the speed up is approximately 4 times. I > assume that this is due to disabled assert statements. I don't want to > remove all these assert statements because I might extend this module in > future when they will be handy again for debugging. You might look into the Test-Driven Development approach espoused by Extreme Programming (XP) proponents. Using a proper set of unit tests is probably going to be a better approach than scattering asserts throughout your code like that, and you would benefit from higher performance even without -O, an improved design, and less need to debug at that level when you extend the module. Just a thought, but I've never seen code that had so many relevant assert statements that the program slowed to a quarter normal speed because of them. -Peter From dradul at yahoo.com Sat Mar 16 17:09:53 2002 From: dradul at yahoo.com (P. Alejandro Lopez-Valencia) Date: Sat, 16 Mar 2002 17:09:53 -0500 Subject: HP-UX, PyThread_* missing References: Message-ID: "Martin v. Loewis" escribi? en el mensaje news:m3d6y41e74.fsf at mira.informatik.hu-berlin.de... > "Paul F. Dubois" writes: > > > I am trying to get Python 2.2 to compile on HP-UX B.10.20. I get a set of > > missing externals with names PyThread_something. I need threads so I don't > > want to turn them off. Is there a package I need to install first? Or some > > other hint about what to do? > > If you need threads on HP-UX 10, you may need to write your own thread > package first :-( > > Provide more info: what compiler (bundled - nah, can't be, unbundled, > gcc?); what symbols are missing, etc. > > In any case, the common understanding is that Python does not really > support threads on HP-UX, and probably never will unless some HP-UX > user who understands all the issues provides patches. > Hmmm.... This is a wild shot, but you might want to try out the GNU pth library. If you are lucky, it may work as a wrapper to the OS threads and python may find it usable. From gmcm at hypernet.com Sat Mar 2 07:30:42 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 02 Mar 2002 12:30:42 GMT Subject: ANN: experimental patch to allow importing from file-like objects References: <3c7fcbe6.7419921@news.t-online.de> Message-ID: Gerson Kurz wrote: > Motivation: Write a customized import that reads data from encrypted > files. Both execfile() and exec() are limited, if only that that they > don't mimic the import syntax. > > Problem: imp.load_module does expect a file object, but you can only > pass "real" files, not file-like objects. The internal C-code expects > native FILE* stuff. > > Solution: An experimental patch to the python22.dll that makes this > possible. Using file-like objects for import opens up a whole new set > of possibilities, for example you could fetch the code at runtime from > a database or a socket. Most people doing something like this don't use imp.load_module. First you need a code object for the module. If it's source: co = compile(open(srcfile, 'r').read()+'\n', srcfile, 'exec') If it's already compiled (and still fresh etc.) stuff = open(bytecodefile, 'rb').read() co = marshal.loads(stuff[8:]) Then you need a module object mod = imp.new_module(nm) (You need to set up mod.__file__, mod.__name__ etc. here). And finally sys.modules[fqname] = mod exec co in mod.__dict__ This is not to say that I'm against your patch (didn't look at it), just that there's another way around the problem. -- Gordon http://www.mcmillan-inc.com/ From jason at jorendorff.com Fri Mar 8 12:40:30 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 8 Mar 2002 11:40:30 -0600 Subject: vfork hangs In-Reply-To: Message-ID: Kip Macy wrote: > I'm having problems with my python application hanging in vfork with > the child never completing the exec. It is hard for me to track it > down just by putting a break on vfork because the code is > multi-threaded, several thousand lines long, and doesn't hit this > right away. I saw it suggested that system is not thread safe on > solaris (the platform I'm using). The other thing of note is that a > SIGCLD is always received promptly before the vfork hang. According to the man page, system() is not thread-safe on Solaris. It says, "MT-Level: Unsafe". The vfork(2) man page says, "The vfork() function is unsafe in multithreaded applications." Not sure what makes it unsafe, but I wouldn't spend any more time fighting it. I believe a thread-safe system() can be implemented in Python, at the cost of some performance. If you go this way, I think you'll want to use os.fork1() instead of os.fork(). Let us know how this works out for you. ## Jason Orendorff http://www.jorendorff.com/ From peter.schwalm at epost.de Tue Mar 12 20:18:59 2002 From: peter.schwalm at epost.de (Peter Schwalm) Date: 12 Mar 2002 17:18:59 -0800 Subject: Redirecting output in Windows NT References: <96e9dee5.0203120044.33a1e19c@posting.google.com> <3C8DC473.2070809@skippinet.com.au> Message-ID: <5cf809e9.0203121718.6d999426@posting.google.com> > >It is a bug in the NT command prompt. Works OK in Win2k. I believe > >there is a FAQ on it too. > > You state that *output* redirection works OK in Win2k. I could verify that, but unfortunately it's not true for the redirection of *input*. If I want to redirect input, I still have to use the form python myprog.py Message-ID: <3CA35C49.31397789@ndh.net> phil hunt wrote: > And Guido's statement supports my suggestion that pass be made > optional in Python. Consider, when someone is designing a class, > one could write an outline like this: > > class BaseClass: > > class MyClass(BaseClass): > def __init__(self): > def method1(self, a, b, c): > def method2(self, d, e): > def method3(self, f): > > It is perfectly clear what this means. I know that there may be reasons to write such code. What I like about pass is that it reminds me to make it explicit if I omit an implementation of e. g. a method. > But unfortunately, as Python > stands today, it is syntactically invalid, one would have to say: > > class BaseClass: > pass > > class MyClass(BaseClass): > def __init__(self): > pass > def method1(self, a, b, c): > pass > def method2(self, d, e): > pass > def method3(self, f): > pass What about class BaseClass: pass class MyClass(BaseClass): def __init__(self): pass def method1(self, a, b, c): pass def method2(self, d, e): pass def method3(self, f): pass IMHO, that looks almost as well as your version, and makes the absence of additional code seem rather intentional, not accidental. If I remember correctly, I seldom use that many pass's, so I don't bother whether I have to write them. > And then, when you begin to flesh out your code, you would have to > get rid of the extraneous passes you didn't want to add (assuming > you are like me) in the first place. So the with-pass version > requires more effort, and is more verbose, for no good reason. I value the explicitness of pass over having to write or delete a bit less. Stefan From stefan.heimann at web.de Sun Mar 3 16:27:30 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 3 Mar 2002 21:27:30 GMT Subject: Problems with print str, References: Message-ID: Martin v. Loewis wrote:: > Stefan Heimann writes: > >> Any help would be great! > > I suggest to use raw_input for this specific application. Works great! Thanks, Stefan From bokr at oz.net Fri Mar 29 14:59:17 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Mar 2002 19:59:17 GMT Subject: Newbie: List of instances? References: <3CA4C09B.D9D15464@bellsouth.net> Message-ID: On Fri, 29 Mar 2002 14:29:31 -0500, Jeff Layton wrote: >Hello, > > I'm still learning Python and I'm playing around with some >code that creates a class. I've mastered that stage already. >However, what I want to do is create multiple instances of >the class and put them into a list. > If the class is called Bob, then I want to do something like, > > >a = [] >a[0] = Bob('input1') > > >and so on. Everytime I try something like this I get the following >error message: > > >a[0] = Bob( 'localhost' ) >IndexError: list assignment index out of range > Because there is no a[0] yet if a is [] > > I also tried it this way, > > >a = [] >a.append = Bob('localhost') > That much should work. Can you copy and paste an actual interactive snippet? E.g., >>> class Bob: ... def __init__(self,v): ... self.v = v ... def show(self): ... print 'This is a Bob instance with v = %s' % self.v ... >>> a = [] >>> a.append(Bob('localhost')) >>> a [<__main__.Bob instance at 0x007CF4A0>] >>> a[0] <__main__.Bob instance at 0x007CF4A0> >>> a[0].show() This is a Bob instance with v = localhost > >and I get the error message: > > >a[0] = Bob( 'localhost' ) >IndexError: list assignment index out of range > a must have still been [], but who can tell from what you posted? > Can anyone shed some light into how I do this? Or is >there a better way? > Post a log of minimal failing code sufficient for anyone to duplicate your problem. Regards, Bengt Richter From fperez528 at yahoo.com Fri Mar 1 07:06:22 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 01 Mar 2002 12:06:22 +0000 Subject: C/C++ to Python translater References: <5e8bd451.0203011049.5d12d3a2@posting.google.com> Message-ID: kevin parks wrote: > Is there a translator to automatically port (rewrite) code snippets > from C or C++ to Python? I have some old C code that i have been > porting by hand (well by head really) and i was wondering if there > were any translation utilities that i could try. I imagine that this > would be a monster AI undertaking, Btu with Python's powerful built-in > types i am guessing c --> Python is easier than the opposite. Yes, almost. It doesn't translate it, but you can embed the C/C++ in your python source code: http://www.scipy.org/site_content/weave Besides, there's various systems for wrapping complete libraries as modules with minimal effort. google(swig,sip,boost.python,siloon) will help. cheers, f. From ark at research.att.com Sat Mar 30 10:58:40 2002 From: ark at research.att.com (Andrew Koenig) Date: 30 Mar 2002 10:58:40 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type In-Reply-To: <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> Message-ID: David> void f(int const&); David> f(false); // error! For the sake of nitpicking correctness, I cannot help but point out that there is nothing wrong with the call of f(false) above unless you drop the "const" from f's parameter type. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From tejarex at yahoo.com Mon Mar 4 15:31:53 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Mon, 04 Mar 2002 20:31:53 GMT Subject: more functional programming References: <3C83EE39.B3665205@gol.ge> Message-ID: > PS. Is a genetic programming library written in/for Python available? Have you searched Google for 'python genetic programming'? TJR From phil.edwards at mistral.co.uk Tue Mar 26 12:09:01 2002 From: phil.edwards at mistral.co.uk (Phil Edwards) Date: Tue, 26 Mar 2002 17:09:01 +0000 Subject: Python, CGI and PGP References: <3c9fbf57@peer1.news.newnet.co.uk> Message-ID: <3ca0b0f9@peer1.news.newnet.co.uk> Jim Dennis wrote: > > How are you feeding "sometext.txt" into the process in your CGI > script? Why now show us the actual fragment of code that you're > attempting to use? > > When it comes to environmental issues (in programming) it's generally > pretty easy to replace a target program with a wrapper script like > so: > > mv $ORIGINAL_BINARY $ORGINAL_BINARY.wrapped > cat > $ORIGINAL_BINARY < #!/bin/sh > printenv > /tmp/$(basename $0).$$ > . /some/where/$(basename $0).env > exec $0.wrapped "$@" > WRAPPER_SCRIPT > chmod +x $ORIGINAL_BINARY > > ... this shell code is relatively terse (as well as concise) so > I'll highlight some of it's finer points in english. > Thanks, Jim, this is definitely one for the "little black book". When I see things like this, I'm reminded just why I love UNIX so much... > > If you are reasonably persistent and a little clever you should be able Oh, that leaves me out, then :-) Managed to figure it all out with the help of the wrapper stuff above. It turns out that both 'os.system' and 'commands.getoutput' (which I had tried) trash so much of the execution environment that there's hardly anything left for the binary to wprk with. I'm left with the following code in my CGI app: cmd = 'export PGPPATH=/var/www/.pgp; /usr/local/bin/pgp -z windsurf -sta -f - ' print 'content-type: text/html\n\n' pw,pr = os.popen2(cmd) pw.write(tdata) pw.close() junk = pr.read() print string.replace(junk, '\n', '
    \n') Thanks for your help! It's a shame there isn't a scheme for sending beer/pizza vouchers over the 'net... -- Regards Phil Edwards UNIX Systems Administrator ========================================================================== Mistral Internet http://www.mistral.co.uk Tel: +44 (0)1273 747432 Fax +44 (0)1273 747452 Running Mandrake Linux release 8.1 (Vitamin) for i586 Kernel 2.4.8-34.1mdk System uptime : 8 days, 8 min, 2 users, load average: 1.66, 1.36, 1.24 ========================================================================== From jimd at vega.starshine.org Wed Mar 27 07:35:54 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 27 Mar 2002 12:35:54 GMT Subject: starting a python program from within xemacs References: <1017098019.357959@DS9.ai-lab.fh-furtwangen.de> Message-ID: In article , Michael Hudson wrote: > jimd at vega.starshine.org (Jim Dennis) writes: >> More to the point, is there a way to direct the Python curses module >> to use an alternative terminal/device? > There's no wrapper for newterm, so not really, no. Also tput is > more-or-less impossible to wrap sensibly, so you'd have to do delays > by hand, if you care about such things. I don't understand. Why couldn't it be redirected to use the same timing as the other terminal? How is tputs involved in the curses module? (I'm guessing you're referring to tputs(3) rather than tput(1)). From the man pages I'd suspect that the Python curses module would make little if any use of tputs since the man pages suggest higher level functions for most operations. >> This would be handy for other situations as well (for example when >> running interactively via idle or from an xterm or a Linux/FreeBSD >> virtual console). It would be nice to have the interactive prompt >> and output decoupled from the "user's" I/O --- especially when >> playing with the curses module. > http://www.python.org/patches/ :) >> I suppose I could try reading the Python curses sources and looking >> for the place where it sets up its terminal context. > Adding a wrapper for newterm probably isn't that hard, and is, I > think, the right thing to do here. > Cheers, > M. Ahhh! I see. newterm() is a function in the ncurses library. From peter at engcorp.com Sun Mar 24 14:40:17 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 14:40:17 -0500 Subject: Memory sizes of python objects? References: <3C9E06A0.EC4D51E3@engcorp.com> Message-ID: <3C9E2BA1.E500BE4A@engcorp.com> Erno Kuusela wrote: > > In article <3C9E06A0.EC4D51E3 at engcorp.com>, Peter Hansen > | Keeping in mind Python's propensity for finding already-existing > | entities and binding to them instead of creating new objects. > > | The difference in memory consumption between creating a list > | of size 1,000,000 filled with 0's and the same size list filled > | with integers from 0 to 999,999 is rather large... > > you make it sound more mysterious than it is - only numbers under > 100 and identifier-like string literals get interned, afaik. So you mean if I do the following, the first one produces only a million references to the value 51, while the second one produces a million instances of 102 plus the million individual references? I don't get that behaviour. On my machine, with Python 2.2, for all intents and purposes the memory allocated stays constant. Did I overlook something? >>> b = 1 >>> a = [0] * 1000000 >>> for i in xrange(len(a)): a[i] = b*51 ... >>> b = 2 >>> for i in xrange(len(a)): a[i] = b*51 ... -Peter From dragon at china.org Sun Mar 10 23:55:36 2002 From: dragon at china.org (Qiang.JL) Date: Mon, 11 Mar 2002 04:55:36 GMT Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: "Patrick" wrote in message news:oBTi8.1475$523.127893 at ozemail.com.au... > > "Aahz Maruch" wrote in message > news:a6g7ra$lm6$1 at panix2.panix.com... > > > > But are there any tasks for which C++ (or C++/Python) is really better > > than C/Python? > > One example is an extremely complex and long-running simulation in which the > time-critical components are a very substantial chunk of the project. In > those (rare) situations you need ruthless efficiency with slightly better > than rudimentary abstraction capabilities. C++ fits the bill, but only if > every processor cycle and every byte counts. > > The vast majority of programmers will never go anywhere near a project like > that. Even "real programmers" very seldom do. And you can virtually > guarantee that if somebody is idiot enough to claim that knowing C++ is > either necessary or sufficient for being a real programmer, they will never > work on a project that actually needs C++. > > Unless somebody has already spent years learning C++, I think they're much > better off using either (a) one vastly more powerful yet still reasonably > efficient language like Common Lisp, or (b) two lean and vicious languages > like C and Python - both small and simple, both perfectly suited to their > respective domains, and both complementary. Either way you end up with very > good performance and far less mental friction. > > If the OP is still around, I'd recommend learning C and Python at this > stage. In spite of what your friends tell you, C++ is *not* a powerful > language in the sense that it has one of the worst power/complexity ratios > of any language in use today. Don't mistake effiency for power. > > If two people of equal ability started programming today, one learning C and > Python, the other learning C++, I'd wager that the C/Python guy will be > running conceptual rings around the C++ guy 12 months from now. Power in a > language is all about being able to express your most complex thoughts with > as few arbitrary difficulties as possible. Some languages help. Some hinder. > > > reasonable,very impressive, Thanks! From weeks at vitus.scs.agilent.com Fri Mar 15 14:21:36 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Fri, 15 Mar 2002 19:21:36 +0000 (UTC) Subject: ***Stopping a Python Thread*** References: <4378fa6f.0203151245.2a87b42d@posting.google.com> Message-ID: <1016229096.335233@cswreg.cos.agilent.com> Steve Lamb (grey at despair.dmiyu.org) wrote: : On 15 Mar 2002 12:45:48 -0800, Marc wrote: : > command to try and kill it all. But the thread keeps running and does : > not stop. How do I kill this thread before it completes? : You must stop each thread from inside the thread. So have some flag : somewhere that it can check to see if it needs to shut down early. Actually, you only need to stop non-daemonic threads. For example, if all the threads (but the main thread) are daemonic, then calling sys.exit in the main thread will exit the program. (To make a thread t daemonic, execute t.setDaemonic(1) before starting the thread.) Finally, if you *must* rudely exit the program from a non-main thread, you can use os._exit. You're supposed to avoid this, but ... Greg From christophe.delord at free.fr Mon Mar 4 16:41:38 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Mon, 04 Mar 2002 22:41:38 +0100 Subject: Problem with SRE's regular expressions References: <3C83D5C6.7010303@free.fr> Message-ID: <3C83EA12.5030406@free.fr> Thanks for your explanation! In my real program, I had a more complex regexp. I need to match text enclosed in << ... >> I first have used such an expression : <<([^>]|>[^>])*>> but I prefered <<.*?>> because it is more readable. I'll listen to the advice and use my old regexp to see how faster it is this way ;-) Thanks, Christophe. Fredrik Lundh wrote: > Christophe Delord wrote: > >>I'm using regular expressions in python in a parser generator. I have >>some troubles with the module named 're'. In fact it uses the 'sre' >>module. When I explicitly use the old 'pre' module it works fine. >>So my problem is when big strings are scanned using non greedy operator >>(for example ".*?") 'sre' seems to be recursivle and python stack limit >>is exceeded. >> > > the SRE engine is trying to tell you that you're using the wrong > tool for the task, and probably should think of a better way to > do the right thing... > > >>big_string = "<" + "that's a very very big string!"*1000 + ">" >> >>if re.match('<.*?>', big_string): >> > > here's the same thing, without any backtracking: > > if re.match('<[^>]*>', big_string): > > under PRE, it's about an order of a magnitude faster than your > version. and SRE is over twice as fast as PRE on this one... > > > > -- Christophe Delord http://christophe.delord.free.fr/ From philh at comuno.freeserve.co.uk Sun Mar 10 19:54:22 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 11 Mar 2002 00:54:22 +0000 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: On Sun, 10 Mar 2002 20:01:02 GMT, Grant Edwards wrote: >In article , phil hunt wrote: >> On Sat, 09 Mar 2002 22:57:42 -0500, Peter Hansen wrote: >>> >>>I agree with much of what you say, especially the "consider skipping >>>C++ and just learn C part", but _what_ pragmatic point of view is it >>>that has one learning Perl, Java, or C++ when one uses Python already? >>>Not dissing those languages, but when would you really need them? >> >> I can think of several tasks for which C++ is better than Python, >> e.g. writing operating systems, network stacks, windowing systems, >> run-time interpreters, crypto algorithms, etc. > >And I can think of several languages which are better than C++ >for those tasks: Modula-2, Modula-3, Ada, Bliss-32... Not if you take into account factors such as availability of compilers, libraries, reference works, programmers etc. Sometimes, the popularity of a language is itself a factor determining how good it is. For certain values of "good", of course. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From jeff at ccvcorp.com Fri Mar 29 19:11:04 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 29 Mar 2002 16:11:04 -0800 Subject: Breaking String into Values References: Message-ID: In article , rgwright at ux.cso.uiuc.edu says... > I am working on reading in a data file format which is set up as a series > of lines that look like this: > > 3500035000010104A Foo 45 > > I want to break up into a variables as follows: > a = 35000, b = 35000, c = 10104, d = 'A', e = 'Foo', f = 45 > > My current code (auto-generated from a data dictionary) looks > something like this: > >.... > Is there a better way to do this? The files have around 1000-8000 lines each > so I would like it to be fast. Is there a package around that someone has > coded up as a C-extension to do this? I've done something similar to this, and find it to be not all that slow. (I haven't timed it, but on my 500-1000 line files the processing time was no more than about a second.) The most significant difference in my approach, was that I parsed each line into a class object, and I used a dictionary to define the beginning and end of each field. (In my case, there were fields in the data that I was uninterested in, so this allowed me to grab only those sections I needed, and by defining my format separately from my code, it made it easier to adjust.) So, I would have something like this: format = { a: (0,5), b: (5,10), c: (10,15), .... } class Record: def __init__(self, data) for field,zone in format.keys(): setattr(self, field, data[zone[0]:zone[1]]) If you want to do error checking of most of the fields, I'd define a series of functions that do whatever checking and/or converting you need, and include those in the dictionary: def ConfirmValidId(): .... format = { a: (ConfirmValidId, 0, 5), b: (int, 5, 10), ... } Then your setattr line becomes: setattr(self, field, zone[0]( data[zone[1]:zone[2]] ) ) You can also define various access methods and such on your Record class, making it easier to use. If each record is only a few hundred bytes, then it's probably not a problem to read your entire file into memory, too. (It'll take a couple of megs of memory, which is trivial on a modern machine.) recordlist = [] for line in datafile.xreadlines(): recordlist.append( Record(line) ) for rec in recordlist: Process(rec) ... This should be fast enough unless you've got *very* strict time constraints. -- Jeff Shannon Technician/Programmer Credit International From r.salz at verizon.net Thu Mar 21 10:58:11 2002 From: r.salz at verizon.net (Rich Salz) Date: Thu, 21 Mar 2002 15:58:11 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C9991C0.4080102@pobox.com> <3C99D770.57345464@engcorp.com> Message-ID: <3C9A031E.5070408@verizon.net> >>Peter, what do you think about qualifying problem sets like what >>arsDigita had? > > > I think that's an interesting sounding name for something. It's the MIT term for homework. /r$ From stephen at xemacs.org Sun Mar 10 21:17:23 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 11 Mar 2002 11:17:23 +0900 Subject: PEP Parade References: <87henqe4dy.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87zo1fc0gc.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Roy" == Roy Smith writes: Stephen J. Turnbull" wrote: Roy> as we discover imcompatabilities between whatever version I'm Roy> using to develop on and whateve they're running on their Roy> boxes. >> So you standardize locally. Roy> It's one thing to say "so you standardize locally", but the Roy> fact is, even requiring just that is an impediment to Roy> adoption. A typical scenario goes like this: Roy> Me: "Hey guys, I wrote a great new program, called foo.py. Roy> It's in CVS, under tools." Roy> Co-worker: "Neat, but when I go to run it, I get a syntax Roy> error" Roy> Me: "Let me see.... Oh, you've got python 1.5.2! Do you have Roy> any idea how old that is? You need to upgrade to 2.1.2" And I say, "Roy, what are you doing programming for 2.anything if the people you're trying to sell to are running 1.5.2?" I didn't mean "make _them_ standardize" (you already made your point, I was listening!), I meant "_you_ comply with the de facto standard (least common denominator)." Marketing is about two things: convincing others to buy in to the pain, and absorbing as much of the pain as you can yourself. Most people seem to think that it's only the first part. One of the things the Microsoft is really good at is postponing pain until the customer is already locked in. But that cost them a lot up front. If I have tools I want to distribute to folks who aren't bleeding- edge-distro-Linux users, I program in python 1.5. It hurts, but it wins. Once you've got them hooked, they come saying "why can't it do ...?" and _that's_ when you say "it's too hard in 1.5, I don't have time. But if you'll upgrade to 2.1.2, it's already in CVS...." If you're not doing that, then you're just programming for yourself. Which is fine: unless your job is writing for others, your needs come first. But it's not investing in support for your tools from your coworkers. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From dale at riverhall.NOTHANKS.co.uk Wed Mar 20 11:15:38 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Wed, 20 Mar 2002 16:15:38 +0000 Subject: Message bug? Message-ID: <99dh9us1b4d8r9u7p5ltt41g34vlun4kjj@4ax.com> Would I be right in thinking that this message quite what the developer intended? AttributeError: 'module' object has no attribute 'work' I have no module called 'module'. Python 2.2 on Win2K. -- Dale Strickland-Clark Riverhall Systems Ltd From tim at vegeta.ath.cx Sat Mar 23 19:51:14 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Sun, 24 Mar 2002 00:51:14 GMT Subject: simple question References: <2UVm8.30655$J54.1855090@news1.west.cox.net> Message-ID: Christopher Palmer graced us by uttering: > Let's say I have a variable called a > > and a contains an integer, say 4522 > > and I want 4, 5, 2, and 2 to be items in a list instead of an integer... > > I know it must be dirt simple, but nothing I have tried so far has worked. Actually, not as simple as it might be, but here's what I came up with: >>> i = 4522 >>> l = [x for x in str(i) >>> l ['4', '5', '2', '2'] >>> > Thanks in advance, > CTP HTH Tim Hammerquist -- I would feel infinitely more comfortable in your presence if you would agree to treat Gravity as a Law, rather than one of a number of suggested options. -- Barnabas, The Sandman From mats at laplaza.org Mon Mar 4 09:32:14 2002 From: mats at laplaza.org (Mats Wichmann) Date: Mon, 04 Mar 2002 14:32:14 GMT Subject: What readers want (was: Deitel and Deitel Book...) References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> <91F926228151D5F5.946DE1D959605688.72F5DF01B36707F9@lp.airnews.net> Message-ID: <3c8383a3.291935621@news.laplaza.org> On 1 Mar 2002 18:54:39 -0600, claird at starbase.neosoft.com (Cameron Laird) wrote: :In article , :DeepBleu wrote: : . : . : . :>> I would love to see books on Algorithms with Python (makes a perfect :>> fit), and more advanced topics such as threads and extending python. :> :>I'd love to see something like that specially on threads and extending :>Python. This is something I can use. :>DeepBleu :> :> : :How would you feel if such material appeared in magazines rather than books? Replying generically since I didn't start this thread, print magazine articles tend to end up chopped by space constraints, and they "expire" - if you happened to pick up a copy of that magazine, and it doesn't get lost in your pile of 23,269 "I ought to go through this someday" tech magazines in boxes out in the shed, then you have it. If you missed it first time, and it's not on the web... On the plus side, if the topic of the article is the one thing I'm interested in, it's a lot more palatable than picking up yet-another $50+ book. Mats Wichmann From eppstein at ics.uci.edu Mon Mar 4 22:59:03 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 04 Mar 2002 19:59:03 -0800 Subject: Status of PEP's? References: <7xwuwrofhk.fsf@ruckus.brouhaha.com> Message-ID: In article <7xwuwrofhk.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Usually the term "natural numbers" don't include zero. > http://mathworld.wolfram.com/NaturalNumber.html I think "usually" is an exaggeration. For instance, a better authority than Weisstein, Ebbinghaus et al's _Numbers_ (Springer Graduate Texts in Mathematics 123, 1991, p. 14) disagrees. From deltapigz at telocity.com Sat Mar 9 17:33:32 2002 From: deltapigz at telocity.com (Adonis Vargas) Date: Sat, 9 Mar 2002 17:33:32 -0500 Subject: Tkinter + Button widget Message-ID: <3c8a921b$1_1@nopics.sjc> when i start a button widget, it automatically fires the command? def HideNewClient(self, frame): frame.configure(bd=0, width=0, height=0) return pdb_btnSearch = Button(pdb_frmCommands, text="Search", relief=GROOVE, font=("Tahoma", 10), width=16, command=self.HideNewClient(pdb_frmNewClient)) any help would greatly be appreciated. Adonis From jkraska at san.rr.com Fri Mar 1 20:48:30 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 02 Mar 2002 01:48:30 GMT Subject: Status of PEP's? References: <3C802175.A527BFA0@ccvcorp.com> Message-ID: <76c08ukou81p7lfnnoiftfhaf5v66amglm@4ax.com> >Now which is easier to come up with? for i in [9:3]: ... with the provision that the negative stride is inferable and therefor assumed. This has been rejected already so I hear. But it still seems perfectly clear to me. I guess I'll have to go hunt down the PEP and see what the rejection rationale was... At least we dont have for (exp-list;expr-listl;expr-list): That's nasty, imo. C// From mlh at vier.idi.ntnu.no Tue Mar 26 13:41:53 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 26 Mar 2002 18:41:53 +0000 (UTC) Subject: Streaming XML-RPC? References: <3C9F51EE.5000203@jerf.org> Message-ID: In article <3C9F51EE.5000203 at jerf.org>, Jeremy Bowers wrote: >Magnus Lie Hetland wrote: >> I'm thinking about implementing a library that uses the xml-part of >> XML-RPC (i.e. XML-RPC without the HTTP) in two-way persistent stream >> (tcp socket) somewhat like Jabber, to improve performance. > >Why not Jabber? Jabber is meant to do that. It's designed to do that. >It's *begging* you to use it that way. > >This is in stark contrast to HTTP. HTTP thinks you're nuts. HTTP will >fight you tooth and nail. HTTP is old, and hoary, and set in her ways. >And XML-RPC isn't exactly ecstatic about being streamed, either. Well, jabber-rpc is just XML-RPC in a Jabber stream... :) >Why fight the system when you can work with another one? Simplicity. Setting up a Jabber server and using Jabber clients may be overkill if I can add 20 lines of code in subclasses of xmlrpclib.Server and SimpleXMLRPCServer. But, yes, Jabber is cool. (And the standard server is written in C, so, of course, that would help performance ;) -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From i.linkweiler at gmx.de Fri Mar 8 14:53:27 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Fri, 08 Mar 2002 20:53:27 +0100 Subject: PyQT: QString to String Problem if ASCII>128 References: <3C88A748.2F95D854@gmx.de> Message-ID: <3C8916B7.E5396663@gmx.de> no ideas? I found a possible solution, but is this the best way? uc=self.edit.text() try: t=str(uc) except: try: t=unicode(self.edit.text()).encode("cp437") except: t="invalid char in string" Ingo From jgardn at alumni.washington.edu Wed Mar 6 10:57:44 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Thu, 07 Mar 2002 00:57:44 +0900 Subject: Bugs/Patches not being watched (Re: Flushing stdout with raw_input) References: Message-ID: Michael Hudson scribbled with his keyboard: >> I will write >> another bug report about the unresponsiveness to bug reports as well, as >> there are a lot of bugs that aren't even addressed at sourceforge. > > Oh, that will help, sure. > I wish to take back my comment about the bugs not being watched. I happened to get some attention from the BDFL, and I feel real bad for bothering him and taking his time. I looked at the stack of bugs at SF, and I saw a lot of old ones that hadn't even been assigned or handled, and I thought that meant that no one reads them. That is wrong. Jonathan From sdm7g at Virginia.EDU Fri Mar 29 19:36:36 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Fri, 29 Mar 2002 19:36:36 -0500 (EST) Subject: table driven code [was: Breaking String into Values] In-Reply-To: Message-ID: On Fri, 29 Mar 2002, I wrote: > Sometimes, with data file conversion problems, I will make an intermediate > class to represent the abstract object, with methods to load from or dump > to the particular representation format. > > > Again -- it's more overhead to do it that way, but I've usually found > it worth it in the long run. I should add, that the reason it's usually been worth doing that way, is that once I've done an "A to B" converter, typically, it's not long before I find I need a "B to A converter" or a batch editor to change some field in a directory full of files, or a 'splitter' or a 'merger' or something to gather statistics from the files... But if you're *sure* that you're only going to do this once, then by all means, go ahead and go all out for speed! ;-) -- Steve Majewski From sandskyfly at hotmail.com Wed Mar 13 11:48:25 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 13 Mar 2002 08:48:25 -0800 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: Martin v. Loewis: > I don't count articles in a newsgroup saying "this is a good thing", > "just continue with your efforts", "we definitely need this" as > interest. Instead, people contributing code, reporting bugs, or just > using the system in their applications show interest. This is the case > for Jython, but I don't think Armin or Christian got much actual code > contributions. Likewise, when Mark would not deliver a win32all build > for a few weeks, people would complain - but nobody would actually > step forward and publish a build herself. Perhaps you're right, but the wonderful work Armin, Christian, and Mark (God bless them) are doing qualify as deep magic in my book: it just ain't easy to wrap your brain around the Psyco, Stackless, or win32all C/C++ codebases. I'm sure many pythonistas would love to contribute... maybe it's just a matter of time. When it comes to use, however, there must be many instances which just aren't talked about. Personally, win32all is an integral tool in my python toolchest and I've used Psyco to more than double the speed of one part of an application with great success. I haven't gotten round to using Stackless to any great effect simply because my brain can't accomodate first-class continuations... but I'm eagerly awaiting the practical library that will accompany the new generation stackless: microthreads are most welcome! I think the best way the average non-guru level pythonista can contribute is to document her/his experiences with various modules in howtos, place examples in the pubic domain, and just spread the love. all the best, Sandy From guido at python.org Sat Mar 30 09:25:24 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 09:25:24 -0500 Subject: [Python-Dev] RE: PEP 285: Adding a bool type In-Reply-To: Your message of "Sat, 30 Mar 2002 08:13:26 CST." References: Message-ID: <200203301425.g2UEPOp01732@pcp742651pcs.reston01.va.comcast.net> > What is the likelihood that __nonzero__ could be renamed (at some > point in the future) to something a bit more intuitive, like > __bool__? I know there would be a lot of user code to change, but > assuming one day the hammer will drop and everyone's __nonzero__ > will have to change to return a bool, I wouldn't mind seeing the > method renamed as well. Or is this a lost cause at this point? I think it's a lost cause. It's one of those minor details that might be considered wrong with 20/20 hindsight, but not wrong enough to want to bother fixing it, given the cost (to the user community) of the fix. --Guido van Rossum (home page: http://www.python.org/~guido/) From weeks at vitus.scs.agilent.com Tue Mar 5 23:14:29 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Wed, 6 Mar 2002 04:14:29 +0000 (UTC) Subject: HP-UX 10.2 deprecated? References: <1015292901.342132@cswreg.cos.agilent.com> Message-ID: <1015388069.929994@cswreg.cos.agilent.com> Michael Piotrowski (mxp at dynalabs.de) wrote: : aCC is the C++ compiler; the unbundled ANSI C compiler is cc. But : since the OP was able to compile Python, I doubt he used the bundled : compiler--you wouldn't get that far with a K&R compiler, I think. In the Makefile, the compiler was "cc -Ae", which is the ANSI compiler plus extensions. However, in "configure", plain old cc was used, and that is the K&R compiler in HP-UX 10.2 (but not in HP-UX 11). This is the compiler that misunderstood the indented compiler directives. : My guess is that, like this problem, most problems on HP-UX are in : configure. 10.20 and threads is, ahem, a bit problematic; the DCE : threads are _not_ POSIX threads. It sounds like I'm lucky that my Python 1.5.2 threads are working on HP-UX 10.2! I should perhaps just be content with that? Greg From mlh at vier.idi.ntnu.no Sun Mar 31 18:51:48 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 31 Mar 2002 23:51:48 +0000 (UTC) Subject: piddle on xdarwin References: Message-ID: In article , Adam C. wrote: >I recently got a copy of fink, xdarwin, python etc. It all works >beautifully, but now I want to stop printing prime numbers to the >stdout and actually draw things. I downloaded a copy of piddle and >installed it. It installed fine and the modules can be imported etc. >Unfortunately, when I run the test files nothing happens. There is no >error, but no window pops up either. I have tried this with several >back ends, but none work. Does anyone have any advice? Try the piddle/sping mailing list, perhaps? -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From mhammond at skippinet.com.au Thu Mar 7 19:38:26 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 08 Mar 2002 00:38:26 GMT Subject: Problem with VB-COM-Python arg passing/value returning References: Message-ID: <3C88081D.7040201@skippinet.com.au> Sue Giller wrote: > I am hoping that someone here can help me with the following > problem. ... > public property get ByValArg(byval arg1) as variant > ByValArg = 1 > end property ... > info = idobj.ByValArg("abc") # raises python error: > #Type Error: list () argument > must be a sequence > print `info` I would be interested to see the complete traceback, as I can't see where the list() call comes from. However, the problem is probably that ByValArg() is a *property*. I would expect it to still work though - so can you post the entire traceback? Thanks, Mark. From ak at silmarill.org Sun Mar 24 20:21:28 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Mon, 25 Mar 2002 01:21:28 GMT Subject: Client/Server Tutorial? References: Message-ID: In article , maximilianscherr wrote: > hi, > > Is there any good tutorial for creating advanced client/server apps > (like online games) out there? i tried to make one 2 times, and both > did not really work well, the first try had problems with > communcications between the client threads, the second one had > problems with connecting at all!!! > > thanks, > > Max > Deitel's Python: How to Program has a chapter where a networked tic tac toe game is created using server/client mechanism. > > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From huaiyu at gauss.almadan.ibm.com Mon Mar 4 17:17:43 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 4 Mar 2002 22:17:43 +0000 (UTC) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: On Sat, 2 Mar 2002 12:04:44 -0600, Skip Montanaro wrote: >According to the pow man page on my Mandrake 8.1 system it suggests that >ERANGE should be set if its first arg is zero. This appears to happen when >x is around 1.5717e-162. I suspect a bug in glibc (I have version 2.2.4). > >In the region where the problem occurs, Python's float_pow() looks like > > PyFPE_START_PROTECT("pow", return NULL) > ix = pow(iv, iw); > PyFPE_END_PROTECT(ix) > Py_SET_ERANGE_IF_OVERFLOW(ix); > >Setting a break immediately after the pow() call shows that ERANGE is set >even though it appears to have correctly returned 0. Perhaps if iv < 1, ix >== 0, and errno is ERANGE, errno should be cleared, at least for certain >versions of glibc? > I can't quite follow you analysis here. Can you put this into a stand-alone C test prog? The following C program produces exactly the same result on two machines, yet on one machine P2.2 raises while on the other it does not. What else need to be tested? #include #include #include extern int errno; main() { double x, y; x = 1e200; y = pow(x, 2); printf("%g %5g %d %s %d\n", x, y, errno, strerror(errno), ERANGE); x = 1e-200; y = pow(x, 2); printf("%g %5g %d %s %d\n", x, y, errno, strerror(errno), ERANGE); } Produces 1e+200 inf 34 Numerical result out of range 34 1e-200 0 34 Numerical result out of range 34 Huaiyu From phd at phd.pp.ru Mon Mar 11 04:23:09 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 11 Mar 2002 12:23:09 +0300 Subject: scripting Outlook express with Python In-Reply-To: ; from jgardn@alumni.washington.edu on Mon, Mar 11, 2002 at 04:57:24PM +0900 References: Message-ID: <20020311122309.A25769@phd.pp.ru> On Mon, Mar 11, 2002 at 04:57:24PM +0900, Jonathan Gardner wrote: > Sandy Norton scribbled with his keyboard: > > Does anyone have any experience, code, etc...? I guess my first > > question should be: is it possible? > > If you want to customize your mail client, you're using the wrong OS. All > the customizability is over here in Linux, with procmail and sendmail and > fetchmail and all sorts of great stuff that you've never even dreamed of - > even in those really wild dreams where you use your computer for a month > and it doesn't crash once. Quite right (though complete OT here). Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jason at jorendorff.com Mon Mar 4 23:06:24 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 4 Mar 2002 22:06:24 -0600 Subject: mult-indexed xrange? In-Reply-To: Message-ID: Huaiyu Zhu wrote: > I forgot to mention: without generating temporary lists. > > > > >for (x,y) in [(i,j) for i in range(2) for j in range(3) ]: > > print x,y > >0 0 0 > >0 0 1 > ... > > Is list comprehension lazy, ie. without generating the actual list? No, list comprehensions are eager. You want generators: from __future__ import generators def pairs(n, m): for i in xrange(n): for j in xrange(m): yield (i, j) for (x, y) in pairs(2, 3): print x, y ## Jason Orendorff http://www.jorendorff.com/ From fredrik at pythonware.com Thu Mar 14 03:08:34 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 14 Mar 2002 08:08:34 GMT Subject: trouble testing for existance of variable References: <4bbaa6d6.0203121352.4358f14@posting.google.com> Message-ID: <6UYj8.31928$l93.6269925@newsb.telia.net> "googlePoster" wrote: > I tried > > try: > ct = vim.exists("colors_name") # doesn't work when not defined > except vim.error: > curr_color = "none" > > if ct > 0: > curr_color = vim.eval('colors_name') > > and got > > AttributeError: 'module' object has no attribute 'exists' > > apparently 'exists' is supported in vim, but not python's > portal to it look at carels's example again: he's not using a vim.exists function, he's using vim.eval to evaluate a string that con- tains an "exists" call. try this instead: if vim.eval('exists("colors_name")' % name): curr_color = vim.eval('colors_name') if you're going to do this a lot, it might be worth defining a helper function: def vim_get(name, default=None): if int(vim.eval('exists("%s")' % name)): return vim.eval(name) else: return default curr_color = vim_get("colors_name", "none") From eppstein at ics.uci.edu Fri Mar 1 20:10:26 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 17:10:26 -0800 Subject: Status of PEP's? References: <3C802175.A527BFA0@ccvcorp.com> Message-ID: In article <3C802175.A527BFA0 at ccvcorp.com>, Jeff Shannon wrote: > > [x for 3 <= x < 10] > > Personally, I still don't see this as being an advantage over xrange(3,10). Ok, quick, what if you want to loop over the same values in reverse order? . . . a n s w e r : . . . [x for 10 > x >= 3] or xrange(9,2,-1) Now which is easier to come up with? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From dale at riverhall.NOTHANKS.co.uk Sat Mar 30 09:09:27 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 30 Mar 2002 14:09:27 +0000 Subject: Another stab at a "switch/case" construct (new proposal): References: <20020329150225.7efdaf2b.logiplexsoftware@earthlink.net> Message-ID: "Chris Gonnerman" wrote: > >Bingo. Like I said before, "clearer code" is not good enough. The >advantage must be *overwhelming*, not just good. > Clearer code is one of the issues. The other important issues are: Speed of writing; Ease of maintenance (clearer code); Speed of Execution; Doesn't break old code & libraries; Feasability (compiler constraints); -- Dale Strickland-Clark Riverhall Systems Ltd From posselt at brics.dk Tue Mar 12 10:57:41 2002 From: posselt at brics.dk (Peter Posselt Vestergaard) Date: Tue, 12 Mar 2002 16:57:41 +0100 Subject: returning a picture from PIL Message-ID: Hi I would like to show a image on a webpage by calling a python script that through the Python Imaging Library (PIL) loads a picture and then returns it. I'm trying to do it like this: In the webpage I write: [...] [...] and in myscript.py I write: [...] pic = Image.open(urllib.urlretrieve(url)[0]) print "Content-type: image/png\n\n" pic.save(sys.stdout,"PNG") the page takes some time loading the picture but nothing is ever shown. If I change sys.stdout to "filename" the picture is stored perfectly on my disk. Anyone who can tell me how to do this kind of output from PIL? Thanks Regards Peter Vestergaard From gimbo at ftech.net Fri Mar 15 08:04:19 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Fri, 15 Mar 2002 13:04:19 +0000 Subject: line-by-line file read In-Reply-To: <20020315073010.A13530@phy.duke.edu> References: <20020315073010.A13530@phy.duke.edu> Message-ID: <20020315130419.GB12743@andy.tynant.ftech.net> Here's one way: fo = open(filename) while 1: line = fo.readline() if not line: break do_stuff(line) fo.close() -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From chris.gonnerman at newcenturycomputers.net Fri Mar 29 08:53:22 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 29 Mar 2002 07:53:22 -0600 Subject: Random... Message-ID: <003c01c1d729$2d1eaaa0$0101010a@local> ----- Original Message ----- From: "Wojtek Walczak" > ** Since micro$oft is stupid it doesn't mean > ** that you should be stupid too - do NOT toppost. > Dnia Wed, 27 Mar 2002 10:22:10 -0500, Steve Holden napisal(a): > >While you correctly interpret netiquette, might it not have been more > >considerate to this list if you had *mailed* the OP rather than giving > >her/him a public dressing down which many others also had to read > >unnecessarily? Or is it OK to waste *my* time by chastising the OP publicly? > This note is automatically added to all my posts. > It wasn't directed to the OP of that thread, it's > directed to anybody who don't know about it. > I haven't sent my post to attack OP's person, I answered > his question (by giving an url to him). Gah. Didn't it ever occur to you that YOU are TOP-POSTING AUTOMATICALLY! Who made YOU the dictator of netiquette? Above and beyond that, your admonition is childish. I rarely get involved in (n)etiquette arguments, but this is just ridiculous. If you are going to warn everyone each and every time you post, well, that's just a bit much. Worse, a great many newbies have NO IDEA what the term "toppost" means (in fact I've been on USENET off and on for years and never knew what it meant until last year), so you are busting their chops for no reason they can understand. Worse, it appears you are busting ANYONE's chops when you reply to ANYTHING. This makes you appear to be a crank. Of-course-I-am-a-crank-and-almost-never-use-dashed-words-ly-yr's Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From brueckd at tbye.com Wed Mar 27 14:57:09 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 27 Mar 2002 11:57:09 -0800 (PST) Subject: interactive python shell In-Reply-To: <200203271333.38160.geiseri@yahoo.com> Message-ID: On Wed, 27 Mar 2002, ian reinhart geiser wrote: > I have an python application and I would like to provide a > "console" in the application where users can have an interactive > session with python that has all of the applications enviroment. > This is for debugging the system in real time. > > Is there an easy way to do this? All it needs to do is execute > commands and return data. I am using PyQt for my GUI, so it would be > cool to fit into there, but I can get away with a input line and a > display view if that is easier. This is not for production, only to > make a more useful debug tool. It's not too hard, but it does require experience using some other modules: Use the 'code' module. More specifically, subclass code.InteractiveConsole and override the raw_input method so that it gets input from a socket you pass to the constructor, and override the write method to write the data back out the socket. Next, use SocketServer.TCPSocketServer to listen for incoming connections and create a ConsoleRequestHandler class whose handle method creates a new console object and calls its interact method. It's helpful to trap sys.stdout like this: def handle(self): c = YourNewConsoleClass() stdout = sys.stdout sys.stdout = self.wfile try: c.interact() finally: sys.stdout = stdout (if you need stdout to keep going to the main console while you're debugging then use a custom file-like class that writes to wfile and the original stdout and install it instead.) Some extra things to think about: - your raw_input method in the Console class needs to be interruptible if your application needs to be able to shutdown and kill the debugging console, so it might be good to use select to read input in a loop that is also checking some shutdown flag - you won't be able to see the local scope of running functions, so for this console to be useful you'll probably need to have a global variable or two that reference whatever objects will be most useful during debugging. - your server that listens for incoming console connections should listen only on 127.0.0.1, and it wouldn't hurt to make it password protected. - make your raw_input function read data 1 character at a time if possible, so that you can check for chr(4) (Ctrl-D to exit), '\n' (newlines, to return the line of input), and '\r' (from Windows users, ignore these). If you have more questions I'll see if I can post some code.. -Dave From jchristl at zdnetmail.com Tue Mar 19 07:21:10 2002 From: jchristl at zdnetmail.com (Joe Christl) Date: 19 Mar 2002 04:21:10 -0800 Subject: Newbie: word count and Win32 Message-ID: newbie here (don't you just cringe when you read that? :), I downloaded the python EXE from http://www.python.org/ftp/python/2.2/, found a script on the mail.python.org Tutor page: http://mail.python.org/pipermail/tutor/2001-February/003403.html but I can't seem to get it to run. I would like it to run from the C:\ command prompt, like so: c:\count.py foo.txt (or) c:\count.pyc foo.txt and have it output the lines, words, and characters. I have tried to even get it working from the >>> prompt, to no avail. Am I doing something wrong here? Thanks for your ideas, Joe From max at alcyone.com Fri Mar 8 19:14:54 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 08 Mar 2002 16:14:54 -0800 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> Message-ID: <3C8953FE.F18CAA13@alcyone.com> damien morton wrote: > is this by design? > > is there any reason why ' in ' shouldnt work? Yes, it's by design. The in operator deals with membership, rather than finding subsequences. Strings are a degenerate case, since they're sequences of "characters" only. For example, [1, 2] in [1, 2, 3, 4] would rightly return false, since [1, 2] is not a member of [1, 2, 3, 4] (that would be something like [[1, 2], 1, 2, 3, 4]). Having in deal with membership _or_ subsequences would lead to ambiguity, and having it deal with subsequences among strings alone would be a peculiar exception. Say what you mean; there's a .find method (or just string.find) for finding substrings. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From looping002 at hotmail.com Mon Mar 25 06:54:53 2002 From: looping002 at hotmail.com (Looping) Date: Mon, 25 Mar 2002 12:54:53 +0100 Subject: communication with a java applet Message-ID: <3C9F100D.BAB4F24D@hotmail.com> Hi all, I am trying to make a real-time system communicate with a java applet under IE 5.5. I only have a pyd file (Python 1.5.2) to get the floats calculated on the platform and I wonder how to make the platform communicate with my java applet : TCP/IP, CORBA, shared memory, others... ? Thanks in advance for any advices, Looping From aahz at pythoncraft.com Fri Mar 29 06:04:16 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Mar 2002 06:04:16 -0500 Subject: The Python Way References: Message-ID: In article , FREDRIK HULDTGREN wrote: > >On a side note, what does PEP stand for?, Ive been seeing it all over >the mails but I have no clue what it is. Python Enhancement Proposal, see http://python.sourceforge.net/peps/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From tripps81 at yahoo.com Sun Mar 24 00:00:39 2002 From: tripps81 at yahoo.com (Tripp Scott) Date: Sun, 24 Mar 2002 12:00:39 +0700 Subject: list comprehension question Message-ID: <5.1.0.14.2.20020324115311.0457dbb8@202.95.131.154> can i generate this list: [1, 1.1, 2, 2.1, 3, 3.1] with a list comprehension in a form of this: [SOMETHING for x in 1,2,3] and without using side effects like this? result=[] [(result.append(x), result.append(x+1.1)) for x in 1,2,3] because the latter case is not very elegant to me. t From olc at ninti.com Sat Mar 30 20:19:44 2002 From: olc at ninti.com (Michael Hall) Date: Sun, 31 Mar 2002 10:49:44 +0930 (CST) Subject: CGI/modpython ??? In-Reply-To: Message-ID: I've got to stop replying to my own emails ... Anyway, further to my last two posts (see below), I have another question or two: - modpython hasn't been updated for a while ... is it still being developed? - where is HTML-embedded Python at? modpython's author refers to several different systems in circulation and a lack of consensus on how to do it. Thanks again Mick On Sun, 31 Mar 2002, Michael Hall wrote: > > Sorry folks, I just found the modpython docs, so I can RTFM. Still, I'd be > interested in any comments about modpython versus Python CGI. > > Mick > > > On Sun, 31 Mar 2002, Michael Hall wrote: > > > > > I'm writing Python CGI scripts using the MySQLdb module and getting a > > grasp on things fairly quickly ... Python is a cool language (I'm coming > > to it from PHP). Thanks to Drew and Emile for sorting out my looping > > function, it works fine now. > > > > Now I'm wondering how modpython is used. If Apache has the modpython > > module installed, how do I use it? What form do scripts take? > > > > Do they still look like CGI scripts, or do they look more like a PHP > > script (some sort of embedded scripting)? > > > > Does a script still use '#!/usr/bin/python', or are file endings (eg > > .py) used to call the Python interpreter? > > > > Is the script located in public_html or cgi-bin? > > > > What would I have to do with a CGI script written in Python to use it with > > modpython? > > > > Thanks > > > > ----------------------------- > > Michael Hall mick at ninti.com > > ----------------------------- > > > > > > > > -- ----------------------------- n i n t i . c o m data driven development ----------------------------- Michael Hall mick at ninti.com ----------------------------- From pecora at anvil.nrl.navy.mil Mon Mar 25 15:55:39 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Mon, 25 Mar 2002 15:55:39 -0500 Subject: Installing Piddle plotting 1.014 on a Macintosh. Problems. Message-ID: <250320021555391378%pecora@anvil.nrl.navy.mil> I have returned to Python after a year away (old version 1.52 on a Mac using sys 9.1). I upgraded to Python 2.2 and got messages that my old version of Piddle was deprecated. I downloaded the latest version and am stuck. After searching the documentation I cannot find how to install it other than the statment in the README.txt that says type in python setup.py install and go. That does nothing for me in the IDE on my Mac. I am probably missing something simple, but unless I get some plotting stuff running my return to Python will be short-lived. Can you tell me what I'm missing so I can install a new version of Piddle on my Mac? Thanks for any help. -- -- Lou Pecora - My views are my own. From flognat at flognat.myip.org Tue Mar 19 02:33:36 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Tue, 19 Mar 2002 07:33:36 GMT Subject: Chewing international (unicode) filenames on windows? Message-ID: Hello! I am messing a bit with my bookmarks (gonna sync them between a bunch of computers and browsers) and now comes the question.. How does os.listdir in the windows-compiled python handle international characters? For me on my windows 2000 machine, to get them into UTF-8 format I do something like: for filename in os.listdir(): utffilename=unicode(filename, "latin-1").encode("utf-8") But do we know that it is latin-1? How would we handle chineese characters? Someone said the filenames were unicoded, how do I encode/decode the filename som I can get it into UTF-8?? /Andy p.s. standard windows compilation downloaded from THE site. p.s.2 what is the status on win9x? Give it up or ;-) -- The eye of the beholder rests on the beauty! From arigo at ulb.ac.be Tue Mar 19 12:57:29 2002 From: arigo at ulb.ac.be (Armin Rigo) Date: Tue, 19 Mar 2002 18:57:29 +0100 Subject: For loops with explicit indices -- again Message-ID: <3c9789ed$0$29676$ba620e4c@news.skynet.be> Hello everybody, Here is yet another proposal (or did I miss something similar?) about the for-with-explicit-indices syntax problems, as discussed in PEP 281 (http://python.sourceforge.net/peps/pep-0281.html). Now that Python has iterators, they could be more explicitely used by user code. Remember that 'for x in sequence' is equivalent to 'for x in iter(sequence)', where iter() is used to get a sequence iterator. As it seems we often loop over sequence elements and occasionnally need an explicit index, I suggest adding a 'count' attribute to sequence iterators that returns the number of items returned so far. This just requires putting the iterator in a local variable. For example, to decrement all positive integers in a list, modifying it in-place: it = iter(lst) for x in it: if x>0: lst[it.count-1] -= 1 No syntax sugar is required. All the trick is in explicitely naming the iterator object used by the loop. Maybe we should have not a 'count' but an 'index' attribute returning the current index, although it is not clear what should then occur if we try to read 'index' before we actually enter the loop (raise a ValueError? Or an AttributeError?). This idea could maybe be extended to make the attribute writeable. For example, inside a loop: it.count += 1 # skip next element it.count -= 1 # process the same element again it.count = 0 # full rewind it.count -= 1; del lst[it.count] # remove bad item from list Does it look reasonable or just plain counterintuitive? Armin. From jonathan at onegoodidea.com Thu Mar 7 04:52:44 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 07 Mar 2002 09:52:44 +0000 Subject: Status of PEP's? References: <1cef615e.0203021254.6bf3658@posting.google.com> <3C82C91C.A60B3242@cosc.canterbury.ac.nz> <3C844D89.31AB890F@cosc.canterbury.ac.nz> Message-ID: On 5/3/2002 4:46, in article 3C844D89.31AB890F at cosc.canterbury.ac.nz, "Greg Ewing" wrote: > * Iterating over parallel lists can be written more > symmetrically with it: > > for i in indices(list1): > do_something_with(list1[i], list2[i]) > > looks better to me than > > for i, item1 in indexed(list1): > do_something_with(item, list2[i]) Yes, but this only works with lists. The point of the 'indexed' proposal is that it works with any iterable object. An arbitrary iterable object may not have a length that is computable in advance, may not be restartable, and quite likely isn't indexable. Jonathan From parker at gol.com Tue Mar 12 18:41:57 2002 From: parker at gol.com (Ian Parker) Date: Tue, 12 Mar 2002 23:41:57 GMT Subject: 15 minute presentation on python? References: <3c7ab974_4@corp.newsgroups.com> <3c7abd92_1@corp.newsgroups.com> Message-ID: In article <3c7abd92_1 at corp.newsgroups.com>, Joshua Muskovitz writes >> > If you had to give a 15 minute introduction to Python, what would you >cover? >> > What is a good example of a simple, but useful, text-based app for a >Wintel >> > environment, that has good "wow" quality? >> >> Who is your audience? What is their background and what types of things >> would they like want to do with a computer? > >They are the tech faculty for the local tech school. It is meant to >demonstrate my ability to teach (something). I have some ideas, but was >looking for a few suggestions. I expect that I won't be able to determine >the expertise of the audience until the last minute, so I'm trying to come >up with a few different levels of topics, and I'll pick one when it happens. > >I think that something demonstrating lists, tuples, and dicts will impress >people who are technical (can program in some language) but haven't seen >python before. Ideas which specifically show successively more complicated >things by adding a few things to the (evolving) source is really the ticket. > >Maybe writing something like wc, then perhaps an indexer (using a dict to >construct a list of references, then producing pretty output). Hmm... I >think I answered my own question. > >Other suggestions are more than welcome. > >-- ># Joshua Muskovitz ># joshm at taconic.net >def lyyrs(sig): return '-'.join(sig.split()+["ly y'rs"]) >lyyrs('Hire me! I need the work!') > > > > >-----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- >http://www.newsfeeds.com - The #1 Newsgroup Service in the World! >-----== Over 80,000 Newsgroups - 16 Different Servers! =----- I wow'd my audience by using Python with the win32 extensions to show simple it was to load data (proxy server log files) into MS Excel. I'd already written a small module to create Excel spreadsheets with neat formatting of column and titles, etc. I simply called this to save a list of lists as a smartly-formatted excel spreadsheet. So my example program developed in four stages: a) read the file data into a list of lists b) sort it c) save it as a spreadsheet d) filter the data to save only a subset of the original data. This worked for my audience because (i) prior to that (i) unable to load proxy server log files into Excel in any reasonable format (2) the data was too large to usefully inspect in its original format (3) they liked the way the smart spreadsheet popped up on the screen - much more impact than just text scrolling up a cmd window. Regards -- Ian Parker From torstenson at no-spam.oti-hsv.com Mon Mar 4 12:31:46 2002 From: torstenson at no-spam.oti-hsv.com (Eric Torstenson) Date: Mon, 4 Mar 2002 11:31:46 -0600 Subject: open() error ---- what am I missing? Message-ID: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com> This is really frustrating for me, and was hoping someone could point me in the right direction. I have a class that I use to generate a log. It handles opens, closes and logging to the file. I have another class which does a lot of other stuff, and occassionally writes messages to the log. The program has worked fine, but when after adding a couple of details (none of which affected the log), I now get: Traceback (most recent call last): File "pLog.py", line 10, in __init__ self.logInit(sFilename) File "pLog.py", line 14, in logInit self.fLog=open(filename, mode='w') IOError: invalid argument: w I have read that you can hide built ins by doing: from some_file import * if some_file an instance of open() exists in the * but I don't have anything like that in my code. The weirder thing, is that I can use the log in other scripts. I have even copied the imports to the test script, and it continues to run without error. Does anyone know how to determine what is hiding the builting open() routine (file() does the same), or how to explicitly call the builtin.open() command? I had trouble with this at the very beginning (I'm still very new to python), but I usually was able to get it worked out. thanks, eric From peter at engcorp.com Fri Mar 1 06:35:01 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Mar 2002 06:35:01 -0500 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> Message-ID: <3C7F6765.94A82394@engcorp.com> Robin Becker wrote: > > . > .... > > > >However, if you are on a 9x platform, and quoting the command just as > >you want the command interpreter to see it on the command line doesn't > >work, you might just want to revert to using the short (non-space) > >version of the name. So in your example you would replace "program > >files" with "progra~1" (or whatever it may be in the unlikely event > >it's different than that). > > > >-- > >-- David > this is win2k. I have tried quoting with "", but I still seem to be > getting > > no such command C:\program etc I'm pretty sure the last time I checked the PROGRA~1 convention still worked on WinNT. Are you sure this doesn't work on Win2K as well? They're supposed to be the same thing, no? -Peter From jimd at vega.starshine.org Thu Mar 21 17:30:44 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 21 Mar 2002 22:30:44 GMT Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: In article , Nick Arnett wrote: >> -----Original Message----- >> From: python-list-admin at python.org >> [mailto:python-list-admin at python.org]On Behalf Of Jim Dennis >[snip] >> I don't know what you're really trying to do, but I decided to >> code up a quickie "word counter" for the hell of it. >Wow -- thanks. I'm going to ask questions more often now! >Nick I deliberately made it a class so you could instantiate multiple word counts on different blocks of text to compare them or whatever, and so you could import it into other programs and use other methods (i.e. a web spider with urllib and a "text" extractor with htmllib) to get your text. With a bit of work this could be cleaned up into a more general class which could then be used as the parent of some more specialized word counters (with different notions of acceptable character sets, and different semantics on handling hypens and apostrophes). In fact it would make alot of sense to simply my Wordcount class and either use it as a base class or put a Decorator class in front of it to impose all the text parsing semantics prior to calling Wordcount.add() I'd definitely factor the "known words" list out of this; possibly as its own class which could be (optionally) used by Wordcount (so you'd decide at instantiation if a "known words" dictionary would be used and (if so) which "known word" sources to use. It would then be possible to use most of that to add support for "stop words" ("words" that would NOT be counted). In practical usage it might be sensible to pickle or shelve the "known words" dictionary since it's moderately expensive to create it at each run-time). Naturally I'd also change the "dump()" method, possibly just returning the dictionary and delegating the sorting, filtering, and analysis of the results to some other class or function. Those bits of refactoring would be pretty simple. Using this in a program that posted the results to your RDBMS should also be easy enough. From maxm at mxm.dk Wed Mar 13 11:48:09 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 16:48:09 +0000 Subject: Why I think range is a wart. References: <873cz44ea8.fsf@bunty.ruud.org> Message-ID: <3C8F82C9.3090308@mxm.dk> ruud de rooij wrote: > perhaps lists should support .keys() and .items() for those operations > (analogous to dictionaries). Yes if that doesn't conflict with anything it would be a very nice way to solve 99% of the cases where I typically use the range function: theList = ['item1', 'item2', 'item3'] subList = ['item4', 'item5', 'item6'] for i, item in theList.items(): print item, sublist[i] But it would not help much in list comprehensions unless they are rewritten: newList = [(theList[i], sublist[i]) for i in range(len(theList))] regards Max M From logiplexsoftware at earthlink.net Thu Mar 21 13:14:35 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 21 Mar 2002 10:14:35 -0800 Subject: How Can I Determine the Operating System with Python? In-Reply-To: References: Message-ID: <20020321101435.56800304.logiplexsoftware@earthlink.net> On Thu, 21 Mar 2002 13:42:03 GMT ingo wrote: > in news:mailman.1016713720.31917.python-list at python.org Mark Gash > wrote: > > > The only way of defining the os name that I have found is then to > > examine the os.environ .By examining the COMSPEC you will be able to > > determine a win 9X machine opposed to an NT or 2000 machine (comspec > > for 9X will show command.com whereas win32 machines will show > > cmd.exe). > > > > >>> os.environ['OS'] > 'Windows_NT' > > No idea what it does on other platforms. It depends upon whether the environment variable "OS" is present, so it's probably less reliable than sys.platform (doesn't exist on RH Linux, at least). -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From fredrik at pythonware.com Sun Mar 3 14:32:03 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 03 Mar 2002 19:32:03 GMT Subject: mx odbc result strings with special characters? References: <24c39b2c.0203021850.7679418c@posting.google.com> <24c39b2c.0203031100.33d57b3d@posting.google.com> Message-ID: Alexander Jerusalem wrote: > Ok, thanks for your reply. Here's my output: > > >>> import mx.ODBC.Windows as odbc > >>> con = odbc.connect("se", "scienceexile", "x") > >>> c = con.cursor() > >>> c.execute("select * from country") > >>> print c.fetchone() > ('aa1', '\xd6sterreich-Ungarn', None, None) > >>> c.close() > >>> con.close() > > And it's the same when I write the resultset to a file, so I don't > believe that it's just a display problem. on the other hand: >>> print '\xd6sterreich-Ungarn' ?sterreich-Ungarn more info here: http://www.python.org/doc/current/tut/node5.html "The interpreter prints the result of string operations in the same way as they are typed for input: inside quotes, and with quotes and other funny characters escaped by back- slashes, to show the precise value" http://www.python.org/doc/current/ref/strings.html http://www.python.org/doc/current/ref/exprstmts.html http://www.python.org/doc/current/ref/print.html (etc) From fredrik at pythonware.com Mon Mar 18 11:27:06 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 18 Mar 2002 16:27:06 GMT Subject: Want to convert images into HSL format References: Message-ID: "F. GEIGER" wrote: > PIL can supply me with RGB data of an image. Does anybody know, how I can > PIL have to transform this into the HSL (aka HSI) model? > > I'm new to image processing, but if I understand the chapter Introducint > PIL -> Concepts -> Mode right, HSL is not mentioned there. Well, I have to > admit, the only two color modes of the mentioned ones I understand are RGB > and CMYK. PIL doesn't support HLS images. if you only need HLS values for individual pixels, you can use the colorsys module in Python's standard library: >>> import Image >>> im = Image.open("lenna.im") >>> im.mode 'RGB' >>> im.getpixel((0, 0)) (226, 161, 119) >>> import colorsys >>> colorsys.rgb_to_hls(*[x/255.0 for x in im.getpixel((0, 0))]) (0.065420560747663545, 0.67647058823529416, 0.64848484848484833) see the library reference for details. From tim.one at comcast.net Mon Mar 11 22:33:01 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 11 Mar 2002 22:33:01 -0500 Subject: PEP 284, Integer for-loops (fwd) In-Reply-To: Message-ID: [Tim] >> Depending on how much overhead you're willing to bear, it's >> straightfoward to write wrapper classes (even using the old >> for/__getitem__ protocol) such that, e.g., adding 1 to every >> element in a table could be expressed via >> >> t = Table(original_table) >> for r in t.rows(): >> for e in r.elements(): >> e.set(e.get() + 1) [James Althoff] > This is nice. We have noticed that there can be a hit in Jython the > first time you instantiate a Python subclass of a Java class (it seems > to build some internal structures based on a lot of Java reflection). I didn't have subclassing in mind; e.g., class Table: def __init__(self, table): self.t = table def rows(self): return RowIterator(self.t) def cols(self): return ColIterator(self.t) class Element: def __init__(self, table, i, j): self.t, self.i, self.j = table, i, j def get(self): return self.t.getValueAt(self.i, self.j) def set(self, value): self.t.setValueAt(self.i, self.j, value) purely in Python. Your original table type is incorporated by containment here, not subclassing. Now you just need to define RowIterator and ColIterator. For example, picking on rows, and in a way that makes "a row" an object in its own right: class RowIterator: def __init__(self, table): self.t = table # Unclear whether these guys are 0-based or 1-based. # This assumes 0-based. Fiddle accordingly. self.limit = table.getRowCount() def __getitem__(self, i): if 0 <= i < self.limit: return Row(self.t, i) else: raise IndexError class Row: def __init__(self, table, i): self.t, self.i = table, i def get(self, j): return self.t.getValueAt(self.i, j) def set(self, j, value): self.t.setValueAt(self.i, j, value) def elements(self): return RowElementIterator(self.t, self.i) class RowElementIterator: def __init__(self, table, i): self.t, self.i = table, i self.limit = table.getColumnCount() def __getitem__(self, j): if 0 <= j < self.limit: return Element(self.t, self.i, j) else: raise IndexError That implements more than the example at the start actually needs; cut back to taste . > We could implement a Java subclass instead. But we are trying to > minimize the appearance of needing to resort back to Java for what are > probably obvious reasons. But I think it might be worth having this > option for times when performance isn't an issue and looping through > all rows or columns is required. I would rather do it with the new > iterator stuff that is available in C-Python, but ... oh well. The new iterator stuff makes coding this kind of thing clearer and easier, but the visible *interface* need not change at all. This is actually well-suited to the __getitem__ protocol: that was designed with sequential indexing in mind, and that's what you're doing here The new iterator protocol is an enormous improvement only when sequential indexing is a strain (like, e.g., in tree traversal). > ... > Some helper functions might be convenient. They would be most > convenient in a helper utility module, of course, so that we could > standardize them for the entire development team. A twist that we > have to live with is that the 3rd party components are not always > consistent with each other. JTable and DefaultTableModel both use > "getRowCount()". So we could have a generic function for these. But > another 3rd party component uses "getNumberOfRows ()" instead. So we > would have to do the try:except:/hasattr/isinstance stuff to make the > helper functions generic. Probably worth giving it a try. I'd try a dict, mapping types to unbound methods, like: rowcounter = {JTable: JTable.getRowCount, DefaultTableModel: DefaultTableModel.getRowCount, ThirdPartyBozo: ThirdPartyBozo.getNumberOfRows} def ri(table): "Return indices of table rows." return range(rowcounter[type(table)](table)) I don't know whether that works exactly as-is in Jython, but you get the idea. Unless you have an unbounded number of classes (a bad Smalltalk habit you should have given up by now ), using dicts to add "conceptual members" to classes is an effective technique. there's-more-than-one-to-do-indirection-in-python-ly y'rs - tim From aleaxit at yahoo.com Tue Mar 26 15:41:00 2002 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 26 Mar 2002 12:41:00 -0800 (PST) Subject: [Python-Help] Re: How to get a key from dictionary? In-Reply-To: <002d01c1d504$d0749010$08020196@Jonah> Message-ID: <20020326204100.576.qmail@web9302.mail.yahoo.com> --- Matthew Sherborne wrote: > Sorry to be a show off, but I reckon that this way > may be faster. Sorry again. The other replies are > very helpful. :) > > def findKey(val): > for key, value in dict.items(): > if value == val: return key > return None Apart from the crucial defects of [a] returning a "random" key if more than one has the sought-for value and [b] not knowing when None is returned if no key was found OR None was the "random" key, this is NOT faster than looping on dict, or even, if you are stuck with old (<2.2) Python, at least on dict.keys(). dict.items() must prepare a list of N tuples, and that's typically slower than it takes to do N key-to-value lookups. And let's not even get into using the name of a built-in type (dict) as a GLOBAL variable, as this code seems to be doing. dict is only a built-in in 2.2 and later, but there's no reason to use it even for earlier releases, and it does risk messing some things up. If you must have a global (and you shouldn't), call it adict, thedict, somedict, ... I keep suggesting: def findKeys(adict, aval): return [k for k in adict if adict[k]==aval] or the obvious equivalent with adict.keys() if you're stuck with some old Python such as 2.1. Returning a list is obviously the right approach since you're returning something of which there could be 0, 1, 2, ..., N occurrences. And a list is built easily and fast with a list comprehension. So, why not? Alex __________________________________________________ Do You Yahoo!? Yahoo! Movies - coverage of the 74th Academy Awards? http://movies.yahoo.com/ From skip at pobox.com Mon Mar 18 16:51:01 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Mar 2002 15:51:01 -0600 Subject: Python on VMS? In-Reply-To: <33e9195e.0203181315.6d841d4a@posting.google.com> References: <33e9195e.0203181315.6d841d4a@posting.google.com> Message-ID: <15510.24901.305918.528315@beluga.mojam.com> Dan> Is Python available on VMS? There are two links given in the FAQ. Dan> One points to a non-existant file and the other declares that the Dan> contents have been erased and not made available elsewhere. Dan> (Someone should really update the FAQ.) Updated, but probably not in the way someone searching for a VMS port might have hoped: http://www.python.org/cgi-bin/faqw.py?query=VMS&querytype=simple&casefold=yes&req=search If anyone stumbles upon references to VMS or OpenVMS ports of Python, let me know and I'll update the answer again. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From ykingma at accessforall.nl Sun Mar 31 14:27:09 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sun, 31 Mar 2002 20:27:09 +0100 Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: <3CA62CD8.6ABD44D0@accessforall.nl> <3CA6F012.E2631003@accessforall.nl> Message-ID: <3CA762EF.F90D942B@accessforall.nl> Martin, you wrote: > > Ype Kingma writes: > > > I'd like to know whether this PEP merging all numeric types would also merge > > the bool type into its evt. hierarchy. > > See for yourself: > > http://python.sourceforge.net/peps/pep-0228.html Quote from PEP 228: Suggested Interface For Python's Numerical Model While coercion rules will remain for add-on types and classes, the built in type system will have exactly one Python type -- a number. There are several things which can be considered "number methods": 1. isnatural() 2. isintegral() 3. isrational() 4. isreal() 5. iscomplex() End of quote. While I wouldn't mind for bool to implement this interface, I would object to True.isnatural() to return True, and also to True.isintegral() to return True. > http://python.sourceforge.net/peps/pep-0242.html This is the one about numerical kind objects allowing for predetermined numerical precision. Since the minimal precision of a numerical kind from this PEP is one decimal digit it would probably never allow for a number with only two usable values. > > > Notice that the relationship of bool and int has two aspects: one is > > > whether you can combine them in numeric operations, > > > e.g. 28+isleap(year). There is absolutely no way to remove this > > > property from the language - too much code would break if that would > > > raise an exception. > > > > There are two ways to do this: > > - marking such code with: from __past__ import nonbool > > (as I remarked earlier this is rather radical) > > I hate the __future__ statement, so I definitely don't want to get a > __past__ statement. Following PEP 5, you will need a phased > introduction strategy for booleans if you don't want to interact them > with numbers. Don't expect to get this in this decade, though. > For backward compatibility I don't mind interacting booleans with numbers. The coercion framework is there, it only needs to be extended with the bool class (sigh.) > > > - defining __add__ and __radd__ in the int and float classes to also > > accept a bool sounds quite pythonic and acceptable to me. > > That would work, but only somewhat. There are other places where > booleans need to act as integers, e.g. indexing: array[b] ought to > work, for backwards compatibility, even if b suddently turns into a > boolean. That means that every __getitem__ implementation needs to > become aware of booleans - so likely a lot of code would break. > Only user code __getitem__ implementations that already use booleans for indexing would break. When these are the only ones that would break I think deprecation would be quite acceptable to handle them, especially because the fix only consists of inserting an int() call. Indexing a dict with both int and bool keys might involve some confusion when True is not 1 anymore. This case should be rare, however. Slices should be no problem: they only need int values, so the evt. int() call can be provided when a slice is created. > > An Square that is a Rectangle has inherits two degrees of freedom, > > (height and width) which have to constrained to a single one in the > > implementation. > > Implementing such constraints is a bit awkward > > That depends on the rectangle interface. If rectangles are immutable, > implementing the constraint is straight-forward, not awkward. > > class Rectangle: > def __init__(self, x, y, w, h): > self.x,self.y,self.w,self.h = x,y,w,h > > def area(self): > return self.w*self.h > > class Square(Rectangle): > def __init__(self, x, y, w): > Rectangle.__init__(self, x, y, w, w) > Even in the non mutable case the redundancy of self.w and self.h has to be accepted here. > > When bool is-a int, one would have to (awkwardly) implement at least > > one such constraint, namely that bool values can only be 1 or 0. > > Not at all. Bools are immutable, and singletons. If bool would not > inherit from int, nothing in the implementation would change; see the > PEP. I meant that the implementation would need to select the appropriate singleton instead of computing the integer as inherited in the is-a int case. All this leaves me in favour of PEP 285 with some remarks: - use of current booleans in user code __getitem__ implementations should be deprecated with indication of the int() fix. After this a bool should not be an int anymore. - Once a bool is no more an int, the implementation of backward compatible 0/1 numerical behaviour could be done in __add__, __radd__, __cmp__, __rcmp__ and similar methods of the bool and/or numerical classes and in __getitem__ methods of indexable classes. Regards, Ype P.S. Thanks for putting up with the typo's. Waking up takes more time some days. -- email at xs4all.nl From amckay at merlinsoftech.com Wed Mar 20 15:55:07 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Wed, 20 Mar 2002 12:55:07 -0800 Subject: How to pass a dtml-var to a python script. In-Reply-To: References: Message-ID: <200203202053.g2KKrtq01211@mail.merlinsoftech.com> If you are placing the things in REQUEST, you dont need to pass them, you can just extract them from the REQUEST. In CMAPContext: ssn = context.REQUEST.SESSION print ssn['tissue'] Sticking the parameters in REQUEST and passing them through is not always the best way, a more explicit approach is usually better. On March 20, 2002 11:57 am, Mike wrote: > I am New to python and Zope and am confused about how to pass a value > I hold inside of a to a python script: here's what I > am doing(or doing wrong): > > > > > > > myHistology, mySubtype)"> > > ContextSession is a python script that extracts parameters from the > URL and puts > them inside of the REQUEST.SESSION.choices placeholder. I then want to > take them > out of the session and pass them to the CMAPContext() python script, > but the way I am doing it doesn't work and I can't find any > documentation on how to do this. > > Thanks, > > Mike -- Andy McKay From sholden at holdenweb.com Fri Mar 29 08:55:51 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 08:55:51 -0500 Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: <7o_o8.17314$Ou.7311@atlpnn01.usenetserver.com> "Fused" wrote in message news:3ca43ef4.3666136 at news.tudelft.nl... > I'm currently trying to master Python, but to succeed I need to > exercise. However, I detest building programs that have already been > built a kazillion times and aren't of use to anyone. > Can anyone think of a program that I could build that would actually > have use to someone (you?)? I'm trained in Delphi, know some Java and > rudimentary C, so the programs don't need to be newbie-easy ( I like a > challenge: the greater the challenge, the faster I'll learn ;-) ). I'd really like to see a Python mail/newsreader. That would teach you a lot, and keep you busy for a while... regards Steve From phr-n2002a at nightsong.com Tue Mar 5 00:51:33 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 21:51:33 -0800 Subject: Order of constructor/destructor invocation References: Message-ID: <7xd6yjsgt6.fsf@ruckus.brouhaha.com> "Reginald B. Charney" writes: > In Python, are destructors defined to be invoked in reverse order of > constructors? Huh? No, of course not. The destructor is called when the last reference goes away. That can happen in any order. > Basically, I need to know if the order of destruction is guaranteed to be > the reverse of construction when reference counts on the objects are the > same (e.g., 1 on this case). Without this guarantee, I don't understand how > Python can effectively use destructors - it falls into the same hole as > Java. For me, this is a show-stopper. When the ref count is 1, the object is still alive. From rjk at grauel.com Mon Mar 18 11:34:49 2002 From: rjk at grauel.com (Richard J. Kuhns) Date: 18 Mar 2002 16:34:49 GMT Subject: A question about generators Message-ID: <858z8pg7h8.fsf@moriarity.grauel.com> I'm a relative newbie with python, so please be gentle. I have an application where I think either an iterator or a generator would be ideal, but I have to be able to reset whichever I use. The paper "What's New in Python 2.2" says that there's no way to reset an iterator, so that's out. Is there a straight-forward way to reset a generator, though? My specific application (I'm using SWIG to generate an interface to a third-party binary-only library, so I have to use the API as is) is approximately as follows (pretend we're looking through a sorted flat text file): 1) Select a starting point. For this particular instance, selecting the starting point won't necessarily involve an exact match with whatever was supplied as an argument. 2) Iterate through the file one line at a time until we either find something interesting or hit the end of the file. 3) Do it all again with a different starting point. I realize that there are several ways to write the loop I just described, but I'd like to be able to use a single API for all searches, something like this: while 1: inkey = raw_input('Well? ') # there are also several variants like 'generate_exact_matches' for i in generate_appox_matches(inkey): if this_is_interesting(i): do_work(i) break There's an assumption that if we find anything with the comparable generate_exact_matches(), they're all interesting. Should I just keep a variable around that keeps the last value of inkey and compare them inside the generator each time? That'll make the generator code a lot more convoluted. There are several different calls to library functions that may return a potentially interesting value, but it's possible. Any style suggestions will be greatly appreciated. - Rich -- Richard Kuhns rjk at grauel.com PO Box 6249 Tel: (765)477-6000 \ 100 Sawmill Road x319 Lafayette, IN 47903 (800)489-4891 / ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With NINE Servers In California And Texas - The Worlds Uncensored News Source From tist at subdimension.com Fri Mar 8 11:41:10 2002 From: tist at subdimension.com (Tist Verdonck) Date: 8 Mar 2002 08:41:10 -0800 Subject: How to compute sunset and dawn times with python? Message-ID: <22722a23.0203080841.3ed7166a@posting.google.com> Does anyone know how to compute sunset and dawn times with python? thanx, Tist From wayne at mishre.com Mon Mar 4 23:30:27 2002 From: wayne at mishre.com (Wayne Pierce) Date: Mon, 04 Mar 2002 20:30:27 -0800 Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> <23891c90.0203040402.86c594d@posting.google.com> Message-ID: <3C8449E3.10709@mishre.com> Paul Boddie wrote: > ddoc wrote in message news:... > >>>I'm looking for a piece of software to aid in reviewing a document >>>through the web - click on a paragraph tag, have the comment added >>>(highlighted in some way). >>> >>Is this what Annotea (Annotation server from the W3C), Third Voice (now >>defunct , and to a lesser extent Allegra are for? >> > > I would think so. Unfortunately, Amaya is probably the only browser > that supports annotations, however. > > Paul > There's a plugin in for Mozilla linked from the W3C site and I think I saw something about a plugin for IE either available or in the works. They also have partial support for making the annotations with any JavaScript enabled browser, although it didn't provide the full capabilities. -- Wayne Pierce web: http://www.mishre.com email: wayne at mishre.com "What you need to know." From bokr at oz.net Sat Mar 9 18:42:58 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 23:42:58 GMT Subject: Tokenize a string or split on steroids References: <4lpj8u4nbsoqjf2h4upadti62jh4sf4i59@4ax.com> <3C89F25F.A560003F@verizon.net> Message-ID: On Sat, 09 Mar 2002 18:10:14 +0100, Fernando Rodr?guez wrote: >On Sat, 09 Mar 2002 11:30:40 GMT, Bob Follek wrote: > > >>If you're unfamiliar with regular expressions, here's a good starting >>point: http://py-howto.sourceforge.net/regex/regex.html > >Thanks. :-) BTW, the strings that must be tokenized contain other non >alphanumeric characters (parenthese, for example), so I tried another regex: >[{}]. > >The result, although usable, is sort of weird: > >>>> s = "{one}{two}" >>>> x1 = re.compile('[{}]') >>>> x1.split(s) >['', 'one', '', 'two', ''] > >Where are those empty strings coming from??? :-? >I can filter() them out, but I wonder where they come from.... O:-) Think of the commas in the list as places where your pattern matched. There was nothing in front of the leading match, so that's represented by ''. Note that there are two commas between 'one' and 'two' -- your pattern matched twice, because it was a single character. If you change the pattern to '[{}]+' you will get a single comma between 'one' and 'two', but the end matches will be unchanged. Of course with that change, "{one}{}{}{two}" will give the same result as "{one}{two}", so caveat . You can think of join as replacing the commas with the join string, e.g., note what happens when you use join on the result above using '!': >>> '!'.join(['', 'one', '', 'two', '']) '!one!!two!' This comma talk is just a mnemonic of course, don't take it literally ;-) Regards, Bengt Richter From mirv123 at yahoo.com Wed Mar 27 11:18:02 2002 From: mirv123 at yahoo.com (Andres Jaime) Date: 27 Mar 2002 08:18:02 -0800 Subject: urllib threads? Message-ID: <92994965.0203270818.500f3665@posting.google.com> I'm creating a thread as follows: class t(Thread): def __init__(self, url, out_file_name, proxy): Thread.__init__(self) self.url = url self.out_file_name = out_file_name self.proxy = proxy def run(self): get.Get(self.out_file_name, self.url, HTTP_PROXY = self.proxy) where get.Get is defined as follows: (I found this code here in comp.lang.python and subsequently modified it to log) def Get(out_file_name, url, HTTP_PROXY=None, ACCEPT_HEADER=None, SHOW=None, **fields): proxy = None if HTTP_PROXY: proxy = { 'http': HTTP_PROXY } d = [] for key, value in fields.items(): d.append('%s=%s' % (key, urllib.quote_plus(value))) args = string.join(d, '&') if args: request = url + '?' + args else: request = url try: u = urllib.FancyURLopener(proxy) if ACCEPT_HEADER: if type(ACCEPT_HEADER) != type(''): ACCEPT_HEADER = string.join(ACCEPT_HEADER, ',') u.addheader('Accept', ACCEPT_HEADER) fn, h = u.retrieve(request) u.cleanup() except: str = '' urlcleanup() if HTTP_PROXY == None: str = 'error getting url: ' + url + '\n' else: str = 'error getting url: ' + url + ' through proxy: ' + HTTP_PROXY + '\n' outfile = open(out_file_name, 'a') outfile.write(str) outfile.close() else: str = '' if HTTP_PROXY == None: str = 'success getting url: ' + url + '\n' else: str = 'success getting url: ' + url + ' through proxy: ' + HTTP_PROXY + '\n' outfile = open(out_file_name, 'a') outfile.write(str) outfile.close() when I create an instance of the class t and call t.run(), the main thread blocks untill the page has been requested and then the function get.Get() logs either error or success in the logfile. On the other hand, when I create an instance of class t and call t.start() (because it inherits Thread, start will spawn a new thread and subsequently call run()), I see evidence of neither success or failure in the log file, which leads me to believe that the thread is either not being spawned correctly, or that it's dying in u.retrieve() somehow? does anyone have any insight into this problem (issues with urllib and multithreading, etc) -andres ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Andres Jaime Lucira Technologies, Inc. What would you do if someone stole your laptop? Protect your hardware and sensitive data with MobileSecure Now available for Download: http://www.lucira.com ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From hdiwan420 at speakeasy.net Thu Mar 21 21:59:49 2002 From: hdiwan420 at speakeasy.net (hdiwan420 at speakeasy.net) Date: Fri, 22 Mar 2002 02:59:49 -0000 Subject: How Can I Determine the Operating System with Python? References: Message-ID: ingo writes: > >>> os.environ['OS'] >'Windows_NT' If you have nmap or queso installed, you can always do: % sudo nmap -v -v -v -sS -O localhost or % sudo queso localhost Ok, so it's not exact, but it's just as good as any other way and both exist on Windows and Unix. -- Hasan =) GPG KeyID: 0xBE42DCA6 Fingerprint: 1CB0 47E3 0A24 DAC1 DCCA 4225 F166 40C2 BE42 DCA6 From newsfroups at jerf.org Mon Mar 25 11:37:08 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Mon, 25 Mar 2002 16:37:08 GMT Subject: Streaming XML-RPC? References: Message-ID: <3C9F51EE.5000203@jerf.org> Magnus Lie Hetland wrote: > I'm thinking about implementing a library that uses the xml-part of > XML-RPC (i.e. XML-RPC without the HTTP) in two-way persistent stream > (tcp socket) somewhat like Jabber, to improve performance. Why not Jabber? Jabber is meant to do that. It's designed to do that. It's *begging* you to use it that way. This is in stark contrast to HTTP. HTTP thinks you're nuts. HTTP will fight you tooth and nail. HTTP is old, and hoary, and set in her ways. And XML-RPC isn't exactly ecstatic about being streamed, either. Why fight the system when you can work with another one? From i.linkweiler at gmx.de Thu Mar 21 17:46:26 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Thu, 21 Mar 2002 23:46:26 +0100 Subject: PyQT, how to compile SIP on MAC? Message-ID: <3C9A62C2.ABA9AE5D@gmx.de> Hi, I am willing to use PyQt on Mac OS X But I was not able to compile SIP -- http://www.river-bank.demon.co.uk/software/sip-3.0.tar.gz Are there any hints you can give to compile SIP with success? With windows and linux it works fine. regards, Ingo From chris.gonnerman at newcenturycomputers.net Mon Mar 4 11:35:47 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 4 Mar 2002 10:35:47 -0600 Subject: Twain Scanners and some other questions References: <3C8396F9.199D3E6B@sage.att.com> Message-ID: <005801c1c39a$a5418900$0101010a@local> ----- Original Message ----- From: "Garry Hodgson" > Jimmy Retzlaff wrote: > > > > dix wrote: > > > I need to know if there is a free library for Python to manage Twain > > > scanners in order to pilot the scanner and have an image > > representation > > > of the paper document. > > > > The wonderful Daily Python-URL (http://www.pythonware.com/daily) just > > pointed to http://twainmodule.sourceforge.net a few days ago. > > but this only works on windows, making it useless for real computers. Ah, dix is interested in *TWAIN* scanner drivers, so necessarily that means Windows. The TWAIN driver interface isn't used outside the M$ world AFAIK. From sumner-nntp5 at forceovermass.com Tue Mar 26 11:38:34 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Tue, 26 Mar 2002 16:38:34 GMT Subject: Python vs. C/C++/Java: quantitative data ? References: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> Message-ID: Eduard Smirnov wrote: > I?m writing a diploma paper on the difference between scripting (e.g. in > Python or Tcl) and system programming (e.g. in C, C++ or Java) Why do you call Python "scripting" and Java "system programming"? I do system programming in Python all the time. > one of the claims I want to make is that you can often develop applications > 10x or more faster in a scripting language. Shouldn't you gather some data first and then form a hypothesis to test? Doug Bagley has an interesting paper on the subject. Google for "Bagley shootout" or similar. > If you have any experience in writing applications in system programming > language (e.g. in C, C++) and re-writing it in scripting language (e.g. > Python) or vice versa, please compare your work in both implementations, I did rewrite a simple SQL query utility in Python that was previously implemented in Java (in preparation for some major new dev work on the code). It's a stupid case; it essentially read many rows out of a database, did some transformations on them and dropped some rows according to simple rules, then output an ASCII file which was a sort of precompiled data file to be used as input by another (C) program. The original Java was around 1000 lines of code and ran in around 40 seconds. The Python was around 200 lines of code and ran in around 25 seconds. But it's a stupid case, performance differences are likely because of different SQL drivers and file/network I/O performance. Neither implementation was optimized at all, both were fast enough. I really can't compare dev time: the Java implementation went through a couple of versions and I had to gather requirements and make major design decisions while implementing it. The Python was a simple rewrite that took only an hour or two. But a rewrite is always much faster than an original implementation (the C program was developed over months, but at one point a fairly substantial refactoring which resulted in a (one piece at a time) rewrite of 50% of the code took only a few days) if you're concentrating only on cleaning up the code and not on gathering requirements and implementing new features. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From mwh at python.net Tue Mar 26 06:01:06 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 26 Mar 2002 11:01:06 GMT Subject: starting a python program from within xemacs References: <1017098019.357959@DS9.ai-lab.fh-furtwangen.de> Message-ID: jimd at vega.starshine.org (Jim Dennis) writes: > In article <1017098019.357959 at DS9.ai-lab.fh-furtwangen.de>, Marco Herrn wrote: > > > Hi there, > > > sorry if this is the wrong newsgroup to ask, but I tried in > > comp.emacs.xemacs and nobody could help me, probably because too few > > people there code in python :-) > > > I develop a program that uses the curses library in xemacs. But for > > testing my program I have to save it in xemacs, switch to a terminal and > > call python myprog.py. Because I use curses, a C-c C-c doesn't work > > because the xemacs output window isn't capable of using curses. > > > Is there a way to execute the content of my current xemacs buffer in a > > terminal/x-terminal? > > > Bye > > Marco > > > -- > > Marco Herrn herrn at gmx.net > > More to the point, is there a way to direct the Python curses module > to use an alternative terminal/device? There's no wrapper for newterm, so not really, no. Also tput is more-or-less impossible to wrap sensibly, so you'd have to do delays by hand, if you care about such things. > This would be handy for other situations as well (for example when > running interactively via idle or from an xterm or a Linux/FreeBSD > virtual console). It would be nice to have the interactive prompt > and output decoupled from the "user's" I/O --- especially when > playing with the curses module. http://www.python.org/patches/ :) > I suppose I could try reading the Python curses sources and looking > for the place where it sets up its terminal context. Adding a wrapper for newterm probably isn't that hard, and is, I think, the right thing to do here. Cheers, M. -- Considering that this thread is completely on-topic in the way only c.l.py threads can be, I think I can say that you should replace "Oblivion" with "Gravity", and increase your Radiohead quotient. -- Ben Wolfson, comp.lang.python From lac at strakt.com Fri Mar 22 13:33:13 2002 From: lac at strakt.com (Laura Creighton) Date: Fri, 22 Mar 2002 19:33:13 +0100 Subject: "Zope-certified Python Engineers" [was: Java and Python] In-Reply-To: Message from "John J. Lee" of "Thu, 21 Mar 2002 21:07:23 GMT." References: Message-ID: <200203221833.g2MIXDrq005253@ratthing-b246.strakt.com> >On Thu, 21 Mar 2002, John J. Lee wrote: > >In general, and for a Python archive in particular, I guess there are two >problems: which metadata, and which software. So, what's wrong with the >web + Google (not saying there isn't anything wrong, just interested in >how you would improve on it)? The problem is more with web-sites, than with Google, though Google has made its own little problem. Most people only visit the top 3 or 5 hits that Google finds. So, if you make a query, and web-page 7 is the best of the lot, you will still tend to read the top 3. There isn't any way to say 'this site was useless for me, consider me one unhappy customer'. Now consider the case where site number 15,899 is your best bet. Unless you can come up with the sort of search terms that makes this site come up higher -- you are never going to see it. This is a neat problem. One days reading of your weeks spam will yield you many offers of programs and advice on how to make your website rise in the Google ranking. This reflects the reality that once you have made it to the top, you basically stay there, so an effort really pays off. These companies are, of course, fuelling an arms race, but then some of them are advising metadata, so I do not mind all that much. The deeper problem is one of the web itself. A few months ago, I wasted 3 days trying to find either a) a bug in my Haskell program, and when that looked very unlikely b) a bug in the floating point of my C libraries. That looked real promising. Alas, the real problem was that the formula I had taken from the most popular Google site for finding the formula I was interested in making into an algorithm had a + sign where what belonged was a minus sign. I can't report this; I can't get it fixed; and right now some other poor soul may have done exactly what I did. This is worrysome We now have too much information at our disposal, vastly too much, when throughout history we were more likely to have too little. The problem now isn't finding stuff -- it is knowing how trustable the stuff is. EBay has one sort of approach. So does Advogato (see http://advogato.org ). It is a real problem and one that interests me a lot. >[OT: A question I've asked many times and got no answer to is 'why has >nobody done self-consistent ranking for academic papers'? I fear the >answer is simply that most of the data is owned by a small number of >companies who, as a result, have no real incentive to advance the state of >the art. Still, maybe somebody out there is trying to do it...] Oh yes! Many people have been trying to do this. See http://www.isinet.com/isi/news/2001/productnews/8117876/index.html for one attempt. > > >John From pan-news at asheeshenterprises.com Fri Mar 15 23:37:14 2002 From: pan-news at asheeshenterprises.com (Asheesh Laroia) Date: Sat, 16 Mar 2002 04:37:14 GMT Subject: Connecting to a Gnutella-network References: Message-ID: <_Zzk8.99683$nl1.16550715@typhoon.nyroc.rr.com> Check out http://wvware.sourceforge.net/libwmf.html . While it's not in Python, it should compile anywhere you can stuff GCC, and you can always either (1) write Python-to-C glue code for it, or (2) just call it from a command line. -- Asheesh. On Fri, 15 Mar 2002 14:05:45 -0500, phil hunt wrote: > On Fri, 15 Mar 2002 14:33:19 GMT, Thomas Weholt > wrote: >>Hi, >> >>I've looked at the Gnutella Protocol, v.0.4, and wondered about trying >>to create an implementation in python. I'm a newbie when it comes to >>this sort of thing, but have created several simple to complex server >>types of applications using SocketServer and its friends like >>BaseHTTPServer etc. >> >>Has anybody tried to do this before? Does anybody have pointers for >>newbies like me in such a project ( how to start, how to connect to >>nodes on a gnutella network etc. ) > > I personally haven't, but there are several open-source Gnutella > clients, just waiting there for you to inspect the code. > From amoustafa at pobox.com Thu Mar 21 23:35:26 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Fri, 22 Mar 2002 04:35:26 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C9991C0.4080102@pobox.com> <3C99D770.57345464@engcorp.com> Message-ID: <3C9AB46C.2020407@pobox.com> Peter Hansen wrote: > Ahmed Moustafa wrote: > >>Peter Hansen wrote: >> >>>Communication skills are, first and foremost, the thing I >>>look for in hiring. [...] Next are adaptability [...] >>>Design skills are useful. Debugging skills are very valuable [...] >>> >>Peter, what do you think about qualifying problem sets like what >>arsDigita had? >> > > I think that's an interesting sounding name for something. > What is it? I'll assume (without taking the time to try > to figure it out... care to tell me?) that those are basically > little exams which they use to judge candidates. If so, > you already know my answer: as I said, specific knowledge > of language syntax is secondary, since I'm more concerned > about finding people with the skills I mentioned. > They are the problem sets of Philip Greenspun's MIT course Software Engineering for Web Applications (6.916) . > If arsDigita (you'd think a company would know enough not > to put the word "arse" in their name...) It's owned by Red Hat now. > has tests which > evaluate communication skills, flexibility and ability > to learn new things, and design and debugging skills, > then I think their qualifying problem sets are a very > good idea... I think yes the problem sets evaluated the parameters you mentioned. -- Ahmed Moustafa From BgPorter at NOartlogicSPAM.com Tue Mar 5 13:52:33 2002 From: BgPorter at NOartlogicSPAM.com (Brett g Porter) Date: Tue, 05 Mar 2002 18:52:33 GMT Subject: Order of constructor/destructor invocation References: Message-ID: "Justin Sheehy" wrote in message news:mailman.1015350430.26774.python-list at python.org... > "Reginald B. Charney" writes: > > Perhaps you are using "destructors" to refer to some concept that is > different from what the rest of us use that word for? No, based on what he wants to do (and his observation that Python suffers from the same 'misdesign' as Java) it's pretty clear that he's using 'destructor' in the C++ sense, since C++ dtors have exactly the behavior he's looking for. As someone who needed a year or so to separate the C++ and Python halves of my brain, I sympathize, and can only urge (as gently as possible) Mr Charney to think Pythonically , instead of dealing with the frustration of expecting Python to follow C++'s rules. Down that path lies madness. -- // Brett g Porter * Lead Engineer, Development Practices // BgPorter at artlogic.com * www.artlogic.com // Art & Logic, Inc. * software engineering and design // Desktop * Embedded * Web From skip at pobox.com Wed Mar 6 15:47:39 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 14:47:39 -0600 Subject: Web scripting with Python (1st post here, also :-) In-Reply-To: <40c3f5da.0203061114.18f7fea6@posting.google.com> References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: <15494.32875.245451.970310@beluga.mojam.com> Julio> I am used to do web scripting using PHP. As a new adventure, I am Julio> trying to learn Python.... Julio> So, I am looking for examples that might help me. Yes, I saw Julio> Zope. Waaaaay too much.... Julio> .... Where do I start? It's for a weblog (Kuro5hin-like) system. I'm experimenting with Webware's WebKit for a new website for my nascent consulting company. It seems pretty easy to grok, is nicely object-oriented and has several "adapters" - ways of connecting between your web server and its AppServer. My other app-server type experience is with Mason, which I love except it uses the other P-language (the one that ends in "l", not the one that ends in "P" ;-) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From fperez528 at yahoo.com Wed Mar 13 13:32:50 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 13 Mar 2002 18:32:50 +0000 Subject: Question about scientific calculations in Python References: <9gcu8u483cn544anr78k67jsknuv4tb6ks@4ax.com> Message-ID: Martin Kaufmann wrote: > > I tried to use weave.inline. Here is my code. But put your coffee away > before you read it (you might spill it otherwise over your keyboard) > and please don't laugh out loudly.. I really didn't know what I was > doing, but it somehow worked... > I haven't checked carefully, but using blitz type converters does away with some of the low-level manipulations you're using and makes the algorithm vastly more readable. Some example code to get you going. Run it, play with it and then use the ideas therein for your problem. It's stuff I wrote when learning weave usage, so there's various little tests simply to clarify issues. I hope you find it useful, f. # Paste into file below here: """Simple examples of weave use. Code meant to be used for learning/testing, not production.""" import scipy.weave as weave from scipy.weave import converters from Numeric import * #----------------------------------------------------------------------------- def simple_print(input): """Simple print test. Since there's a hard-coded printf %i in here, it will only work for numerical inputs (ints). """ # note in the printf that newlines must be passed as \\n: code = """ cout << "Printing from C++ (using cout) : " << input << endl; printf("And using C syntax (printf) : %i\\n",input); """ weave.inline(code,['input']) #----------------------------------------------------------------------------- # Returning a scalar quantity computed from a Numeric array. def trace(mat): """Return the trace of a matrix. """ nrow,ncol = mat.shape code = \ """ double tr=0.0; for(int i=0;i x**n. Implemented using the C pow() function. """ support = \ """ #include """ code = \ """ return_val = Py::new_reference_to(Py::Float(pow(x,n))); """ return weave.inline(code,['x','n'], type_converters = converters.blitz, support_code = support, libraries = ['m'], ) #----------------------------------------------------------------------------- def sinC(x): """sinC(x) -> sin(x). Implemented using the C sin() function. """ support = \ """ #include """ code = \ """ return_val = Py::new_reference_to(Py::Float(sin(x))); """ return weave.inline(code,['x'], type_converters = converters.blitz, support_code = support, libraries = ['m'], ) def in_place_multNum(num,mat): mat *= num def ttest(): nrun = 10 size = 6000 mat = ones((size,size),'d') num = 5.6 tNum = time_test(nrun,in_place_multNum,*(num,mat)) print 'time Num',tNum tC = time_test(nrun,in_place_mult,*(num,mat)) print 'time C',tC #***************************************************************************** # 'main' print 'Printing comparisons:' print '\nPassing an int - what the C was coded for:' simple_print(42) print '\nNow passing a float. C++ is fine (cout<< takes care of things) but C fails:' simple_print(42.1) print '\nAnd a string. Again, C++ is ok and C fails:' simple_print('Hello World!') A = zeros((3,3),'d') A[0,0],A[1,1],A[2,2] = 1,2.5,3.3 print '\nMatrix A:\n',A print 'Trace by two methods. Second fails, see code for details.' print '\ntr(A)=',trace(A) print '\ntr(A)=',trace2(A) a = 5.6 print '\nMultiplying A in place by %s:' % a in_place_mult(a,A) print A # now some simple operations with 3-vectors. a = array([4.3,1.5,5.6]) b = array([0.8,2.9,3.8]) print '\nPython and C versions follow. Results should be identical:' print 'a =',a print 'b =',b print '\na.b =',dot(a,b) print 'a.b =',dot_product(a,b) print '\na x b =',cross_product(a,b) print 'a x b =',cross_productC(a,b) print '\nIn-place versions. The second one fails, see code for details.' print 'a x b =',cross_productC2(a,b) print 'a x b =',cross_productC3(a,b) print '\nSimple functions using the C math library:' import math x = 3.5 n = 4 theta = math.pi/4. print '\nx**'+str(n)+'=',x**n print 'x**'+str(n)+'=',powC(x,n) print '\nsin('+str(theta)+')=',math.sin(theta) print 'sin('+str(theta)+')=',sinC(theta) From newgene at bigfoot.com Wed Mar 27 00:19:02 2002 From: newgene at bigfoot.com (newgene) Date: 26 Mar 2002 21:19:02 -0800 Subject: Can I use python code to login a website? Message-ID: Hi, group, I am wondering if possible to use python code to login a website need username and password, like mail.yahoo.com. Another type of website is poping up a authorization box asking for username and password instead of a input form within the webpage. Thanks you in advance. Newgene From grey at despair.dmiyu.org Fri Mar 29 16:11:48 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 29 Mar 2002 21:11:48 -0000 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: On Fri, 29 Mar 2002 10:48:15 GMT, Benjamin Schollnick wrote: > IF X == 0: > DO_THIS () > ELIF X == 2: > DO_THIS (2) > ELIF X == 4: > DO_THIS (X+2) > ELIF Y == 6: > DO_THIS() > ELIF Z == "ZEBRA": > DO_THIS ( ZEBRA ) > ELSE: > DO_NOT_DO_THIS () > But, this routine is not exactly readable compared to a case: > CASE X of: > 0 : DO_THIS() > 2 : DO_THIS (2) > 4 : DO_THIS (x+2) > 6 : DO_THIS () > ELSE: > DO_NOT_DO_THIS() its_called_a_directory_pointing_to_functions = {'case':closed} I do not believe that any language which can have a hash of function pointers has any business with a case statement. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From phd at phd.pp.ru Fri Mar 22 06:04:20 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Fri, 22 Mar 2002 14:04:20 +0300 Subject: Word frequencies -- Python or Perl for performance? In-Reply-To: <1o2m9ucoqb9qqs2fcign6sts3ckc3mqkma@4ax.com>; from anders.eriksson@morateknikutveckling.se on Fri, Mar 22, 2002 at 11:48:30AM +0100 References: <1o2m9ucoqb9qqs2fcign6sts3ckc3mqkma@4ax.com> Message-ID: <20020322140420.O21612@phd.pp.ru> On Fri, Mar 22, 2002 at 11:48:30AM +0100, Anders M Eriksson wrote: > > file = open(i,"r") > > for line in file: > Here I get the error ^ > for line in file: > TypeError: loop over non-sequence > > Is this something specific for Python 2.2, or just a typo? Yes, 2.2 only. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From peter at engcorp.com Sun Mar 31 11:08:38 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 11:08:38 -0500 Subject: OT: Daylight savings time (was Re: Subclass sadness (was Re: [Python-Dev] PEP 285: Adding a bool type)) References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> Message-ID: <3CA73486.72B4059F@engcorp.com> Richard Jones wrote: > > On Sun, 31 Mar 2002 15:46, Andrew Koenig wrote: > > The other way around -- inheriting rectangle from square -- would > > seem to make more sense because a rectangle has all the information > > that a square does, and then some. But that doesn't really work either, > > because then you can no longer assume that every kind of square is > > really a square. After all, it might be a rectangle. > > Hrm, just following this thought here, possibly for no good reason at all > (hey, it's Sunday, and daylight savings just ended so I've got a whole _hour_ > extra to waste today :)... In which country? Good thing it's not a work day, since I took your word for it last night... or was that another advance April Fools joke? -Peter From rasmussn at lanl.gov Fri Mar 29 12:52:05 2002 From: rasmussn at lanl.gov (rasmussn at lanl.gov) Date: Fri, 29 Mar 2002 10:52:05 -0700 Subject: Anyone need a program written? In-Reply-To: Message-ID: On Friday, March 29, 2002, at 10:46 AM, phil hunt wrote: >> "Fused" wrote in >> message news:3ca43ef4.3666136 at news.tudelft.nl... >>> I'm currently trying to master Python, but to succeed I need to >>> exercise. However, I detest building programs that have already been >>> built a kazillion times and aren't of use to anyone. >>> Can anyone think of a program that I could build that would actually >>> have use to someone (you?)? I'm trained in Delphi, know some Java and >>> rudimentary C, so the programs don't need to be newbie-easy ( I like a >>> challenge: the greater the challenge, the faster I'll learn ;-) ). How about a Python substitute for make. Craig From dmitry at athabascau.ca Fri Mar 22 15:58:47 2002 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Fri, 22 Mar 2002 13:58:47 -0700 Subject: Copmlex structures.... Message-ID: Hi. The problem itself is - I want to use complex structures like described below, but i want it another way.... 01. >>> f={} 02. >>> f['name']='dimon' 03. >>> f['age']=20 04. >>> a=[] 05. >>> a.append(f) 06. >>> print a 07. [{'age': 20, 'name': 'dimon'}] 08. >>> f['age']=22 09. >>> print a 10. [{'age': 22, 'name': 'dimon'}] I don't like result in the last like I've expected to have [{'age': 20, 'name': 'dimon'}], how could i do this? I know that it must be as simple as using something like b[:], but what? WBW, Dmitry S. Makovey From david at goodgirldesigns.com Mon Mar 25 18:29:14 2002 From: david at goodgirldesigns.com (dc) Date: 25 Mar 2002 15:29:14 -0800 Subject: Looking for bids Message-ID: <7085ec43.0203251529.527ce980@posting.google.com> We are looking for bids to create an online alumni directory similar to classmates.com using zope/MySQL. We need quotes and timeframes. We will accept bids up to 3/29/02. Thank you. From peter at engcorp.com Sun Mar 31 10:54:19 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 10:54:19 -0500 Subject: string copying References: <3CA4F5CB.E8961330@engcorp.com> <3CA6ABB6.71786096@engcorp.com> Message-ID: <3CA7312B.9B426248@engcorp.com> Aahz wrote: > > In article <3CA6ABB6.71786096 at engcorp.com>, > Peter Hansen wrote: > > > >Yeah, I know. I think you and Aahz missed my (admittedly puny) > >point, which was to hypothesize _at least one case_ where it > >was conceivably desirable by someone to try to copy a string. > > No, I didn't miss your point, I was just chastising you for posting > incorrect code without posting a solution. ;-) Ah, thank you. (bowing) I am still unable to take the stone from your hand. :-) -Peter From tim.hochberg at ieee.org Tue Mar 26 23:09:11 2002 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Wed, 27 Mar 2002 04:09:11 GMT Subject: Most efficient unzip - inverse of zip? References: <3CA0ECAB.2070900@free.fr> Message-ID: In this same vein, I like this (assuming you're using a fairly recent version of Python): >>> a = (1,2,3) >>> b = (4,5,6) >>> ab = zip(a, b) >>> a1, b1 = zip(*ab) >>> a1 (1, 2, 3) >>> b1 (4, 5, 6) -tim "Christophe Delord" wrote in message news:3CA0ECAB.2070900 at free.fr... > Hi, > > apply zip again on the zipped list : > > > def unzip(l): > return tuple(apply(zip,l)) > > a = (1,2,3) > b = (4,5,6) > > ab = zip(a,b) > print "zip(a,b) =", ab > print "unzip(ab) =", unzip(ab) > > > > zip(a,b) = [(1, 4), (2, 5), (3, 6)] > unzip(ab) = ((1, 2, 3), (4, 5, 6)) > > > unzip([(1,4),(2,5),(3,6)]) will compute zip((1,4),(2,5),(3,6)) > zip can zip more than two lists :-) > and zip((1,4),(2,5),(3,6)) is (1,2,3),(4,5,6) > > > You can also use zip to transpose matrix. > > > Pearu Peterson wrote: > > > Hi, > > > > What would be the most efficient way to unzip zipped sequences > > in Python 2.2? > > > > For example, consider > > > > a_b = zip(a,b) # where a and b are some sequences > > a_b.sort() > > a,b = unzip(a_b) > > > > For a start, I have > > > > def unzip(seq): > > ns = range(len(seq[0])) > > r = [[] for i in ns] > > [r[i].append(s[i]) for i in ns for s in seq] > > return tuple(r) > > > > Is there any better algorithm for unzip? > > > > Regards, > > Pearu > > > > > > > -- > Christophe Delord > http://christophe.delord.free.fr/ > From tim.one at comcast.net Sat Mar 9 03:16:19 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 09 Mar 2002 03:16:19 -0500 Subject: PEP Parade In-Reply-To: <1015655700.378331@yasure> Message-ID: [Donn Cave] > ... > If there are lots of people using 2.1.2 and it has a serious bug, then > I'm sure someone will come up with a fix sooner or later, Like there were many serious bugs in 1.5.2, and sooner or later they did get fixed. However, because nobody volunteered to produce a bugfix release for 1.5.2 (and despite that Guido started asking for volunteers about 6 months after 1.5.2 was released -- no response), none of those fixes do 1.5.2 users any good. The only advice they get when they hit a 1.5.2 bug is "so upgrade -- or pay someone for the pain of investigation and backporting". If you're serious about holding on to 2.1, talk someone into starting work on 2.1.3 now. It will already be more difficult for them than it would have been had they started to produce 2.1.3 right after 2.1.2 was released. Let a few more months pass, and the odds of another 2.1 bugfix release will be down with the odds of a new 1.5.2 bugfix release. If you're picturing individual patches for only those bugs you consider "serious", the distribution, integration, and support problems will kill that in practice. That is, very few will agree to hunt down and apply random patches to an unsupported product, and those who do will eventually hit bugs unique to the specific combination of patches they applied. Keeping the 2.1.x series alive is a real solution to all that too. reality-check-ly y'rs - tim From drgergl at mindspring.com Sat Mar 2 10:02:41 2002 From: drgergl at mindspring.com (Greg Landrum) Date: Sat, 2 Mar 2002 07:02:41 -0800 Subject: Profiling extensions Message-ID: [Linux, python 2.1] Hi All, I've got a Boostified C++ class that I'm using from Python. The class supports pickling, but restoring things from pickles seems to be really, really slow. I figured that I'd profile the code and find out where the time is being spent, but I ran into a wall. I built both my extension modules and python itself with -pg. Running a test case and looking at the gprof output only shows me numbers for the python interpreter itself. This is none too edifying. So, my question is: is there any way to trick gprof (or prof, I don't much care) into gathering data for the extension modules as well as the interpreter? Thanks, -greg From beppu at ax9.org Mon Mar 11 03:06:49 2002 From: beppu at ax9.org (John Beppu) Date: Mon, 11 Mar 2002 00:06:49 -0800 Subject: Python Equivalent of Perl's Safe module? Message-ID: <20020311080649.GA25930@Ax9.org> Hello, I was wondering if there was a Python equivalent of Perl's Safe module. Here is the beginning of the man page for Perl's Safe. NAME Safe - Compile and execute code in restricted compartments SYNOPSIS use Safe; $compartment = new Safe; $compartment->permit(qw(time sort :browse)); $result = $compartment->reval($unsafe_code); The full documentation for the Safe module can be found at: http://perldoc.com/perl5.6.1/lib/Safe.html Any help finding such a module for Python would be appreciated. From jfhamilt at usgs.gov Mon Mar 4 18:22:34 2002 From: jfhamilt at usgs.gov (jfhamilt at usgs.gov) Date: Mon, 4 Mar 2002 23:22:34 +0000 (UTC) Subject: XMODEM Module for Python Message-ID: Hi. I am wiriting a program that retrieves and manipulates data from a variety of sensor / data recorder hardware. One of these types of equipment requires the use of XMODEM to transfer the data file. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere? Thanks. Jeff Hamilton From tim.one at comcast.net Sun Mar 31 14:17:20 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 31 Mar 2002 14:17:20 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Message-ID: [Aahz] > But what do you think of changing bool() to truth()? Whatever Guido tells me to think . Before then, I think "bool" usually reads better, as it's less a strain to use as either adjective or noun. Contrast, e.g., isatty returns bool isatty returns a bool isatty returns a bool value with isatty returns truth isatty returns a truth isatty returns a truth value After reading "isatty returns a truth", I'm left wondering which specific truth it returns, and whether I'd agree with it . Strangely enough, even today: >>> print os.isatty.__doc__ isatty(fd) -> Boolean Return true if the file descriptor 'fd' is an open file descriptor connected to the slave end of a terminal. >>> isatty(fd) -> truth doesn't read poorly, though. From pearu at cens.ioc.ee Sat Mar 30 08:40:17 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sat, 30 Mar 2002 15:40:17 +0200 Subject: PEP 285: Adding a bool type In-Reply-To: References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> Message-ID: > ----- Original Message ----- > From: "Guido van Rossum" > > > Dear reviewers: > > > > I'm particularly interested in hearing your opinion about the > > following three issues: > > > > 1) Should this PEP be accepted at all. It seems that this is already decided as Guido is the author and also the only one who accepts PEPs. > > The standard bool type can also serve as a way to force a value to > > be interpreted as a Boolean, which can be used to normalize > > Boolean values. Writing bool(x) is much clearer than "not not x" > > and much more concise than > > if x: > > return 1 > > else: > > return 0 This one does not convince me at all as one could always define bool = lambda x: not not x and I would never write such a verbose code fragment as above just to return whether x is false or true. However, using constructs like if x: ... while x: ... for x being a sequence or dictionary can be very useful and efficient. In future (Python 2.>=3, >3), are these constructs valid or must they be replaced with while bool(x): ... ? :( Ka-Ping Yee has raised related conserns in http://mail.python.org/pipermail/python-dev/2002-March/020893.html that never got a proper answer from Guido nor others. So, I am (-1)*0 on this PEP. -1 --- I have succesfully programmed in Python without needing the bool function and I share Ka-Ping's concerns about Python future. To me the only reasonable point in rationale seems to be that "other languages have or will have boolean". That also sounds quite weak to me --- other languages have many useful concepts that would be more worth for introducing to Python than this boolean concept. 0 --- this PEP will be hardly rejected, it seems to me. Regards, Pearu From ark at research.att.com Sat Mar 30 11:19:31 2002 From: ark at research.att.com (Andrew Koenig) Date: Sat, 30 Mar 2002 11:19:31 -0500 (EST) Subject: [Python-Dev] PEP 285: Adding a bool type In-Reply-To: <01b401c1d806$378aa100$0202a8c0@boostconsulting.com> (david.abrahams@rcn.com) References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net><008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com><200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net><014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com><200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> <01b401c1d806$378aa100$0202a8c0@boostconsulting.com> Message-ID: <200203301619.g2UGJVR13515@europa.research.att.com> David> Even that won't work, because of the different repr/str behavior... one David> reason I don't like the inheritance relationship. Ah -- hadn't thought of that. From opengeometry at NOSPAM.yahoo.ca Mon Mar 4 19:09:59 2002 From: opengeometry at NOSPAM.yahoo.ca (William Park) Date: 5 Mar 2002 00:09:59 GMT Subject: Text Search Engine that works with Python References: <4abd9ce7.0203041356.39491249@posting.google.com> Message-ID: damien morton wrote: > Have you looked at mg. > Its written in C, but useable from the unix command line. > http://www.mds.rmit.edu.au/mg/ Thanks Damien! -- William Park, Open Geometry Consulting, 8 CPU cluster, NAS, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Tin From eppstein at ics.uci.edu Mon Mar 18 19:34:00 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 18 Mar 2002 16:34:00 -0800 Subject: A question about generators References: Message-ID: In article , "Delaney, Timothy" wrote: > > I have an application where I think either an iterator or a > > generator would > > be ideal, but I have to be able to reset whichever I use. The paper > > "What's New in Python 2.2" says that there's no way to reset > > an iterator, > > so that's out. Is there a straight-forward way to reset a generator, > > though? > > That's not actually correct. There is no general way to reset and iterator > or generator, but you can make a custom iterator or generator that can be > reset. You could create the generator inside some larger scope, and communicate with it by changing variables in that scope. Ok, actually it's not possible to change a variable from outside that variable's scope (why??) but it is possible to have a list or dictionary within a scope and change one of its cells. Or you can make a new generator every time you would want to reset it. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From aahzpy at panix.com Tue Mar 12 08:48:04 2002 From: aahzpy at panix.com (Aahz) Date: 12 Mar 2002 08:48:04 -0500 Subject: Is Python an object based programming langauge? References: Message-ID: In article , Roy Smith wrote: > >I've got one guy I work with you insists python isn't OO for exactly one >reason: because it doesn't implement private variables. Sure it does, it just implements them through convention rather than through the language. And it can be proven that e.g. C++ really doesn't have private variables. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From stephen at xemacs.org Fri Mar 1 01:39:42 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 01 Mar 2002 15:39:42 +0900 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Please note, you are correct---I missed the main point. I'm not going to address that point-by-point, unless you ask. However, it's easy enough to paraphrase my comments to apply to "are we going to mandate UTF-8 for all source code?". The following is a rough counter- proposal to handle the main issues, framed correctly. >>>>> "Martin" == Martin von Loewis writes: Martin> [U]nder the proposed change, Python would refuse to accept Martin> source code if it is not UTF-8 encoded. In turn, code that Martin> has a euc-jp comment in it and is now happily accepted as Martin> source code in the current Python programming language Martin> would be rejected. Fine with me for Elisp. We don't have satisfactory UTF-8 support yet, but will soon. After that there will be no excuses for us, since the editor is the interpreter. This _is_ the direction we're heading. Emacs treats Lisp files the same as any other on initial loading, so we already have hooks in place that could be used to translate. The point is that if XEmacs didn't accept the encoding of a Lisp file, it would be on the user- provided codec to get it right. It's not our problem (except to the extent that we would of course provide such codecs). We're currently working to make codecs available to users in a convenient, consistent way--and Python has the advantage that that part is done! Such a hook probably would be something new in Python, but I don't see that it would be terribly difficult to implement. Martin> Will you reject a source module just because it contains a Martin> latin-1 comment? >> That depends. Somebody is going to run it through the >> converter; it's just a question of whether it's me, or the >> submitter. Martin> 'you' in this case isn't the maintainer of a software Martin> package; it is the Python source code parser... Same thing either way, if you add the preprocessing hook. IMO, the Python source code parser should never see any text data[1] that is not UTF-8 encoded. If you want to submit Python programs to the parser that are not UTF-8 encoded, then it is your responsibility as the programmer to make sure they get translated into UTF-8 (eg, by the preprocessing hook) before the interpreter proper ever sees them. Note that the Python language doesn't need to specify at all what's allowed on the preprocessing hook. It can be a Perl-to-Python translator, for all I care. You simply say "if the parser doesn't accept it when run `python --skip-preprocessing-hook', it's not valid Python." No more problem. From the user's point of view, in everyday operation it's basically the same as a Python which accepts his favorite encoding. From your point of view, the interpreter is invulnerable to coding issues. Even if you choose to support complex (eg, autorecognizing[2]) codecs on the pre-processing hook as part of the Python library, bugs are more easily localized. Since the preprocessing-hook would be callable from Python, it would be easy to run it as a separate program, and require the users to send the output of that as the bug report. The final benefit is that in multilingual environments it makes use of UTF-8 a lot more attractive to the users. But those are exactly the environments where coding cookies will be a massive pain for Python to support them, because people will forever be copying the top matter from German files into Polish files and forgetting to adjust the cookie, etc. Footnotes: [1] Ie, Python language or character text. It might be convenient to have an octet-string primitive data type, in which you could put EUC-encoded Japanese or Java byte codes. However, the Python interpreter would never do anything with them except (1) pass them whole as arguments or variable values, (2) extract slices, and (3) extract individual octets as an integral (but non-character) type. (Roughly speaking. There might be other operations that "base Python" should implement, like applying codecs.) [2] But I recommend against this. Don't offer support for such; it's a time and effort sink, for little return. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From pinard at iro.umontreal.ca Tue Mar 5 18:01:05 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: 05 Mar 2002 18:01:05 -0500 Subject: Pyhon and PIL In-Reply-To: References: Message-ID: [Olav Viken] > I'm using Python Imaging Library (PIL) to convert a lot bmp-files from > color to monochrome images. This works, but all images are dithered > (grayscale), This is not really dithering. Dithering is a way to trade spatial resolution in favour of color resolution, by making many neighbouring pixels to use different colours from a limited set, but with the average of these colours approximately being the wanted one. > what I want is to set "all colors (except white) to black". > import Image > im = Image.open("yellow.bmp") > im = im.convert("1", dither=Image.NONE) > im.save("yellow.bmp") Maybe this would work? import Image Image.open('yellow.bmp').convert('L').point(255*[0] + [255]) \ .convert('1').save('yellow.bmp') -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From aahz at pythoncraft.com Sun Mar 31 20:38:01 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 20:38:01 -0500 Subject: Cannot find what I'm sure is a simple command... please help. References: <3ca7978b.251291804@mammoth.usenet-access.com> <3ca7b638.259145474@mammoth.usenet-access.com> Message-ID: In article <3ca7b638.259145474 at mammoth.usenet-access.com>, A. Jones wrote: >On Sun, 31 Mar 2002 19:39:45 -0500, "John Roth" > wrote: >> >>If you read the file into a list using readlines(), you can then >>access each line by the index into the list. Unfortunately, that >>doesn't get you one line without reading the entire file up to >>that point... > >Right, I knew I could do that. However, when I did that, it causes a >meltdown when I index from that list, owing to the large size of the >file (it's a database, with each entry on a separate line, but with an >arbitrary line size). Get a real database. Then you can retrieve an arbitrary record. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From emile at fenx.com Sun Mar 3 16:36:48 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 3 Mar 2002 13:36:48 -0800 Subject: Newbie question References: <3c810efa.475638531@mammoth.usenet-access.com> Message-ID: "Martin v. Loewis" > If you want to output a string in Python source format, but using > triple quotes, I believe you have to implement this yourself. > [ducking...;-)] >>> print '''"""%s"""''' % "Spam & Eggs!" """Spam & Eggs!""" -- Emile van Sebille emile at fenx.com --------- From op73418 at mail.telepac.pt Fri Mar 15 21:38:08 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sat, 16 Mar 2002 02:38:08 +0000 Subject: pythonic way of depth first and breadth first tree iterators References: Message-ID: <3mb59ugde1vho8i7fk15h7e8uo0j2jnf3g@4ax.com> On Fri, 15 Mar 2002 20:37:59 -0500, Dave Reed wrote: > >We're planning to use Python in our CS1 and CS2 courses next year so >I'm beginning to think about the issues for these courses. > >http://www.python.org/doc/current/lib/typeiter.html states: > > If a container supports different types of iteration, additional > methods can be provided to specifically request iterators for those > iteration types. (An example of an object supporting multiple forms > of iteration would be a tree structure which supports both > breadth-first and depth-first traversal.) > >I don't quite understand exatly what that is saying - what would be >the pythonic way of defining/calling separate breadth first and depth >first iterators for a binary tree class - i.e., is there a way to >indicate which method to use when you make the call to iter() so that >I could do something like: for node in tree('depth'): > >and > >for node in tree('breadth'): > >Or is that just implying that I can make a depth first class iterator >class and breadth first iterator class that both support the >corresponding next() method and do something like: > >d = DepthIter(tree) >for node in d: > >where DepthIter is a class that takes a tree as a parameter to its >constructor and has a next() method that returns the nodes in a depth >first manner. And similarly, write a BreadthIter class? > >Thanks, >Dave The standard way to define an iterator is via def __iter__(self): and THIS iterator is what is used in the for loop, e.g for node in tree: But there are classes(trees, dictionaries, etc.) where more than one iterator (more than one to traverse it) is useful. In the example of a tree the __iter__ could be the breadth-first traversal and then you could code ANOTHER iterator, e.g. def depth_first(self): To use this second iterator, you just do for node in tree.depth_first(): Hope it helps. Best regards, Gon?alo Rodrigues From usenet at thinkspot.net Mon Mar 18 13:53:48 2002 From: usenet at thinkspot.net (Sheila King) Date: Mon, 18 Mar 2002 10:53:48 -0800 Subject: bug reporting References: Message-ID: On Mon, 18 Mar 2002 09:57:51 -0500, "Arthur Siegel" wrote in comp.lang.python in article : > >Yes, that is sort of what I am hoping for, when I post stuff here. I've > >gotten a lot of "submit it as a bug report" responses, more recently. > >Anyhow, the one in the thread you continued this from...I have now > >submitted it as a bug report. However, as I continue to work on this > >problem (sort of trying to see if I can fix it or at least see if I can > >understand what's causing it), I'm not so sure it will end up to be a bug > >report after all. It may end up to be a problem in my own code. :/ > > I ended up posting my issue up to the tutor list, where Danny Yoo picked > it up and did the kind of analysis I wouldn't know how to undertake. > > I know you are active there - so assumedly you saw it. Well, I'm not having time to read all of the mail that comes in under that list right now (nor, in fact for any of the lists I'm currently subscribed to), so once in a while I look at the subject lines and see if something interests me. So, actually, I did miss your post. I will go back this afternoon and look for it. Thanks. > Danny has helped > me before, and I was actually figuring I might get his attention to the > problem by posting on tutor. Danny is amazing. Not only does he have a thorough understanding that far exceeds my own, he can actually explain stuff, and takes the time and trouble to do a full analysis of your question. He must have a clone? Or else he is not human, because he certainly doesn't sleep! > Must admit some perverse satisfaction in uncovering something > that perhaps has some significance. Bit of a Pythonic > coming of age. ;) :D > And thanks, Danny. Ditto. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From brueckd at tbye.com Wed Mar 27 10:56:45 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 27 Mar 2002 07:56:45 -0800 (PST) Subject: instrumenting Python code In-Reply-To: <15521.50103.968819.131319@12-248-41-177.client.attbi.com> Message-ID: On Wed, 27 Mar 2002, Skip Montanaro wrote: > >> I was wondering if there is an easy way to instrument Python code [snip] > Or, in 2.2, the new hotshot module, which is a lot more efficient at > profiling than the profile module. The hotshot module doesn't appear to have any documentation yet. There is a unit test that's kinda confusing; below is a simplification of how to use the module: import hotshot, os import hotshot.log from hotshot.log import ENTER, EXIT, LINE WHAT_NAMES = {ENTER:'ENTER',EXIT:'EXIT',LINE:'LINE'} def ProfIt(callable): outf = 'out.temp' prof = hotshot.Profile(outf, 1, 1) prof.runcall(callable) prof.close() log = hotshot.log.LogReader(outf) print 'What\tFunc (where)\ttDelta' for event in log: what, (filename, lineno, funcname), tdelta = event print '%s\t%s (%s:%d)\t%d' % (WHAT_NAMES[what], funcname, filename, lineno, tdelta) os.remove(outf) def f(): y = 2 x = 1 def g(): f() ProfIt(g) The output from this is: What Func (where) tDelta ENTER g (hot.py:24) 59 LINE g (hot.py:24) 12 LINE g (hot.py:25) 7 ENTER f (hot.py:21) 21 LINE f (hot.py:21) 6 LINE f (hot.py:22) 6 LINE f (hot.py:23) 7 EXIT f (hot.py:21) 8 EXIT g (hot.py:24) 11 My question for Skip: is there no good way to profile a multithreaded application? -Dave From jonathan at onegoodidea.com Thu Mar 7 07:31:19 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 07 Mar 2002 12:31:19 +0000 Subject: fork and thread and signal... oooooops References: <87550ef1.0203050846.2166835e@posting.google.com> Message-ID: On 7/3/2002 11:46, in article MeIh8.104$_Z4.397 at news.hananet.net, "Jonathan Gardner" wrote: > Shell is really good for writing things like init scripts. All the other > init scripts are written with shell. Python just doesn't compare to shell > when all you want to do is start or stop or send signals to a process. > That's what shell was built for. Writing an init script in Python makes > about as much sense as writing your init script in Tcl or C++. This isn't much of an argument. Python is a great deal more capable than sh and contains much of the equipment that you'd need to invoke subtools for with sh (grep, sed, test, kill, etc.). The main reason why one wouldn't want to write an init script in Python is that you might not have Python available when you need it most. A statically linked 'sh' (and the useful subtools) residing on the boot volume is a standard feature of any UNIX (or should be). If pretty much everything else fails, you generally know that you can get to a single user prompt and run shell scripts. If you've severely mangled some library installations your Python may very well be toast - or it may be on a file system that just got hosed. Of course this is old-skool sysadmin. These days I guess you just boot from the emergency CD and press the repair button or something ;-) Jonathan From uwe at rocksport.de Wed Mar 27 05:06:15 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 27 Mar 2002 10:06:15 GMT Subject: wxPython and wxFlexGridSizer problem References: <3C9FBE22.A72B4A27@ccvcorp.com> <3CA0FCE8.8D8FE0D7@ccvcorp.com> Message-ID: Jeff Shannon wrote: | Uwe Schmitt wrote: |> Cliff Wells wrote: |> |> | That may be the case, but Jeff brought up some good points. It looks odd |> | to create a window in this fashion (it looks procedural rather than OO). A |> | more typical approach would be something like: |> |> I know what you mean, but I'd like to write a general procedure |> which generates an input/output mask based on a relational database |> describption. And this mask may appear in a wxFrame *or* a wxDialog. |> So I use the "parent" of the mask as a parameter of my function... | Then create your controls on a wxPanel, and then add that panel to either your | frame or your dialog. The wxPanel will have the added benefit that, even in a | frame, it will handle tabbing between controls, etc, correctly. Hi Cliff, Hi Jeff, thanks for your suggestions. As I am quite new to wxPython, I did not know the class wxPanel. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From peter at engcorp.com Sun Mar 10 15:15:15 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 15:15:15 -0500 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> Message-ID: <3C8BBED3.D947EE5E@engcorp.com> phil hunt wrote: > > On Sat, 09 Mar 2002 17:21:39 GMT, Gerson Kurz wrote: > > > >!0,1.!1,1.!2,1.!3,1.,.@?0.!4,?0.!0,?1.~4,?0.!1,?4.~2,?3.!5,?2.A5,10.-5 > > > >will print the first ten fibonacci numbers. > > I wonder what it does in Perl? Obviously it's a multithreading web server. From aahz at pythoncraft.com Sun Mar 31 09:33:53 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 09:33:53 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: In article , phil hunt wrote: > >That *is* a valid reason. However, it must be decided whether >Python's primary goal is to be easy to learn or easy to use. It must? Much of why I love Python so much is because it's *both*. By using lots of simple, orthogonal constructs, Python manages that unusual feat. That's the main reason I was (and am) unhappy with the "print >>" proposal, but on the whole, I can't argue with Guido's ability to find solutions that promote the goals of both "easy learn" and "easy use". I happen to think that adding a truth type (I like the suggestion of "truth" over "bool") does that. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From weeks at vitus.scs.agilent.com Sat Mar 16 17:36:22 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Sat, 16 Mar 2002 22:36:22 +0000 (UTC) Subject: HP-UX, PyThread_* missing References: Message-ID: <1016327182.366474@cswreg.cos.agilent.com> Paul F. Dubois (dubois at users.sourceforge.net) wrote: : I am trying to get Python 2.2 to compile on HP-UX B.10.20. I get a set of : missing externals with names PyThread_something. I need threads so I don't : want to turn them off. Is there a package I need to install first? Or some : other hint about what to do? I posted recently regarding Python 2.2 and HP-UX 10.2. See the Subject "HP-UX 10.2 deprecated"? Quoting from there: --------------------------------------------------------------------------- To determine if _POSIX_THREADS is defined in unistd.h, "configure" runs the C preprocessor on a file with the contents: #include #ifdef _POSIX_THREADS yes #endif Unfortunately, with the C preprocessor invocation used by ./configure, the indented #ifdef is not recognized, which results in the #ifdef construct being mindlessly echoed, which is erroneously interpreted as the answer "yes". This causes _POSIX_THREADS to not be defined in pyconfig.h, resulting in a bunch of undefined thread-related functions at link time. When I removed the indentation from the above #ifdef construct, the "make" of the executable was successful. Unfortunately, "make test" did not pass. --------------------------------------------------------------------------- An alternative to editing "configure" is to run: CC='cc -Ae' ./configure In either case, though, "make test" fails at test_threads with: test_thread *** Termination signal 14 That was where I got stuck, and I'm *still* stuck. On the other hand, I recall (sort of) someone posting after I did who successfully built Python 2.2 on HP-UX 10.2 by installing gcc. Unfortunately, I don't remember the Subject or the details. If you do find a recipe for getting it to work, please post it! Greg From scott.l.hathaway at lmco.com Tue Mar 26 11:45:00 2002 From: scott.l.hathaway at lmco.com (Scott Hathaway) Date: Tue, 26 Mar 2002 10:45:00 -0600 Subject: a website information gathering script References: <3C9B33FA.3D853D65@lmco.com> Message-ID: <3CA0A58C.18800669@lmco.com> Thanks to both of you for your help! I will improve teh script when I have some time. Scott Bengt Richter wrote: > On Fri, 22 Mar 2002 07:39:06 -0600, Scott Hathaway wrote: > > >I have a simple python script which gathers information about a website > >and produces an html report about what it finds. The way it works is > >very clunky and I would appreciate some feedback and help improving it. > > > >http://www.hcsprogramming.com/downloads/index.html > > > Unless you know that the format of your files is more restricted than their > types require, your criterion for finding a file reference is going to > get spurious hits (of course the other side is you can't statically find > strings that don't exist until run time either, when it comes to program sources). > > E.g., for HTML you could do a much better job by using the HTMLParser module. > UIAM it also normalizes things to lower case for you, besides letting you > skip commented-out references and similar character sequences in > the data part. And since the parser makes it easy to get hrefs, you could > split and check #-references and definitions too. > > The other files should really be parsed too, if you want to avoid spurious > matches. > > As Emile pointed out, concatenating strings with '+' is relatively expensive, > and one way of doing it more cheaply is to put the pieces in a list and later > join them. You can do that in a style that looks similar to what you did, but > is a lot more efficient. > > Note that strings separated by white space are concatenated by the compiler, > and in a () or [] context that white space can include EOLs, so you can mix > string fragments and expressions e.g., like this: > > >>> x= '' > >>> a = [ > ... '123' > ... '456' > ... '\n', x*2 , '\n' > ... 'abc' > ... 'def' > ... ] > >>> a > ['123456\n', '', '\nabcdef'] > > Notice that 'a' wound up a list of _3_ strings here, > and note the commas isolating the x*2 expression. > > >>> print ''.join(a) > 123456 > > abcdef > >>> a += ['\nYou can add this way too, for ', x[1:-1], '.'] > >>> print ''.join(a) > 123456 > > abcdef > You can add this way too, for example. > >>> a += [ > ... '\nOr' > ... ' this' > ... ' way' > ... '\n(noting that indent is ignored inside () or [].' ] > >>> print ''.join(a) > 123456 > > abcdef > You can add this way too, for example. > Or this way > (noting that indent is ignored inside () or []. > >>> > > Of course, you can arrange pieces to suit, but the point > is that it needn't be expensive to write a mix of string fragments > and expressions in a sequence, and you can lay it out in > multiple lines of source without a += 'next string piece' expense > at every line (noting that the similar looking > a += ['a string ',foo(),' more'] > is comparatively cheap). > > Triple quotes of course are good for defining lines without using '\n', > and you can plug in pieces symbolically from a directory: > > >>> b = """

    %(bigText)s

    > ... %(redText)s > ... etc... > ... """ > >>> stuff = {'bigText':'Should be big', 'redText':'Should be red'} > >>> b % stuff > '

    Should be big

    \nShould be red\netc...\n' > >>> print b % stuff >

    Should be big

    > Should be red > etc... > > You can also use vars() in place of stuff to pick up symbols > from the local or other dictionaries. > > You might also want to consider using dictionaries for some > sets of things instead of lists. > > To enhance the directory walker, you could give it globbing > and excluding and optional recursion controls. Perhaps make > it a class meant to be subclassed like HTMLParse, feeding it > glob strings and having it call convenient methods. > > BTW, I'd try to avoid useless re-computation, as in putting > ".tolower()" on stuff that's already guaranteed lower case > by previous code. And file = str(file) looks like a no-op > in its context. Also, if you have a series of mutually > exclusive if conditions, making the if's after the first > into elif's will avoid executing tests after one succeeds. > > BTW2, all those .endswith() tests would succeed on file names > without extensions but having the given suffix. You could fix > it, but Emile's version avoids that by splitting on '.' so you > gain two ways ;-) > > That enough for this go ;-) > > Regards, > Bengt Richter From python at rcn.com Tue Mar 5 22:07:38 2002 From: python at rcn.com (Raymond Hettinger) Date: Tue, 5 Mar 2002 22:07:38 -0500 Subject: Why KeyError ??? References: <7dee885c.0203051843.36efa5c2@posting.google.com> Message-ID: "Ozren Lasic" wrote in message > >>> import sys > >>> sys.setdefaultencoding("cp1250") > >>> a = "\xe7\xd0\x9f\x86\xa7" # Croatian characters > >>> b = unicode(a) > >>> b > u'\xe7\u0110\u017a\u2020\xa7' > >>> c = {} > >>> c[a] = 1 > >>> c[b] > Traceback (most recent call last): > File "", line 1, in ? > KeyError: šđčćž > >>> a == b > 1 Hmm. I don't get the same identity check results as you do: >>> a = '\xe7\xd0\x9f\x86\xa7' >>> b = unicode(a,'cp1250') >>> a is b 0 Raymond Hettinger From aahz at pythoncraft.com Wed Mar 27 18:44:59 2002 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2002 18:44:59 -0500 Subject: thread-safe swap References: <833cyl3gfe.fsf_-_@panacea.canonical.org> Message-ID: In article <833cyl3gfe.fsf_-_ at panacea.canonical.org>, Kragen Sitaker wrote: > >Someone recommended using the idiom > > spam, eggs = eggs, spam > >to get a thread-safe swap. Does this really work? Not really. IIRC, there are some specific circumstances where it does work, but better to protect it with an RLock(). OTOH, it's safe if spam and eggs are both local. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From grante at visi.com Wed Mar 6 15:03:21 2002 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Mar 2002 20:03:21 GMT Subject: select.select() on Regular Files? References: Message-ID: In article , Jim Dennis wrote: > I'm trying to figure how to write a daemon that will > efficiently wait for activity on any of several file and/or > socket descriptors. [...] > Unfortunately it continually outputs. I don't understand why > if there's no more data at the end of the file. Is my read() > not pushing my file position all the way to the EOF? It's as > though there's *always* data available on that file descriptor. You've misunderstood what select() is telling you. When select returns a read fd, that doesn't mean there's data available. It means that a read() call on that fd will not block. A read() call on a regular file's fd never blocks: it always returns immediately with data or with EOF. Therefore, select() will always return a read fd immediately for a regular file. IOW, select() is supported for regular files, but the semantics aren't very useful. > This seems to contradict the documentation: > > Wait until one or more file descriptors are ready for some kind > of I/O. "ready for some kind of I/O" means that the read() or write() call will not block. In the case of a read fd it doesn't imply that there is data available. > Is this a bug? I'm using Python2.2 as packaged by Debian (unstable) > on a Debian GNU/Linux system (what a surprise, a Debian package > on a Debian system!) under 2.4.9 SMP kernel). Probably -- in the sense that the documenation was not sufficient to prevent a surprise. Not in the sense that the select() call doesn't do what the designers intended. > Would poll() be a better choice? The __doc__ for that is a bit > terse. IIRC, poll() will do the same thing. -- Grant Edwards grante Yow! Is this "BOOZE"? at visi.com From philh at comuno.freeserve.co.uk Fri Mar 29 11:45:15 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 29 Mar 2002 16:45:15 +0000 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> <3CA3768B.32BB6AC9@ccvcorp.com> <3CA3C981.2433ECD7@ccvcorp.com> Message-ID: On Thu, 28 Mar 2002 17:55:13 -0800, Jeff Shannon wrote: > > >phil hunt wrote: > >> On Thu, 28 Mar 2002 12:01:15 -0800, Jeff Shannon wrote: >> > >> >I disagree. I'm just as happy that Python doesn't try to guess what would be a >> >suitable "default" value for non-existent keys. >> >> The default value should always be None. >> >> None should act like 0 or "" or [] or {} where appropriate, i.e.: >> >> None + 1 --> 1 >> None + "x" --> "x" >> None * 4 --> 0 >> None + ['x'] --> ['x'] >> None + {2:3} --> {2:3} > >I strongly disagree with that. Next thing you know, you'll be saying that (3 + >'one' ) should evaluate to 4. Not at all. Actually, I think catenation and addition should have separate operators, so: [1,2] & [3,4] --> [1,2,3,4] [1,2] + [3,4] --> [4,6] >> >It seems to me to be entirely >> >consistent with the philosophy of "explicit is better than implicit". >> >> But that isn't the philosophy of any high level langauge. In fact, >> the more high level any language is, the more implicit things are. >> And I would argue that's a pretty good definition of what a high >> level language is. > >I disagree with your conception of high level language. A high level language hides >unnecessary details, but I don't think that conversion between different data types >is an unnecessary detail. So would you prefer: float(2) + 3.14 to: 2 + 3.14 ? >High level means that a logical step can be done in one >or two lines of code, Define "logical step". > not that it does magic transmutations in the background. Define "magic transmutations". Y'know, the transmutation between Python source and machine code is rather complex *already*. >There's a large class of cases where the interpreter, in trying to "do the right >thing", is as likely to guess wrongly as it is to guess right. This is only true if what the interpreter will do is not cleanly defined for the programmer. > If you want an >interpreter that guesses anyhow, use Perl. Yuck. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From david.abrahams at rcn.com Sun Mar 3 15:05:45 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sun, 3 Mar 2002 15:05:45 -0500 Subject: C/C++ to Python translater References: <5e8bd451.0203011049.5d12d3a2@posting.google.com> <3C811653.871C5BEF@tds.net> <3C8207F6.8000008@rdg.ac.uk> Message-ID: No thanks, I was looking for a C++ to Python translator... ;-) "Alex Willmer" wrote in message news:3C8207F6.8000008 at rdg.ac.uk... > David Abrahams wrote: > > "Edward K. Ream" wrote in message > > news:3C811653.871C5BEF at tds.net... > > > >>leo.py contains a script called c2py.py that I have used to translate > >>all my C++ code to Python. It does about 80% of the work and is mostly > >>intended to be run from inside Leo. IIRC there is another entry in > >>c2py.py script to translate "exterior" files and this can be run from > >>idle, say. Munging source to Python is actually remarkably easy to do. > > > > > > > Biggest problem I'm having is that I can't find it. > > http://prdownloads.sourceforge.net/leo/leo-1.0.zip doesn't contain a file > > called c2py.py. Did you have something else in mind? > > > > Perhaps this is what you're looking for? > > http://mail.python.org/pipermail/python-list/2002-January/079454.html > > Regards > > Alex > > From db3l at fitlinxx.com Tue Mar 19 18:28:57 2002 From: db3l at fitlinxx.com (David Bolen) Date: 19 Mar 2002 18:28:57 -0500 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <_kqk8.25881$N7.5410299@ruti.visi.com> <83elihknoz.fsf@panacea.canonical.org> Message-ID: Kragen Sitaker writes: > Signals fit into this rather poorly, but they do interrupt select() > and cause the appropriate handler to run, which is generally what you > need. True, but signals can be problematic in multi-threaded applications (I think that was the original context at least - if not, it's still a point :-)) and also if there's any chance the signal might interrupt some other I/O operation than the select, since while many are restartable, others are not. But definitely, signaling to break a select() is certainly another possibility in some cases under Unix. > But all of those approaches are really ways to try to work around the > fact that WaitForMultipleObjects (sp?) only works on signaling of > event objects. With Unix native functions, I'd just define an extra > file descriptor, and wait on that file descriptor along with the file > descriptors related to the sockets. To shut it down, just signal the > special file descriptor. As long as you can create a file descriptor that you can signal at will, that's cool. That's the same approach as listening on an extra port as has been mentioned, or using a socketpair() as you comment below. But it should be noted that WaitForMultipleObjects can wait on more than event objects. It's documented to work for the following objects: Change notification Console input Event Job Mutex Process Semaphore Thread Waitable timer For example, using a thread object signals when the thread terminates. Same for process. Event/Mutex/Semaphore are obvious and so on. The event is just a way that other types can be tied in if they can trigger a thread. So it's up to various kernel objects if they support the notion of a signaled and unsignaled state, and if so, they can be included in the call. So in some ways I'd consider it more generic than just waiting for read/write/exception on file handles (or device handles). But to address your next point you could turn it around and say that making everything a device handle properly is even more generic. Of course, Unix didn't really follow through fully or we wouldn't want to interrupt a select outside of the handles it was waiting on. Particularly with constructs added on later (e.g., semaphores), they don't really match the file descriptor model, at least not the last time I used them. E.g., you had to use sem_wait to wait for a semaphore, not include it in a select list, so you have a similar problem as to how to wait for both events simultaneously. > I think the difference is just in how you look at things. Oh, I certainly wasn't trying to make one system sound better than the other. I do think it's fair to say that the select() model is not quite generic enough to have been found portable across the systems, since it requires a specific underlying implementation along the Unix device driver lines, so can be hard to reproduce on systems that don't follow that model. Thus the MS decision to support it for sockets, but not try to overlay it on top of their asynchronous I/O model for files. But there are advantages and disadvantages to each. > > It's interesting that all of these approaches do have one thing in > > common - they tend not to be portable. > > Does Winsock not have socketpair()? My Win32 API references are all > in another state. Don't believe so. Probably because I believe that socketpair() is typically implemented (or limited to) UNIX domain sockets. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From db3l at fitlinxx.com Mon Mar 11 20:12:01 2002 From: db3l at fitlinxx.com (David Bolen) Date: 11 Mar 2002 20:12:01 -0500 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8C82D3.CA4220CA@earthlink.net> <3C8CAA83.9EBBC03E@engcorp.com> <924j8.19297$N7.4387774@ruti.visi.com> Message-ID: grante at visi.com (Grant Edwards) writes: > Ya know, I've actually read the transcript of that interview. > He never claimed to have invented the Internet, only to have > been responsible for funding it. Which, BTW, was more truth than not. When in Congress, Gore was very important to the funding at the time (primarily, I believe, to NSF). The whole "father of the internet" thing clearly got blown up a bit, but for those of us working on the backbones at the time, he really was a big guy in our camp. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From roy at panix.com Sat Mar 9 09:02:55 2002 From: roy at panix.com (Roy Smith) Date: Sat, 09 Mar 2002 09:02:55 -0500 Subject: PEP Parade References: <87henqe4dy.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: Stephen J. Turnbull" wrote: > Roy> Having the core language change from version to version just > Roy> makes it worse, as we discover imcompatabilities between > Roy> whatever version I'm using to develop on and whateve they're > Roy> running on their boxes. > > So you standardize locally. It's one thing to say "so you standardize locally", but the fact is, even requiring just that is an impediment to adoption. A typical scenario goes like this: Me: "Hey guys, I wrote a great new program, called foo.py. It's in CVS, under tools." Co-worker: "Neat, but when I go to run it, I get a syntax error" Me: "Let me see.... Oh, you've got python 1.5.2! Do you have any idea how old that is? You need to upgrade to 2.1.2" Co-worker: "Oh, I don't have the time to do that. Nice looking tool, but I guess I'll have to pass, thanks". If there was management buy-in, there might be a chance of declaring "thou shalt install python 2.1.2 on all development machines", but there's no management buy-in. In fact, management sort of humors me by letting me waste my time playing with Python as long as I get my "real work" done. Quite reasonably, my boss wants to know what the "business case" is for the group adopting python. The fact that python is cool and wonderful and perl sucks eggs doesn't go very far in the face of the fact that perl tends to be a lot more portable (or at least is percieved to be). The 1000's of lines of production perl code I've written run without a hitch on everybody's machine using whatever version of perl happened to come with their box. And, I think there lies the real problem. Python is facing an uphill battle for acceptance by the business community. Anything that increases the perception (true or false) that python is difficult to support makes it just that much harder to get it accepted. Technical arguments notwithstanding, frequent changes to the core language syntax sure increase the perception that it's a risky language on which to risk the success of your business. From emile at fenx.com Fri Mar 29 10:31:28 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 29 Mar 2002 15:31:28 GMT Subject: Function problem References: Message-ID: Michael Hall > Can someone tell me why this function stops printing after looping through > the " % (category,category) result = c.fetchone() And there's no 'really bad' code in there. I tend to keep SQL connection and authentication related information in a separate local module and then: from sqldata import cache catdata = cache("SELECT category FROM categories") for cat in catdata: print "" % (cat.category,cat.category) but that's really just personal choice. HTH, -- Emile van Sebille emile at fenx.com --------- From p.g at figu.no Sat Mar 2 11:10:31 2002 From: p.g at figu.no (Per Gummedal) Date: Sat, 2 Mar 2002 17:10:31 +0100 Subject: Black Adder and PyQt In-Reply-To: <3C80B1E3.575761B7@river-bank.demon.co.uk> References: <3C80B1E3.575761B7@river-bank.demon.co.uk> Message-ID: <1851070092828.20020302171031@figu.no> Wayne Pierce wrote: > As I understand it, the only restriction on redistribution is if you are > distributing commercial apps. Then you need the business edition to > redistribute Qt and the other modules. It might be good to get the > scoop directly from them on this since I got the business edition and > haven't had to worry about it. >From the BlackAdder readme file: The license of the Beta version prevents run-time components of the Business Edition being distributed with your applications. This restriction will be removed when the final version is released. Per From greg at cosc.canterbury.ac.nz Mon Mar 11 19:03:44 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 12 Mar 2002 13:03:44 +1300 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> <4abd9ce7.0203101059.444f1ec1@posting.google.com> <3C8BBFD4.A29A69F1@engcorp.com> <4abd9ce7.0203102128.67c7fa0d@posting.google.com> Message-ID: <3C8D45E0.5F8F91D4@cosc.canterbury.ac.nz> damien morton wrote: > > The existing mass of python code would be unchanged. The only issue > that might occur is that something that is now an error, would not be. > > It remains to be seen whether or not the mass of python programmers > are opposed. All that really matters is whether Guido is opposed, and from past discussions, he is. For what it's worth, I'm inclined to agree with him. Although it's very tempting to make an exception here, maintaining consistency is more important than the small convenience it would bring. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From kragen at pobox.com Sat Mar 30 04:12:18 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 30 Mar 2002 04:12:18 -0500 Subject: Client/Server Tutorial? References: <83u1r43zav.fsf@panacea.canonical.org> Message-ID: <831ye21kst.fsf@panacea.canonical.org> "Irmen de Jong" writes: > "Kragen Sitaker" wrote in message > news:83u1r43zav.fsf at panacea.canonical.org... > > "Irmen de Jong" writes: > > > > Is there any good tutorial for creating advanced client/server apps > > > > (like online games) out there? i tried to make one 2 times, and both > > > > > > May I suggest you take a look at Pyro; http://pyro.sourceforge.net > > > It may be just what you want/need for easy distributed application > development. > > > You don't have to do any network programming when using Pyro. > > > > I don't think Pyro is suitable for online games. It's an RPC layer. > > Yes, but what is wrong with that? 'RPC' usually means 'synchronous'. > Your game clients communicate with a game server, voila, RPC. A single or a few > Pyro objects could perfectly be the game server, can't they? > Your server publishes game state updates. Voila, Pyro's event service. I didn't know Pyro had an event service. I should look at that. Thanks! From aahz at pythoncraft.com Thu Mar 14 00:05:22 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2002 00:05:22 -0500 Subject: zlib vulnerabilities and python References: Message-ID: In article , Tim Peters wrote: >[Aahz] >> >> Dunno, but I filed a SF bug to check compatibility with the new 1.1.4. > >I can't find any such bug report. Did you file it against the Python >project? I *thought* I did, but I'm certainly prepared to believe that I failed to do it properly. Do you care if I try again? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From return at trafficmagnet.net Thu Mar 14 16:25:13 2002 From: return at trafficmagnet.net (Christine Hall) Date: Fri, 15 Mar 2002 05:25:13 +0800 (CST) Subject: TrafficMagnet - Special Offer! Message-ID: <20CR1000035967@emaserver.trafficmagnet.net> ReplyTo:"Christine Hall" Hi! Did you know that 85% of your potential customers will be using search engines to find what they are looking for on the Internet? Have you ever thought about getting your website listed on search engines worldwide? TrafficMagnet offers a unique technology that will submit your website to over 300,000 search engines and directories every month. We can help your customers find you! Submit your website to more than 300,000 search engines and directories http://news.linuxprogramming.com Normal Price: $14.95 per month Special Price: $9.95 per month You Save: more than 30% off Sign up today at http://www.trafficmagnet.net Benefit now! It's easy, it's affordable and you can sign up online. I look forward to hearing from you. Best Regards, Christine Hall Sales and Marketing E-mail: christine at trafficmagnet.net http://www.TrafficMagnet.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjones16 at rochester.rr.com Fri Mar 1 20:58:48 2002 From: sjones16 at rochester.rr.com (Seth Jones) Date: Sat, 02 Mar 2002 01:58:48 GMT Subject: (Hopefully) simple IDLE question Message-ID: Hi all, Is there any way to set the current working directory for a file being used in IDLE? I simply want to open a file that is in the same directory as my script, which I've opened into the idle window, and I don't want to hard-code the full path of the file. Failing that, is there any alternative in Windows 95 to the normal command line? I ask, since the reason I'm using IDLE in the first place is to avoid calling my script from the horribly unsatisfying DOS prompt. Failing even that, is there a better way to get error output from a .pyw file than to catch all exceptions and write them to a file? A google search did lead me to an old mailing-list post about adding the option for setting current directories in IDLE, but apparently that hasn't been done yet. I hope someone can convey some wisdom to this poor soul who's still stuck on win95. Thanks in advance for any advice. Keith (not Seth) Jones (^ : From aahz at panix.com Sun Mar 10 13:15:06 2002 From: aahz at panix.com (Aahz Maruch) Date: 10 Mar 2002 10:15:06 -0800 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: In article , phil hunt wrote: >On Sat, 09 Mar 2002 22:57:42 -0500, Peter Hansen wrote: >> >>I agree with much of what you say, especially the "consider skipping >>C++ and just learn C part", but _what_ pragmatic point of view is it >>that has one learning Perl, Java, or C++ when one uses Python already? >>Not dissing those languages, but when would you really need them? > >I can think of several tasks for which C++ is better than Python, >e.g. writing operating systems, network stacks, windowing systems, >run-time interpreters, crypto algorithms, etc. But are there any tasks for which C++ (or C++/Python) is really better than C/Python? -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From cliechti at gmx.net Sat Mar 16 21:59:44 2002 From: cliechti at gmx.net (Chris Liechti) Date: 17 Mar 2002 03:59:44 +0100 Subject: return type question - operator oveloading References: Message-ID: arthur.siegel at rsmi.com wrote in news:mailman.1016322689.22392.python-list at python.org: > Given: > > class Complex(complex): > def __mul__(self,other): > other=Complex(other) > t = complex.__mul__(self,other) > return Complex(t.real,t.imag) > __rmul__ = __mul__ > > def __add__(self,other): > other=Complex(other) > return > Complex(self.real.__add__(other.real), > self.imag.__add__(other.imag)) > __radd__ = __add__ > > Then: > > print type(Complex(5,4) * 7) >>> > print type(7 * Complex(5,4)) >>> > print type(Complex(5,4) + 7) >>> > > But: > > print type(7 + Complex(5,4)) >>> yes i get the same results (py 2.2). > Multiple choice: > That the result at But is a surprise to me because I am missing: > 1)Something obvious about __radd__ or general classic syntax > 2)Something related to new style classes > 3)Other i vote for "3) Other". i think the integer class defines __add__ for complex numbers but not __mul__ for complex numbers. thus when adding "7+Complex(5,4)" your __radd__ is never called cause the int class indles it. chris -- Chris From bobx at linuxmail.org Sun Mar 10 20:10:30 2002 From: bobx at linuxmail.org (Bob) Date: 10 Mar 2002 17:10:30 -0800 Subject: Learning Python 2nd Edition??? Message-ID: <1001ff04.0203101710.46f27d85@posting.google.com> Is there an "updated" Learning Python book in the works? Bob P.S. post here please...I read c.l.python a bit From martin at v.loewis.de Sat Mar 30 17:00:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 23:00:51 +0100 Subject: PEP 285: Adding a bool type References: Message-ID: "Terry Reedy" writes: > A. This PEP formalizes existing Python practice in regards to truth > values. The 'new' type is not really new. The main visible effect is > to change the display of the doubleton values. The existing magic > method is __truth__(). Better to call the new type and constructor > truth() than to change __truth__ () to __bool__(). The existing magic method is __nonzero__, and the PEP does not propose to change it... Regards, Martin From denro at NSPAMearthlink.net Mon Mar 4 17:29:36 2002 From: denro at NSPAMearthlink.net (Dennis Roark) Date: Mon, 04 Mar 2002 22:29:36 GMT Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <20020227163411.71b4b4d8.alex@netWindows.org> Message-ID: "DeepBleu" wrote in news:u7v372preds40a at corp.supernews.com: > Then of course we'll see some professors assigning the D & D Python > book as a textbook on a scripting language. How disgusting! > DeepBleu > I suspect so, but it certainly won't be me. I plan on using the Mark Lutz book Programming Python for an elective course next academic year. I won't use the D&D C/C++ books either. I would like to see some organized, printed material for GUI development in Python, but my impression is that that area is still settling out and books are premature. -- Dennis Roark denro at earthlink.net Starting Points: www.home.earthlink.net/~denro From frithiof.jensen at removethis.ted.ericsson.dk Tue Mar 12 08:54:53 2002 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Tue, 12 Mar 2002 14:54:53 +0100 Subject: Has Mark Hammond attained pariah status yet? References: Message-ID: <1015941315.65895@robert> There is also the issue of the "Poisonous Community License Agreements" used by Microsoft - in essence they bar developers from using any knowledge gained from access to source under license Microsoft to implement *any* Open Source software, not "merely" software in competition with MS's implementation. Odds are that if one were to develop for .NET, one would be screwed later by Microsofts legal machine for disclosing proprietary information and violating the NDA ... From roy at panix.com Sun Mar 10 12:18:39 2002 From: roy at panix.com (Roy Smith) Date: Sun, 10 Mar 2002 12:18:39 -0500 Subject: Use apply() or not, and raising multiple exceptions (co-routines?) Message-ID: I've got some code which performs a series of integrety checks against a data set. The way I've set things up, I put each check in its own method and keep a list of all the methods: checks = [] def check1 (self, data): do stuff checks.append (check1) def check2 (self, data): do other stuff checks.append (check2) and so on. This makes it easy to add and delete bits of policy over time. I cycle over the checking functions by doing: for check in self.checks: check (self, data) I could have also written this as: for check in self.checks: apply (check, [data]) is there any particular reason to prefer one style over the other? Having walked a few people through the code, I'm starting to think that the latter is a little more self-explanitory (especially for junior pythonistas). On the other hand, I suspect it's slighly less efficient. A related question is how best to have the check methods do more than one thing. Right now, I just have each method print an error message when it finds a problem. A given method might check for more than one related problem. I'd like to pull the printing out of the functions themselves, and go to an exception based system, where I'd do something like: for check in self.checks: try: check (self, data) except IntegrityCheckError, message: print 'failed check:', message The problem is I'd only catch the first problem found by a given check method. The way around that would be to make the check methods each look for one, and only one, problem, but that wouldn't be inefficient (especially since some methods would share a lot of code and repeat a lot of work). Is there some way to stack exceptions, so a given method can raise two or more of them in sequence, or something having the same effect? The only thing I can see is to have each check method return a list of problems it found. Then, the main loop would look like: for check in self.checks: for problem in check (self, data): print 'failed check:', problem but that implies pushing a lot of scaffolding down into the check methods, making them build and manipulate error lists to return. I'm trying to keep them as clean as possible, so they're easy to write and debug. It would be kind of neat if after doing the except clause, my method picked up again at the statement after the raise. I guess what I'd have then is the caller and callee acting as co-routines. Is there a way to do anything like that? From trentm at ActiveState.com Wed Mar 13 12:21:11 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 13 Mar 2002 09:21:11 -0800 Subject: RFC PEP candidate: q''quoted ? In-Reply-To: ; from nhodgson@bigpond.net.au on Tue, Mar 12, 2002 at 10:33:53PM +0000 References: Message-ID: <20020313092111.B2272@ActiveState.com> [Neil Hodgson wrote] > No. I started writing a lexer for Perl, but it is incomplete and is > likely to remain incomplete. The subset of Perl handled is sufficient for > syntax styling but is not sufficient for a language interpreter. The code is > available as part of Scintilla and is used in various IDEs. At one stage it > was used in Komodo, but ActiveState may have changed to using the Perl > interpreter's lexer. I wrote the first versions and then other contributors > extended the lexer into some of the more difficult pieces of Perl syntax. Komodo (and Visual Perl sort of too) is still using LexPerl.cxx from the scintilla project. I *believe* we have some additional bug fixes that should come down the pipe when we get that in order. Trent -- Trent Mick TrentM at ActiveState.com From grante at visi.com Thu Mar 7 10:46:59 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Mar 2002 15:46:59 GMT Subject: how to give an object as argument for a method References: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> Message-ID: In article , Marco Herrn wrote: > Is there a reason why this is just a convention? Because it seems to work well enough that way. > It seems (because it is such a _strong_ convention) that this > should be a real feature of the language. I mean that there > could be a reserved word "self" which is there all the time, so > that one doesn't hast to do this himself. It would make the language and the parser more complex. Extra cost must be justified by some corresponding gain. It would also make it less obvious what "self" is if the first parameter to a method was hidden from the user. If a function expects a parameter, then it should show up in the function definition. Methods are just functions whose first parameter is expected to be an object reference. -- Grant Edwards grante Yow! Did we bring enough at BEEF JERKY? visi.com From ggerrietts at yahoo.com Sun Mar 3 17:09:37 2002 From: ggerrietts at yahoo.com (Geoff Gerrietts) Date: Sun, 3 Mar 2002 14:09:37 -0800 Subject: [newbie] Problem with os.system In-Reply-To: References: Message-ID: <20020303220937.GC12980@isis.gerrietts.net> Quoting DarkCed (malletc3 at cti.ecp.fr): > I would like to run a program from a python script (a source for a > icecast server). > The program works, but a simple two-line script with os.system('ices') > does not. I get this message : > "syntax error near unexpected token". > > If I type "ices" in the same repertory, it works... > Shall I use another command to run my program ? By itself, that's not a syntax error. Maybe you should show us the entire script? -- Geoff Gerrietts -rw-rw-rw-: permissions of the beast From claird at starbase.neosoft.com Fri Mar 22 21:12:36 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 22 Mar 2002 20:12:36 -0600 Subject: Environment variables. References: <3C9BAFAE.51D0896D@cs.unm.edu> Message-ID: <87690C90F6F2E02F.105990D53AD9A33E.F2FA6E52B7893A40@lp.airnews.net> In article <3C9BAFAE.51D0896D at cs.unm.edu>, Vamsi K Kalapala wrote: >> > >Hi, > >I am learning python and I wanted to write a small script that will set >environment variables. > >#!/usr/bin/python > ># Program to set the environment. > ># Import the sys and os modules. >import sys >import os > ># Function to change the environment. >def setenv(var, value): > os.environ[var] = value > ># The driver. >if __name__ == '__main__' : > setenv(sys.argv[1], sys.argv[2]) > >I am running this on Python-2.2, but the script doesn't change the >environment. In Programming Python, it is claimed that newer versions of >Python do change the environment like this. Why is'nt this script >working. > >--Vamsi > "... [Y]ou can't change the value of an environment variable in another process". That's what an authoritative FAQ claims on the matter. That's almost entirely true. What environment is it you want to change? The one of the parent of your Python process? Why? On what page of *Programming Python* do you find the claim to which you refer? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From martin at v.loewis.de Fri Mar 1 16:00:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 22:00:43 +0100 Subject: ICU wrapper for Python? References: Message-ID: Fredrik Juhlin writes: > I was fiddling around with a Python wrapper for the ICU libraries this > weekend, when it occured to me to check if anyone else is/has been working > on the same thing. I looked around a bit on the net but couldn't find > anything, so I figured I'd drop a question here too :) Did you make any progress on that? I'd be most interested in exposing the codecs. Regards, Martin From gh_pythonlist at gmx.de Sun Mar 17 20:50:14 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 18 Mar 2002 02:50:14 +0100 Subject: Python on an ARM Linux Graphics Client Plus In-Reply-To: <55ddffcb.0203171705.3fb1d286@posting.google.com> References: <55ddffcb.0203171705.3fb1d286@posting.google.com> Message-ID: <20020318015014.GA76781@lilith.hqd-internal> * Robert Innes [2002-03-17 17:05 -0800]: > Been killing myself trying to build this to no avail. I know it can be > done but I have not been able to get a good version. Could some kind > person help me preserve what little hair I have left and tell me how > they did it or point me to a binary that I can copy to my system? While cross-compilation is possible with some hacking, it's much easier to compile natively. Take a look at http://www.handhelds.org/projects/skiffcluster.html then just compile Python and whatever else you need natively on the Skiffcluster. Take it home and enjoy :) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 7.3 ?C Wind: 1.8 m/s From siegfried.gonzi at kfunigraz.ac.at Wed Mar 13 04:40:15 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Wed, 13 Mar 2002 10:40:15 +0100 Subject: Question about scientific calculations in Python References: <3C8DFF7B.7EF0EAC6@kfunigraz.ac.at> <9dvs8u8aulpr2ceppipnakdk78e9bipneo@4ax.com> Message-ID: <3C8F1E7F.715A6E45@kfunigraz.ac.at> Martin Kaufmann wrote: > >How much slower? A performance penalty of 100 would be of great concern; > >a factor of 5 should not mind you (but this is my personal view). Okay, > >if you have to wait in C or C++ 1 hour then even a factor of 5 is > >somewhat bothersome. > > Even a factor of 5 is not really nice if you have to run it for > several hundred times... [I haven't studied your code, yet]. The speed/tuning problem only emerges when one knows about the speed of an equivalent code lets say written in C++ or Fortran 90. It is comprehensive that then one does ask: "What are the reasons for, and why should I just use the slow one". But you should re-think your stance. I can assure you, that normally people are not complaining about speed in Matlab/IDL/Python/Mathematica/Yorick/Octave,... as long as they do not compare it to C++ or Fortran 90. They even write simulations in IDL (whenever you see a high resolution solar granulation image, it is likely that they did it in IDL; at least my colleague in front of me). Personally, I think they are in error as long as they write such stuff in IDL, because it is questionable to make ones code (more than 1000 lines of code) dependent on one company. If you are going to decide whether you should learn C or C++, I want suggest you to dive in to C++ or Fortran 90 directly (If you are a scientist I can ssure you that nobody on earth will ever pay you money that you can show how C works). You should just starting to use valarray and the like. I am not a C++ advocate (nor I am a Fortran 90 junkie, either), but maybe the following (a little bit biased towards C++) article will help you during your reasoning-study: www.amath.washington.edu/~lf/software/CompCPP_F90SciOOP.html S. Gonzi [It is lurking to have a look at so called modern programming paradigms, e.g. "functional programming". But you should stay away from them as long as you do not know whether it is possible for example to write a number with a sepcific format to a file. Only to mention one tragedy] From p.magwene at snet.net Fri Mar 15 19:52:32 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sat, 16 Mar 2002 00:52:32 GMT Subject: Shot in the Dark: Minimum-weight perfect matching algorithm Message-ID: Hi Y'All, Here's a long shot - Does anybody happen to have a Python implementation of a minimum-weight perfect matching algorithm? Or a Python interface to one? I'm aware of (some) of the literature on this topic, but as a non-computer scientist I'd rather not have to twist my mind around one of the Blossum algorithms. I'm trying to implement a variation of Christofide's algorithm, and hence need to find minimum weight perfect matchings on graphs. My original plan was to use to simply pipe my data from my Python implementation to Cook and Rohe's Blossom4 implemenation, but while I can compile their C-code, I get core dumps when actually trying to use the binaries (on recent versions of Linux and FreeBSD systems). Before I spend hours/days reimplementing a Blossom algorithm or going through somebody elses C code I thought I'd see if any Pythonistas had implemented any such code lying around. Thanks, Paul Magwene From tl_news at nexgo.de Tue Mar 12 10:02:37 2002 From: tl_news at nexgo.de (Tino Lange) Date: Tue, 12 Mar 2002 16:02:37 +0100 Subject: New-Style-Classes: some questions Message-ID: Hi! I'm trying to use the new, cool 2.2-feature of deriving own classes from builtin types. For one application I thought it could be useful to have a list that has a maximum size and throws away the first elements if new elements are appended at the othe end (it's name should be MaxSizedList) OK, implementing something like that is no problem at all. The new list-like class works quite fine. But testing it I found two problems/questions: 1) According to the current documentation http://www.python.org/doc/current/ref/sequence-methods.html the special methods __getslice__ and __setslice__ are deprecated and should not be implemented anymore (since 2.0) . But they exist automatically in the subclassed list and are used for insertion like newlist[3:4] = 5 - so it seems I have to code/overload these deprecated methods. What's true now? Deprecated or not? 2) I wanted to transfer the MaxSizedList on request via XML-RPC. But xmlrpclib only nows about "real" lists. And there seems to be no interface to add dump()-Methods for other data types, or? So the best solution is to transport an object like return list(newlist) But I guess this makes a temporary copy of my MaxSizedList just for the XML-RPC-transport, or? So it's horrible inefficient? Is there no other way to deal with subclassed types in this lib besides patching the xmlrpclib to know my MaxSizedList? Is there a kind of casting to a "normal" list possible without making a completely new list from the MaxSizedList-Content? Thanks a lot for your help! Tino From phr-n2002a at nightsong.com Wed Mar 13 23:43:33 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 13 Mar 2002 20:43:33 -0800 Subject: Performance problem with filtering References: Message-ID: <7xd6y74v4a.fsf@ruckus.brouhaha.com> Gerhard =?iso-8859-15?Q?H=E4ring?= writes: > I have two lists of files (approx. 50000 entries). Now I want to have all the > entries of list b, that are not in list a. However, the primitive: > > results = [] > for entry in b: > if entry not in a: > results.append(entry) > > is terribly slow. I mean *really* slow. Any recommendations on how > to optimize this? Wouldn't it be nice if I could simply do > b.removeall(a)? Method 1: use a dictionary, as several people suggested Method 2: sort both lists, then make a single sequential pass through them selecting out the elements that you want, sort of like the "comm" command in Unix. Coding this is left for you as an exercise :) From theller at python.net Tue Mar 26 14:43:26 2002 From: theller at python.net (Thomas Heller) Date: Tue, 26 Mar 2002 20:43:26 +0100 Subject: PEP262 - database of installed packages References: Message-ID: "David Ascher" <> wrote in message news:mailman.1017164505.29287.python-list at python.org... > PS: Thomas -- where's the source to the code that's embedded in > bdist_wininst? > In the distutils tree of the Python CVS repository: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/distutils/misc/ Thomas From cpbotha at i_triple_e.org Thu Mar 28 15:11:04 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Thu, 28 Mar 2002 20:11:04 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <001d01c1d67f$2eb81090$445d4540@Dell2> Message-ID: In article , David Ascher wrote: > Thanks for all the interest in ActivePython. We hope to not have these > kinds of delays in the future. Just remember not to split your infinitives in the future. ;) Keep up the good work! -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From aleaxit at yahoo.com Tue Mar 26 03:50:46 2002 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 26 Mar 2002 00:50:46 -0800 (PST) Subject: [Python-Help] How to get a key from dictionary? In-Reply-To: <3C9FAFCC.20062.91741D@localhost> Message-ID: <20020326085046.6693.qmail@web9304.mail.yahoo.com> --- A wrote: > Hi, > Is there a possibility to get, from a dictionary, a > key according to a value ? In general, zero or more keys will correspond to a given value, and it's easy to get the list of those (but of course it takes time proportional to the TOTAL number of items in the dictionary): [ key for key in thedict if thedict[key] == avalue ] This is Python 2.2, but it's not hard to do it in Python 2.1 (or even 2.0) just as well, e.g.: [ key for key, v in thedict.items() if v == avalue ] just a bit slower for huge dictionaries given the need to call .items(). > For example > I have a dictionary > > dict={'aa':1,'bb':2} I STRONGLY suggest you don't use the name of built-in types as the name of your variables. Don't call your variables: list, dict, tuple, int, long, float, str... Python lets you do that, but sooner or later you'll come a doozy. Use alist, adict, ... or else thelist, thedict, .... dict is a built-in name only since Python 2.2, by the way. Alex __________________________________________________ Do You Yahoo!? Yahoo! Movies - coverage of the 74th Academy Awards? http://movies.yahoo.com/ From joefahler at hotmail.com Wed Mar 13 13:17:53 2002 From: joefahler at hotmail.com (fester) Date: 13 Mar 2002 10:17:53 -0800 Subject: Mailman stat script? Message-ID: Hello, I've been searching for quite some time for a program/script that will generate monthly stats for a mailman list. (And output to HTML, which would be very cool) I've found a good one for Majordomo on freshmeat, but so far nothing turns up for Mailman. Does anyone know of such a beast? Thanks for any suggestions... From xd_pan at yahoo.com Sat Mar 2 22:13:29 2002 From: xd_pan at yahoo.com (Xiangdong Pan) Date: 2 Mar 2002 19:13:29 -0800 Subject: make: Fatal error: Command failed for target `Modules/posixmodule.o' Message-ID: Hi, I tried to install Python 2.2 on my unix machine, but it received above error when I typed make. I'm really appreciated if anyone could help me out. Thanks in advance. Patrick ======================================= Here is the system info and error mesg: ======================================= My machine info is: osname=solaris, osvers=2.6, archname=sun4-solaris uname='sunos 5.6 generic_105181-25 sun4u sparc sunw,ultra-60' The complier I use is cc='gcc', gccversion='2.7.2.1', gccosandvers='solaris2.6' The following was the error message I got: gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/posixmodule.c -o Modules/posixmodule.o In file included from /usr/include/sys/wait.h:24, from /pkg/gnu/gcc-2.7.2.1/lib/gcc-lib/sparc-sun-solaris2.6/2.7.2.1/include/stdlib.h:22, from Include/Python.h:50, from ./Modules/posixmodule.c:19: /usr/include/sys/resource.h:148: warning: `struct rlimit64' declared inside parameter list /usr/include/sys/resource.h:148: warning: its scope is only this definition or declaration, /usr/include/sys/resource.h:148: warning: which is probably not what you want. /usr/include/sys/resource.h:149: warning: `struct rlimit64' declared inside parameter list In file included from ./Modules/posixmodule.c:4341: /usr/include/sys/statvfs.h:93: warning: `struct statvfs64' declared inside parameter list /usr/include/sys/statvfs.h:94: warning: `struct statvfs64' declared inside parameter list ./Modules/posixmodule.c:4344: warning: `struct statvfs64' declared inside parameter list ./Modules/posixmodule.c:4344: parameter `st' has incomplete type ./Modules/posixmodule.c: In function `posix_fstatvfs': ./Modules/posixmodule.c:4391: storage size of `st' isn't known ./Modules/posixmodule.c:4401: type of formal parameter 1 is incomplete ./Modules/posixmodule.c:4391: warning: unused variable `st' ./Modules/posixmodule.c: In function `posix_statvfs': ./Modules/posixmodule.c:4419: storage size of `st' isn't known ./Modules/posixmodule.c:4428: type of formal parameter 1 is incomplete ./Modules/posixmodule.c:4419: warning: unused variable `st' *** Error code 1 make: Fatal error: Command failed for target `Modules/posixmodule.o' From mlh at vier.idi.ntnu.no Mon Mar 18 17:03:41 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 18 Mar 2002 22:03:41 +0000 (UTC) Subject: XML help References: Message-ID: In article , Vincent Foley wrote: >Hi, > > I have a XML document . >I want to put the latest_version value in a variable. How would I do >that? Well, to download it, you would probably simply use urllib (very easy to use). To extract the value, you have many options. You don't really have to use xml parsing for such a simple problem. E.g.: from urllib import urlopen url = 'http://freshmeat.net/projects-xml/vim/vim.xml' for line in urlopen(url).readlines(): start = line.find('') end = line.find('') if -1 not in (start, end): print line[start+16:end] On the other hand, using the xml libraries wouldn't be that hard either. > >Thanks -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From gimbo at ftech.net Tue Mar 5 12:43:02 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Tue, 5 Mar 2002 17:43:02 +0000 Subject: Reorganizing python.org (was: Why isn't pychecker...) In-Reply-To: <3C841006.634D0059@tds.net> References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> <3C841006.634D0059@tds.net> Message-ID: <20020305174302.GC1303@andy.tynant.ftech.net> If you're thinking about improvements to the organisation of www.python.org, I'd like to say that I think the module index at http://www.python.org/doc/current/modindex.html is getting bloated by platform-specific modules I don't need to know about. Perhaps it would be a good idea to split this up somehow. Maybe not one list for each platform, but maybe two lists: "Platform independent" and "Platform specific". Then all those Carbon. modules wouldn't distract me so much. ;-) Having said all that, I still find that the most useful page on the site. ;-) Just a thought. Cheers, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From not-a-real-address at usa.net Mon Mar 25 15:19:17 2002 From: not-a-real-address at usa.net (those who know me have no need of my name) Date: 25 Mar 2002 20:19:17 GMT Subject: stdin/stdout redirection mystericals References: Message-ID: [fu-t set] divulged: >I just wondered, why thes dup2 didn't work within my programm, >while an normal shell pipe does it's work... a) neither the python libraries nor dup2 is iso c, the topic of comp.lang.c, so this needs to move elsewhere. restate your question there. b) if workarounds are suggested by people familiar with the subject matter that is an _extremely_ strong indicator that what you want to do cannot be done any other way. -- bringing you boring signatures for 17 years From calves at coelce.com.br Mon Mar 11 12:06:51 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Mon, 11 Mar 2002 14:06:51 -0300 Subject: lambda question Message-ID: <29A97D00F387D411AC7900902770E148044AAFEB@lcoeexc01.coelce.net> Hi all, Look at the two codes below first code: f='x**3+2*x' list=[0,1,2,0] map(lambda x:eval(f),list) second code: def exe1(f,list): return map(lambda x:eval(f),list) Can someone explain to me why the first code works while second doesn't. Carlos Alberto COELCE/DPRON-Departamento de Projetos e Obras Norte Fone: 677- 2228 e-mail: calves at coelce.com.br \|||/ (o o) --ooo0-(_)-0ooo-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sun Mar 31 12:24:03 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 12:24:03 -0500 Subject: Most important extensions? References: <3CA6ADEC.80859964@engcorp.com> <3CA732D6.91163F1E@engcorp.com> Message-ID: In article <3CA732D6.91163F1E at engcorp.com>, Peter Hansen wrote: > >I do hope you will have a chance to mention PyUnit anyway, even >if not as an extension. Learning how to use it will definitely >improve a programmer's productivity. Oh, of course I'll mention doctest and unittest. My focus will be on "batteries included"; the question is which of the *non*-included extensions I should cover. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From graz at mindless.com Sat Mar 16 06:00:13 2002 From: graz at mindless.com (Graham Ashton) Date: Sat, 16 Mar 2002 11:00:13 +0000 Subject: Optimising list comparison References: Message-ID: On Fri, 15 Mar 2002 22:33:29 +0000, Tim Peters wrote: > [Graham Ashton] >> def compare(): >> for i in range(len(list1)): >> a = list1[i] >> b = list2[i] >> if (a != b) and (a != -1) and (b != -1): >> return 0 >> return 1 > > You could also exploit Python's chained comparisons: > > if -1 != a != b != -1: > return 0 That's quite neat. I'll bear it in mind. I do see significant differences in performance for different data sets, as you pointed out. > if list1[i] + list2[i] == 1: > return 0 > > should work fine, and runs at the same speed regardless of relative > frequency of the various input-pair possibilities. Very cunning. And yes, it does go nearly as fast as the original comparison, even under the original loop's most favourable conditions. It beats everything when there is more varied input. :) > Then it's actually quite difficult to explain why > > import operator > def attempt5(list1, list2, sum=operator.__add__): > return 1 not in map(sum, list1, list2) > > isn't quicker than an explicit loop doing the same thing. And it's not. I've tested it, and though it comes quite close I must admit I'm surprised. Has it got something to do with the "1 not in seq" part having to traverse the whole sequence? > Keep trying . Also give > > for a, b in zip(list1, list2): > > a shot. It may surprise you . It's not bad, but the fastest is still attempt4 (see below). >> [breaking out of map()] > > You can't, short of raising an exception. Whether you *want* to break > out early depends on the expected distribution of input pairs; e.g., if, > like the example you're timing, it's typical that the vectors start with > a long stretch of equal elements, breaking early would be much more > useful if you started comparing at the end. I'm not sure about that - that's my friend's research part that I'm not familiar with, but I'm assuming that the frequency of a mismatch will be low, but they could occur at any point in the string. > Well, your specific test case always raises an exception. Exceptions > are cheaper if they're not raised. In the intended application, what > percentage of the time do you expect inequality to occur? An exception > gets more attractive the less often inequality obtains. I don't know that either. We'll have to ask him. Matt - are you reading this? > Note that having to use a lambda is also a drag on speed. map() speed > tricks are much more effective if a builtin function can be mapped. That's very useful to know. > However (and this is a clue to an earlier mystery), an infix "+" applied > to integers is much quicker than operator.__add__ applied to integers. Ah! I see. Thanks for all that Tim - a very enlightening conversation. >> Here's my complete script: >> ... > Thanks! That's very helpful. Well for those who've been following this, here's my latest version. attempt5() is commented out because you need 2.2 to get it to run. ----cut---- #!/usr/bin/env python import time list1 = [1] * 20 ## list1 = [1] * 9 + [0] + [1] * 10 list2 = [1] * 19 + [0] def benchmark(func, iters=100000, l1=list1, l2=list2): start = time.time() for i in range(iters): r = func(l1, l2) end = time.time() print "%d iterations of %s took: %.6f secs" % (iters, func, end - start) def attempt1(l1, l2): for i in range(len(l1)): if (l1[i] != l2[i]) and (l1[i] != -1) and (l2[i] != -1): return 0 return 1 func = lambda a, b: (a == b) or (a == -1) or (b == -1) or 1 / 0 def attempt2(l1, l2): try: map(func, l1, l2) except ZeroDivisionError: pass def attempt3(l1, l2): for i in range(len(l1)): if -1 != l1[i] != l2[i] != -1: return 0 return 1 def attempt4(l1, l2): for i in range(len(l1)): if l1[i] + l2[i] == 1: return 0 return 1 ## import operator ## def attempt5(l1, l2, sum=operator.__add__): ## return 1 not in map(sum, l1, l2) def attempt6(l1, l2): for a, b in zip(l1, l2): if a + b == 1: return 0 return 1 if __name__ == "__main__": ## for f in (attempt1, attempt2, attempt3, attempt4, attempt5, attempt6): for f in (attempt1, attempt2, attempt3, attempt4, attempt6): benchmark(f) ----cut---- ratchet% python listmatch.py 100000 iterations of took: 3.349525 secs 100000 iterations of took: 7.734273 secs 100000 iterations of took: 4.878889 secs 100000 iterations of took: 3.413134 secs 100000 iterations of took: 4.656984 secs -- Graham From m.faassen at vet.uu.nl Mon Mar 11 06:34:31 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 11 Mar 2002 11:34:31 GMT Subject: PEP 2, Procedure for Adding New Modules References: Message-ID: Aahz Maruch wrote: > The maintainers also possess primary responsibility for determining > whether bugfixes should be backported to previous Python releases as > discussed in PEP 6. Thanks; I'm adding some phrases on this to PEP 2. PEP 6 claims it's a 'draft' PEP by the way, what is its status? Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From kwg at renre-europe.com Wed Mar 20 09:24:33 2002 From: kwg at renre-europe.com (Ken Guest) Date: 20 Mar 2002 14:24:33 +0000 Subject: tkinter menuitem question Message-ID: <1016634274.18026.39.camel@lewis> ok, I might be way off here but is there a way with a collection of Tkinter menuitems that all have their callbacks set to be the one function to determine which menuitem was clicked on? for example, given the snippet: menubar1=Pmw.MenuBar(vbox1) menubar1.addmenu('TopLvlMenu','this is a tooltip') menubar1.addcascademenu('TopLvlMenu', 'Item#6','tool tip for item 6') menubar1.addmenuitem('Item#6', 'command', '', label="item#7",underline=0, command=menu_item_selected) menubar1.addmenuitem('Item#6', 'command', 'oct', label="item#8", underline=0, command=menu_item_selected) menubar1.addmenuitem('TopLvlMenu', 'command', 'naoi', label="item#9", underline=0, command=menu_item_selected) menubar1.addmenuitem('TopLvlMenu', 'separator', '') menubar1.addmenuitem('TopLvlMenu', 'command', '', label="item10", underline=0, command=menu_item_selected) menubar1.pack(expand=NO, side=TOP) Is it possible to give these menuitems the one handler function/callback function that can determine which item was clicked on? The reason for asking is that I have a dynamically generated cascading popup menu and need to know which menuitem has been selected. I have thought of displaying a very small dialog box which would only contain a combobox and nothing else. the dialog box would be unloaded once the user selects an item from the combobox but this wouldn't really work as there need to be cascaded entries. any ideas? k. From * at spam.ruud.org Wed Mar 13 11:34:55 2002 From: * at spam.ruud.org (ruud de rooij) Date: 13 Mar 2002 11:34:55 -0500 Subject: Why I think range is a wart. References: Message-ID: <873cz44ea8.fsf@bunty.ruud.org> > > for index in range(len(mylist)): > > > several solutions: > > # if whatever contains only refs to mylist [index] > for element in mylist: > > > # if you really need the index > def listIndices (list): > return range (len (list)) > > for index in listIndices (mylist): > > > # my favourite > class IndexAndElement: > def __init__ (self, list): > self.list = list > > def __getitem__ (self, index): > return (index, self.list [index]) > > for index, element in IndexAndElement (mylist): > > > There's more than one way to heal a wart. perhaps lists should support .keys() and .items() for those operations (analogous to dictionaries). - ruud -- ruud de rooij | *@spam.ruud.org | http://ruud.org From djc at object-craft.com.au Wed Mar 13 07:16:59 2002 From: djc at object-craft.com.au (Dave Cole) Date: 13 Mar 2002 23:16:59 +1100 Subject: Python embedded like PHP References: Message-ID: > >Are there any projects out there that allow you to embed python in > >HTML like PHP? I like the PHP-style of embedding the bits of > >program in HTML, but I'd like to use python... Something like: > > > > > > > print "
      " > > for reptile in ["Crocodile", "Python", "Iguana", "Tortoise"]: > > print "
    • %s
    • " % reptile > > print "
    " > >?> > > The example Andrew presented is certainly the Albatross way, but you could also do things like this with Andrew's improved template parser in 0.06 (if you were so inclined): - - reptile.html - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - The example program adds a write() method to the execution context to make it look like a file for the print statement. - - reptile.py - - - - - - - - - - - - - - - - - - - - - - - - - - - #!/usr/bin/python import sys import albatross class Ctx(albatross.SimpleContext): def write(self, data): self.write_content(data) ctx = Ctx('.') ctx.locals.reptiles = ["Crocodile", "Python", "Iguana", "Tortoise"] template = ctx.load_template("reptiles.html") old_stdout = sys.stdout try: sys.stdout = ctx template.to_html(ctx) finally: sys.stdout = old_stdout print "Content-Type: text/html" print ctx.flush_content() - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Produces the following output... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Content-Type: text/html
    • Crocodile
    • Python
    • Iguana
    • Tortoise
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Dave -- http://www.object-craft.com.au From grante at visi.com Sat Mar 9 22:30:00 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 03:30:00 GMT Subject: Standalone Win32 wxPython apps? Message-ID: I'm considering writing a wxWindows app for Win32. The only way I'm willing to do this is by doing all of the development under Unix, and then grit my teeth while I package up the final product for Win32. I've already got a command-line application that runs under Win32/Cygwin/Unix, but it far too small, quick, and efficient. In order to alleviate those problems, I need to stick on a hard-to-use GUI to make the program comfortable for windows users. In order for it to be useful, I'll need to be able to distribute it as a stand-alone app to users who don't have (or care to have) a regular Python or wxWindows distro installed. Optimally, it would be a single "exe" file that doesn't require any installation procedure. If that's not possible, it would be permissible to use a typical "isntall-wizard" type installation: running the exe installs the required files somewhere, adds a start-menu entry, leaves an un-installer around. It looks like Gordon McMillan's installer might fit the bill. Anybody care to share any experiences distributing wxWindows apps for Win32? -- Grant Edwards grante Yow! Clear the at laundromat!! This visi.com whirl-o-matic just had a nuclear meltdown!! From siegfried.gonzi at kfunigraz.ac.at Sun Mar 17 04:38:56 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Sun, 17 Mar 2002 10:38:56 +0100 Subject: basic statistics in python References: <3C931C23.B0B2BF75@kfunigraz.ac.at> Message-ID: <3C946430.8A4408ED@kfunigraz.ac.at> Tim Churches wrote: > > delivers: > > > > Min. 1st Qu. Median Mean 3rd Qu. Max. > > 0.230 1.226 7.300 18.960 31.680 78.900 > > > > Everything is correct, except the 1st quantile and 3rd quantile. > > You mean 1st quartile and 3rd quartile, not quantile. And the values > calculated by R are not wrong, just different (see below). The book "Statistical Methods in the Atmospheric Sciences", by D.S. Wilks, does not really make a difference between "quantiles" and "quartiles". According to the book I got the impression that quartiles is inferior to quantiles (e.g. page 24: "Example 3.1. Computation of Common Quantiles". But you are right that I should be more precise in order to avoid confusion. > There are a number of methods for calculating quantiles. In R, the > summary() function calls the quantile() function to calculate the 1st > and 3rd quartiles and the median. The quantile() function uses linear > interpolation to calculate the sample quantile for the probabilities of > 0.25 and 0.75, whereas XLispStat is just taking the arithmetic mean of > the 2nd and 3rd, and 6th and 7th values respectively (using zero-based > indexing/counting, since this is the Python list).# My first guess was also that R just calculates the quantiles in a different fashion; but I could not find any hints in the documentation. According to the beforementioned book (page 23): "Almost as commonly used as the median are the quartiles, q0.25 and q0.75. Usually these are called the lower and upper quartiles, respectively. They are located halfway between the median, q0.5, and the extremes, x(1) and x(n). In typically colorful terminology, Tukey (1977) calls q0.25 and q0.75 the 'hinges', imagining that the data set has been folded first at the median, and the quartiles." I simply thought (and note the word "halfway" in the citation) then XLispStat is/was correct. > The methods used by R are fully described in the R manual (see > help(quantile)), but a commonsense explanation of the R approach is as > follows (again using zero-based indexing/counting). Maybe I did look too superficialy after the method of calculation. Regards and especially thank you for your insight, S. Gonzi From mail at andreas-penzel.de Tue Mar 26 18:00:40 2002 From: mail at andreas-penzel.de (Andreas Penzel) Date: Wed, 27 Mar 2002 00:00:40 +0100 Subject: seek in a file Message-ID: Hello NG! How to jump to a specified line in a file which is read-opened? With seek() I can jump to an exact position of the complete file in "byte-steps". Is seek able to jump to a line-number? If not, what else can I do? Thanks for help! - Andreas From gtalvola at nameconnector.com Fri Mar 22 14:18:22 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Fri, 22 Mar 2002 14:18:22 -0500 Subject: Why do Windows sockets break after exactly 4 minutes? Message-ID: Peter Hansen wrote: > Geoffrey Talvola wrote: > > > > I've noticed that Windows sockets seem to close all by > themselves if there > > is no activity for 4 minutes. Does anyone know why? Is it > possible to > > control this behavior? Just a link to some documentation > of this behavior > > would be greatly appreciated. > > > > I don't think the same thing happens on Linux, or maybe it > does but the > > timeout is longer than 4 minutes there. > > > > I've attached a set of 2 test scripts that provoke the > behavior. Start up > > server.py first, then client.py, then wait 4 minutes. > > Haven't run your tests, but isn't this what SO_KEEPALIVE is used for? > > > Try using: > > import socket > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) > > and this will turn on the keep-alive feature (I think... pulled > that last line from pygale.py since I don't know where it > is well documented). I tried that after I sent the original message. But after putting in calls to turn on keepalive in every place and combination I could think of, it still made no difference. If the time.sleep() is for less than 4 minutes, everything works, but if it's > 4 minutes, a socket.error exception gets thrown on the client side. - Geoff From rnd at onego.ru Sun Mar 3 06:56:45 2002 From: rnd at onego.ru (Roman Suzi) Date: Sun, 3 Mar 2002 14:56:45 +0300 (MSK) Subject: RFC PEP candidate: q''quoted ? In-Reply-To: Message-ID: On 3 Mar 2002, Bengt Richter wrote: >Problem: How to put quotes around an arbitrary program text? Have it in a separate file. >Obviously a program may contain quoted material using all the >defined string quoting methods (and this new method as well), >so the problem is defining delimiters that won't occur in the text. > >I propose using a variation of the MIME multipart delimiter idea: > >Note the lack of quotes around the final delimiter string, since it itself is >the final delimiter. This can also be used to solve the final unescaped >backslash problem for quoting windows paths: > > q'|'c:\foo\bar\| Making Python as gibberish as Perl is. And all that only to have Windows path be written without double-\ AFAIK, latest Windows also use / for delimiting dirs. So this is non-problem. >Regards, >Bengt Richter > > Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Sunday, March 03, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "Why build a wall round a cemetery when no-one wants to get in?" _/ From usenet at thinkspot.net Sun Mar 17 14:08:20 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 11:08:20 -0800 Subject: Where to download bugfix for email Module? References: Message-ID: On Sun, 17 Mar 2002 14:43:02 +0300, Oleg Broytmann wrote in comp.lang.python in article : > If you still will have troubles, > I can tar and send my copy to you. Well, I managed to download the files onto my computer. Not sure yet what I'm going to do with them, but at least I *HAVE* them. Hmm... Per my other questions, I got some remarks on that from another person, here: http://www.aota.net/forums/showthread.php?s=&postid=63779#post63779 Where skolnic writes: """ I think working with the CVS repository addresses your concerns directly. To wit: 1) stability CVS maintains everything that gets checked in. Most projects will use tags to label stable points in the tree. You can check out the latest stable tree, and then only check out the more recent versions of the individual source files you care about. In fact, you can generate diffs between the latest bleeding edge and the last stable release [run to garage to get Cederqvist manual out of the car]: checkout the latest, then cvs diff -r stable-release to see all the changes or cvs diff -r stable-release module-I-care-about . From the output, you should be able to identify the code that provides the functionality you care about and merge only those changes into the codebase you use locally. 2) distribution This is more of a challenge. One could hope that the functionality you need makes it into a stable release by the time you are ready to distribute. You can also post/distribute either a patch file or a patched module. I think that I would incorporate the needed functionality into a module of my product (lifting liberally from the Python sources, i.e. rename and edit only as needed) and distribute it as an integral part of the tool. Tracking the stability of the functionality in the framework (Python here) then becomes your task--transparent to the users--to decide when to drop the integral module and use the framework. With CVS running locally (server, not just client) you can maintain your own release version control that includes customized framework modules, and run diffs against the public baseline to ease the management of what becomes a personal branch of the Python distribution. You can find the Cederqvist manual on-line at www.cvshome.org. I also recommend Karl Fogel's Open Source Development with CVS ISBN 1-57610-490-7. This all falls into the category I call constructive laziness. Work my behind off setting things up so that they are easy. Sort of like carrying a dozen grocery bags in from the car all at once so I only have to make one trip. """ Sounds like WAY more than I want to get into at the moment, but I may look into it in the future. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From phd at phd.pp.ru Fri Mar 29 10:07:06 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Fri, 29 Mar 2002 18:07:06 +0300 Subject: Python embedded like PHP In-Reply-To: <23891c90.0203290655.25bbcab9@posting.google.com>; from paul@boddie.net on Fri, Mar 29, 2002 at 06:55:54AM -0800 References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> <23891c90.0203290655.25bbcab9@posting.google.com> Message-ID: <20020329180706.E27418@phd.pp.ru> On Fri, Mar 29, 2002 at 06:55:54AM -0800, Paul Boddie wrote: > It's actually quite reminiscent of the earliest versions of DTML, in > fact, where comments are used to mark the structure of the "model" as They are not exactly comments, they are modelled after Apache SSI (which are comments, I must admit :) Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From eddieborder2001 at yahoo.co.uk Fri Mar 1 13:07:42 2002 From: eddieborder2001 at yahoo.co.uk (Ed) Date: 1 Mar 2002 10:07:42 -0800 Subject: hotmail Message-ID: hi im just wondering whether it is possible to access hotmail thru python so that i have a far quicker way of checking my emails. can telnetlib do this? thanx ed From martin at v.loewis.de Sun Mar 24 04:12:14 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Mar 2002 10:12:14 +0100 Subject: forgetting state References: <98b6685d.0203231539.1459d00d@posting.google.com> Message-ID: emersonwood at yahoo.com (Emerson Wood) writes: > Hi, how would I make a python interpreter > shell forget everything that I've done > and run a script or accepts commands as > if it were first run? You will explicitly need to clear all state. There is no builtin feature to do that. In addition, it is not possible at all to unload extension modules. Regards, Martin From phd at phd.pp.ru Wed Mar 13 06:46:48 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 13 Mar 2002 14:46:48 +0300 Subject: 16-Bit MS-DOS and Python In-Reply-To: ; from mail@andreas-penzel.de on Wed, Mar 13, 2002 at 12:17:23PM +0100 References: Message-ID: <20020313144648.D28183@phd.pp.ru> On Wed, Mar 13, 2002 at 12:17:23PM +0100, Andreas Penzel wrote: > Is it possible to run Python-Programs with Microsoft DOS 6.2, 16-Bit? Only with *VERY* old python, like 1.2. New pythons require much more memory. But it is possible to run DOS Python in 32-bit mode. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From johannh at uclink.berkeley.edu Sat Mar 23 03:18:03 2002 From: johannh at uclink.berkeley.edu (Johann Hibschman) Date: 23 Mar 2002 00:18:03 -0800 Subject: simple question References: <2UVm8.30655$J54.1855090@news1.west.cox.net> Message-ID: Christopher Palmer writes: > Let's say I have a variable called a > and a contains an integer, say 4522 > and I want 4, 5, 2, and 2 to be items in a list instead of an integer... Try: map(int, str(a)) --Johann From peter at engcorp.com Thu Mar 21 19:11:21 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 21 Mar 2002 19:11:21 -0500 Subject: How Can I Determine the Operating System with Python? References: Message-ID: <3C9A76A9.41956E4C@engcorp.com> Mark Gash wrote: > > * Mark Hadfield [2002-03-21 14:02 +1200]: > > >>> import sys > > >>> sys.platform > > 'win32' > > >>> import os > > >>> os.name > > 'nt' > > That's a crude way of determining the platform, because sys.platform > depends on the compiler used to compile Python. Yes, even on Windows. > But I'm reasonably sure that the Pythonlabs folks won't change their > Windows compiler anytime soon. > > I'd very much like to have a real way for determining the platform. > Anybody wants to write a PEP? :-) > > The only way of defining the os name that I have found is then to examine > the os.environ .By examining the COMSPEC you will be able to determine a win > 9X machine opposed to an NT or 2000 machine (comspec for 9X will show > command.com whereas win32 machines will show cmd.exe). This, and the other proposals, may be exactly the wrong thing to do, if you've at all followed Alex Martelli's advice about type checking. The approach whereby you check explicitly for a certain environment and then take certain actions based on that, such as running particular executables and so on, is very like doing type testing when passed an object instead of just trying to call methods and catch the exceptions if the call fails. It's not good to say "this isn't a File object so I refuse to try writing to it" when you can say "try writing, but don't crash if there's no write method". Simpler, robust, and much more flexible if someone wants to send in a non-File object which fakes it. For example, rather than checking that os.environ['COMSPEC'] is command.exe and assuming if it's not you aren't on Win98, one should just check for the external program needed and if it exists, run it. If instead you build in too much "smarts" by doing explicit checking, you'll end up screwing people who have replaced command.exe with something more useful, such as might happen with certain replacement shells. They might not have COMSPEC set to command.exe, but unless you really are trying to run the standard Win98 command.exe file, you don't really care about that. What you care is whether the action you are trying to take will work or not. So try taking the action and catch any exceptions. (Yes, there are times when you do need to check explicitly, but they're probably rarer than one might think.) -Peter From msx at crs4.it Thu Mar 14 10:07:39 2002 From: msx at crs4.it (Federico Caboni) Date: Thu, 14 Mar 2002 16:07:39 +0100 Subject: Good book on Python? References: Message-ID: On 14-03-2002 15:35, in article Qy2k8.377386$Aw2.31139131 at bin7.nnrp.aus1.giganews.com, "Brett g Porter" wrote: [SNIP] > The second edition (updated to Python 2.1) has been available for some time > now. I second the recommendation. > Wow....that's cool...I'll buy it then. I found that book the most useful thing to keep in my desktop while coding w/python (except maybe coffee ;) ) Thanks a lot ____ ____ ____ _ _ ____ _ _ ____ / ___)| __ \/ ___)/ /| | / ___)| \| |/ ___) Federico Caboni (msx at crs4.it) | (___ | /\___ \\__ | * \___ \| |\___ \ Software & Network Solutions \____)|_|\_\(____/ |_| (____/|_|\_|(____/ Phone: +39 070 2796 368 CRS4, Center for Adv. Studies, Research and Development in Sardinia From dale at riverhall.NOTHANKS.co.uk Thu Mar 28 03:34:38 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 28 Mar 2002 08:34:38 +0000 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: "A.M. Kuchling" wrote: > >I have vague memories of adding PythonWin to the Python CVS tree being >suggested on python-dev long ago. Wonder if that idea should be >revived for 2.3? > Absolutely. All of Mark's Win32 stuff are pretty much essential to many Windows users now, I would guess. Updating the distro package would be nice too: Add a few handy registry tweaks, such as setting PATHEXT properly, and a nice HTML Windows help file (chm) and we'd have a nice slick package. -- Dale Strickland-Clark Riverhall Systems Ltd From anton at vredegoor.doge.nl Wed Mar 13 07:59:28 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 13 Mar 2002 13:59:28 +0100 Subject: Is Python an object based programming langauge? References: Message-ID: On 11 Mar 2002 07:31:55 -0800, drevenhaug at hotmail.com (Graz Bukanoff) wrote: >Is Python an object based programming langauge? Short answer: Yes, but at least for me there can be some confusion originating from factors that have to do with graphical user interfaces. Long answer: Some modern programming IDE's (integrated development environments) are trying to adapt the way user thinks to the way the computer works. A computer is a thing that is in an infinite loop where sometimes events can trigger certain actions. For example in the old days of Borland Pascal or Borland C it was easy to write a program that did certain things and then exited. Now with modern Delphi or C++ Builder its a real accomplishment to write such a program. It goes directly against the paradigm of always creating a form (a form is a container for graphical objects) whether one needs one or not, and since forms are reacting to events one has to generate an exiting event. In this view it's also natural to view graphical things on the screen as objects, and to have objects react to events. (user clicks button) This idea has become very pervasive and can be seen in other IDE's that are of the GUI kind (graphical user interface). In python most of the time objects are not connected to graphical elements on the screen. In Delphi, C++ Builder and Visual Basic there are also non graphical objects, but these IDE's *start* with graphical objects and introduce other objects later. In python it is the other way around: It is possible to have graphical objects and infinite loops and events but a starting python script is often more like the "old" way of programming. This makes it easy to try things out. Complex loops and graphics can be added later. Both ways of designing programs have some advantages. Different ways of viewing objects -as graphics reacting to events or as datacontainers reacting to methodcalls- can be appropriate. A program can be nongraphic but still be object oriented and reacting to events, for example a webserver. The resulting confusion sometimes leads to not recognizing the object oriented (or object based?) nature of other language-IDE combinations. On the other hand its entirely possible that the source of the confusion is something completely different. Anton. From jgardn at alumni.washington.edu Fri Mar 8 00:54:37 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Fri, 08 Mar 2002 14:54:37 +0900 Subject: Seek fame(*) & fortune(**) as a Python developer References: Message-ID: Skip Montanaro scribbled with his keyboard: >>> http://mail.python.org/mailman/listinfo/python-dev >Darrell> Have you changed to acceptance criteria? > > Yes, I believe python-dev has opened up. Try subscribing again and see > what happens. ;-) > Deferred for administrator's approval. Jonathan From jason at jorendorff.com Tue Mar 12 16:43:34 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Tue, 12 Mar 2002 15:43:34 -0600 Subject: RFC PEP candidate: q''quoted ? In-Reply-To: <6Ytj8.10726$mp.48831@news-server.bigpond.net.au> Message-ID: Neil Hodgson wrote: > In my experience writing a lexer for Perl (for use in syntax styling > editors), 'here documents' and arbitrary quote sequences add much > complexity to a lexer. [...] (skeptical look) Are you really claiming to have written a lexer for Perl? Is that even possible? ## Jason Orendorff http://www.jorendorff.com/ From greg at cosc.canterbury.ac.nz Sun Mar 10 22:55:59 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 11 Mar 2002 16:55:59 +1300 Subject: Integers class...? References: <3C882BF0.B7B6A239@cosc.canterbury.ac.nz> <6qd6yf461k.fsf@abnoba.intevation.de> Message-ID: <3C8C2ACF.D7B2FEA@cosc.canterbury.ac.nz> Bernhard Herzog wrote: > > Slices support a step parameter, so > > for x in int[9:-1:-1]: I don't consider that a good solution, for two reasons: (1) I'm not sure what the semantics are of slices with negative steps. There are at least 4 equally plausible interpretations of [a:b:-c] if you count all the possible combinations of endpoint swapping and open/closed swapping. (2) Even if the semantics are well-defined, it's too mind-bending remembering and applying them correctly in any given situation. It's no better than range(a,b,-c) in that respect. This is one of the things I was trying to address with for x <= i < y. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From not at all.com Mon Mar 11 15:31:54 2002 From: not at all.com (Nom de Plume) Date: Mon, 11 Mar 2002 12:31:54 -0800 Subject: Setting UNIX environment with a Python script Message-ID: <3C8D143A.17963385@all.com> I connect to about 10 different servers which are various platforms, e.g. Irix, AIX, Solaris, HP-UX. Each has different versions of Oracle running on it with different SIDs based on what the others are using at my work. Each time I want to change SIDs, I have an Oracle environment file which I source and it sets the appropriate shell variables, e.g. ORACLE_HOME =, etc. I have written a little menu in Python which will determine the host that I am connected to and present all the Oracle Environment files for that server, along with a corresponding numeric option so that I just have to type '3' and enter and it will set my Oracle environment for that session. The only step left is sourcing the ora_env.[name] file from within Python in a way such that the environment of the parent shell is modified. Anyone have any ideas? I have tried: src_cmd = 'source ' + ora_env.file os.system ( src_cmd ) but it doesn't like that. From logstx at bellatlantic.net Mon Mar 25 17:45:55 2002 From: logstx at bellatlantic.net (logistix) Date: Mon, 25 Mar 2002 22:45:55 GMT Subject: pythonwin and raw_input Message-ID: I could've swore I posted this yesterday, so please have mercy on my soul if my news server is just messed up. Does anyone know how to access the builtin raw_input function in pythonwin? Pyhtonwin overrides it with a dialog box. This doesn't work out too well with the following: import code code.interact() -- - From aahz at pythoncraft.com Sun Mar 31 12:21:24 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 12:21:24 -0500 Subject: Thread blocking problem References: Message-ID: In article , Garyr wrote: > >I have a program consisting primarily of a simple Tinker GUI and in separate >thread some code that invokes a function in a C++ extension module that >blocks on WaitForSingleObject most of the time. The Python code is a >producer and the C++ code the consumer, a sound card driver. > >Shouldn't the GUI be responsive when the code in the thread is blocked? Not unless you've released the Global Interpreter Lock. See http://www.python.org/doc/current/api/threads.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From bokr at oz.net Thu Mar 14 15:24:58 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Mar 2002 20:24:58 GMT Subject: redirecting stdin with Python scripts under win2k (solution) References: <9t119uo75apvom6ghje49fk21b5o325n99@4ax.com> Message-ID: On Thu, 14 Mar 2002 11:38:52 +0000, Dale Strickland-Clark wrote: >I'm sure you're very pleased with that but I don't see the point. > >If I want to run a Python program, I just type the name of it at a >command prompt. > Yes, but that is not the key point of Syver's contribution. >A few prerequisites need to be in place but some of these happen >during install: > >1. The directory containing the script needs to be in your PATH >environment var or be the current directory. >2. PATHEXT environment var needs to contain ".PY;.PYC;.PYW" >3. The Python exes need to be associated with the Python file types. > >Once you get all the above right, you just type: > >C:\> wibble args > >and it runs: > >"C:\Python21\python.exe" "wibble.py" args > You are missing the key point, which is about redirection of i/o. If you tried to use your wibble thus: wibble args > outputfile You would get a zero length output file on NT4. Syver solved _that_ problem without using a separate wrapper. I would have been pleased to have thought of it, especially since I recently posted separate wrapping solutions. Plus, not long ago I saw a post using a similar technique with a linux shell in a cgi context, and I didn't make the connection. Syver either re-invented that (for windows) or made the connection and reformulated it. Either way, I think he deserves credit, not a comment like "I'm sure you're very pleased with that ..." >This only works with Win NT/2K/XP. As for 95/98/ME, well it's easier >not to bother, really. > >Disguising your Python programs as batch files is going to knacker any >attempt your editor may make to help with syntax highlighting and >suchlike. That may be a downside for editors that decide on the basis of file extension, but you are not obligated to do all your scripts this way ;-) Being able to invoke a script concisely and have its output redirectable is something you want for full flexibility e.g. in putting customized scripted build steps in the VC++ IDE for e.g., customizing building Python from source on windows. Being able to wrap without a separate file is a good thing IMO, although for scripts that are supposed to be verbatim (e.g. signed etc) portable to *nix, you'd want to continue using separate wrappers in windows. If you use a hash, e.g. MD5, or PGP to sign/validate a script, should it be based on canonicalizing to unix format (i.e., \n vs \r\n or \r)? I imagine the XML folks must have decided something. ...but I don't have time to google every stray question that pops to mind ;-) > >Also, FYI, I think all the command extensions you mention were >introduced with NT 4. Yes, the technique works on NT4, which pleases me ;-) The cmd.exe batch command line syntax is really horrid, weak, and badly documented though, so it's nice to be able to transition to Python in one line! Regards, Bengt Richter From tanzer at swing.co.at Sat Mar 30 02:38:01 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Sat, 30 Mar 2002 08:38:01 +0100 Subject: PEP 285: Adding a bool type In-Reply-To: Your message of "Fri, 29 Mar 2002 23:28:21 PST." <3CA56915.62947DDC@alcyone.com> Message-ID: Erik Max Francis wrote: > > Because the repr() or str() of a bool value is different from an > > int value, some code (for example doctest-based unit tests, and > > possibly database code that relies on things like "%s" % truth) > > may fail. How much of a backwards compatibility problem this will > > be, I don't know. If we this turns out to be a real problem, we > > could changes the rules so that str() of a bool returns "0" or > > "1", while repr() of a bool still returns "False" or "True". > > Where is the backward compatibility problem for using bool? At present, > no one uses it, so none of their types will be bools (right?). Even if > they happen to use the values True and False (or whatever gets adopted), > those can be overridden just like None, so if they define and use them > they should get their values, not Python's. Right? The value of `"%s" (not x, )` is going to change. Any code depending on the old way will break. -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From wurmy at earthlink.net Mon Mar 11 05:09:54 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Mon, 11 Mar 2002 10:09:54 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> Message-ID: <3C8C82D3.CA4220CA@earthlink.net> Eric Brunel wrote: > > Hans Nowak wrote: > > It's not April 1st yet... > > Considering Brad's article was posted on 2001-07-02, it certainly wasn't at > that time... ;-) > Can anyone using a recent version of Microsoft development tools confirm > whether it's a hoax or not? If it isn't, this is bad news... > - eric - It sure smells like a hoax. I mean, really: """Microsoft has only been able to achieve this position of near hegemony on the implicit premise that its products and tools would always remain open and unrestricted in their usage. If Microsoft had ever tried to thwart its competition by legally or technologically preventing competitive software from running on their systems or being built with their tools, then they would have been unlikely to have retained customers or to have grown so dominant.""" "Open and unrestricted"? It sure seems ludicrous to see these words in the same sentence with "Microsoft". -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From bokr at oz.net Thu Mar 28 22:58:56 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Mar 2002 03:58:56 GMT Subject: mutliple search and replace References: Message-ID: On 29 Mar 2002 02:00:03 GMT, bokr at oz.net (Bengt Richter) wrote: [...] >Here is something to deal with the key order problem (i.e., if one >key is a substring of another. You have to sort by length to get >maximal or minimal matching. This is for maximal: > > >>> def dirinterp(s,d): > ... import re > ... klist = [(-len(k),k) for k in d.keys()] > ... klist.sort() > ... resp = re.compile('('+'|'.join([k for l,k in klist])+')') > ... return ''.join([kv.get(w,w) for w in resp.split(s)]) ^^--oops, that worked because of a leftover global ;-/ > ... > >>> subdir = {"sub":"","substring":""} > >>> dirinterp("Will sub or substring be replaced?",subdir) > 'Will or be replaced?' > >>> dirinterp("Will substring or sub be replaced?",subdir) > 'Will or be replaced?' > >This is hardly tested at all, but I guess it could be handy. Must run in fresh interpreter before posting ;-/ >>> from miscutil import subbydict >>> d={'x':'A', 'xx':'B','xxx':'C'} >>> s='xxxxxx xxxx xxx xx x' >>> subbydict(s,d) 'CC CA C B A' >>> s='xxxxxx xxxxx xxxx xxx xx x' >>> subbydict(s,d) 'CC CB CA C B A' where name changed and kv->d def subbydict(s,d): import re klist = [(-len(k),k) for k in d.keys()] klist.sort() resp = re.compile('('+'|'.join([k for l,k in klist])+')') return ''.join([d.get(w,w) for w in resp.split(s)]) Regards, Bengt Richter From ullrich at math.okstate.edu Thu Mar 7 11:47:12 2002 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Thu, 07 Mar 2002 16:47:12 GMT Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: <3c879853.166102962@news> On Wed, 06 Mar 2002 09:12:09 -0500, Ramkumar Kashyap wrote: >I find that most introductory books approach programming in a >non-intuitive manner and lose out on a big chunk of their audience. > Only a few of us that persevere, end up learning the language and even >fewer go on to achieve "GURU" status. Why is this? > >I have seen several posts on CLP and the newbie tutors list, where >people mention that their first encounter with programming was in BASIC, >COBOL, Pascal, Fortran. They did not really make any progress, gave up >on programming. Now they are attempting once again, hoping things have >become a little easier. > >I would like to know how the pattern was set to teach programming >languages. You do an introductory program like "Hello World", learn how >to compile and run it. Then jump into decision structures, loops, >functions, etc. > >This is extremely non-intuitive to most people. Most 5,6,7 year olds >can speak fluently in their native languages, but how many of them could >tell you about vowels, consonants, nouns, verbs, adjectives. In fact >quite a few of them speak multiple languages, can easily differentiate >sentence structures in those languages, but would be hard-pressed to >give defintions of the above. > >So how come in programming, we ALWAYS jump into the constructs of a >language, rather than just doing, gaining proficiency and then >understanding how it is put together? Because a child can make himself understood even though he's speaking with atrocious grammar, while invalid code doesn't do anything but generate an error message? >I think that unless the approach to teaching Programming languages, is >changed and follows the more universal style of teaching spoke language >or verbal communication, Computer Programming for Everybody will remain >a dream. David C. Ullrich From phr-n2002a at nightsong.com Fri Mar 8 09:08:15 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 08 Mar 2002 06:08:15 -0800 Subject: Turn string into function call References: <1f5252d4.0203080545.3861adec@posting.google.com> Message-ID: <7x1yevxicw.fsf@ruckus.brouhaha.com> nbecker at fred.net (N Becker) writes: > What's the best way to turn a string naming a function into a function call? > > I used this: > eval (funcname + '()') vars()[funcname]() might be a little safer. From logiplexsoftware at earthlink.net Wed Mar 6 16:26:12 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 6 Mar 2002 13:26:12 -0800 Subject: Threading help? In-Reply-To: <3C867E68.B4C3FED2@accessforall.nl> References: <3C867E68.B4C3FED2@accessforall.nl> Message-ID: <20020306132612.4a5d756a.logiplexsoftware@earthlink.net> On Wed, 06 Mar 2002 21:39:19 +0100 Ype Kingma wrote: > VanL wrote: > > I need three threads (at least): > > > > 1. Every .1 second, retrieves some data via http from an adjacent > > machine on the network. Easy enough with urllib. > > 2. Do processing on that data > > 3. Every .1 second, be ready to spit out the most recent results from > > the processing in response to an http query. I've got the latest medusa > > distribution, and I was thinking about using that. It doesn't really > > matter, though. > What would you gain from using separate threads for task 1 and 2, ie. > what's the point of getting new data (task 1) before the processing on that > data (task 2) has finished? One good reason to use threads in this context is to ensure that the network port gets serviced in a timely fashion. How long the processing is expected to take is the deciding factor in whether threads are appropriate. In this case, the OP wants to service the port every .1s. What if the processing takes longer than .1s? > Assuming you combine task 1 and 2 in a single thread B, that thread should > yield a few times during your 0.1 second period to allow an evt. execution > of task 3 in thread C. In case you have thread priorities available > you can give C a higher priority instead of yielding in B. > > In case you decide to have task 1 in a separate thread A you > can treat A as C. You might need to yield more often in B with two > other threads instead of one. > > A simple reference to the last available processing result > can be shared between any pair of threads. Make sure to > copy the reference (not the last result itself) in the receiver. The approach I would take, based upon the information given, is to have thread A retrieve the data every .1s (using time.sleep), when the data is retrieved, put it on a Queue and go back to sleep. Thread B blocks on the Queue until data is available. When data becomes available, B processes that data and place it on a second Queue for thread C (thread C handling HTTP requests) to deal with. Whether this will occur within the time constraints is difficult to say. However, if thread C is simply serving HTTP requests, I imagine it could simply resend the last processed data if no new data is available when the request comes in. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From ponderor at lycos.com Mon Mar 18 09:36:41 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 18 Mar 2002 08:36:41 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 18) Message-ID: <86AF6DCEFA992F8B.4CD196BCE4C4A45A.75D2F5BCF712DA37@lp.airnews.net> QOTW: [Cross Platform Environment Tips] "I'd really recommend that you vary quite frequently your tune selection (there's some good Internet radio stations if your mp3 collection isn't large enough). There's nothing worse than ruining a great CD because hearing it reminds you of some awful project you worked on." - Dave Brueck http://groups.google.com/groups?start=175&hl=en&ie=ISO-8859-1&oe=ISO-8859-1&group=comp.lang.python&selm=mailman.1015952421.10168.python-list%40python.org "I'm pretty sure it's because the hobbits were all wiped out after Sauron rose again and conquered Middle Earth, imposing the Unified Mordorian Calendar system across much of the planet until the changes made by Pope Gregory in 1582." - Peter Hansen PEP 279 updates Enhanced Generators. http://groups.google.com/groups?start=175&hl=en&ie=ISO-8859-1&oe=ISO-8859-1&group=comp.lang.python&selm=mailman.1015961402.6720.clpa-moderators%40python.org Now version 1.6 http://python.sourceforge.net/peps/pep-0279.html NormalDate 1.2 Released! Historical Calendar Discussion Ensues. http://groups.google.com/groups?hl=en&ie=ISO-8859-1&oe=ISO-8859-1&threadm=Xns91D08815184B2svenaxelssonbokochwe%40212.37.1.234&prev=/groups%3Fnum%3D25%26hl%3Den%26ie%3DISO-8859-1%26oe%3DISO-8859-1%26group%3Dcomp.lang.python%26start%3D150 python 2.2 bug encounter http://groups.google.com/groups?hl=en&ie=ISO-8859-1&oe=ISO-8859-1&frame=right&th=bd7e08291b334261&seekm=3C8E54C4.7030506%40livinglogic.de#link1 print to stream to multiple objects: http://groups.google.com/groups?hl=en&ie=ISO-8859-1&oe=ISO-8859-1&threadm=mailman.1015962446.10330.python-list%40python.org&prev=/groups%3Fnum%3D25%26hl%3Den%26ie%3DISO-8859-1%26oe%3DISO-8859-1%26group%3Dcomp.lang.python%26start%3D175 Text Indexing and compression discussion http://groups.google.com/groups?hl=en&ie=ISO-8859-1&oe=ISO-8859-1&threadm=mailman.1015976905.21484.python-list%40python.org&prev=/groups%3Fnum%3D25%26hl%3Den%26ie%3DISO-8859-1%26oe%3DISO-8859-1%26group%3Dcomp.lang.python%26start%3D150 A thread on an English thesaurus and dictionary for python is particularly cool. http://groups.google.com/groups?th=3c477063910da12e Vinay Sajip proposes a standard logging module for Python. http://www.red-dove.com/python_logging.html http://python.sourceforge.net/peps/pep-0282.html The secret labs releases Python Imaging Library, v1.1.3. "Version 1.1.3 adds distutils build scripts, improved resampling, screen grabbing support (windows only), and more." http://www.pythonware.com/products/pil/ Lars Gust?bel's tarfile module provides a zipfile-like interface for reading and writing TAR files. http://www.gustaebel.de/lars/tarfile/ David Mertz posts an early draft of his book in progress, Text Processing in Python. http://gnosis.cx/TPiP/ PythonCard 0.6.4 "includes walkthroughs to get you started with PythonCard, an improved layout editor..., and new samples that use SOAP and XML-RPC (Blogger API)." http://pythoncard.sourceforge.net/ Mike C. Fletcher calculates sunrise and sunset times. http://members.rogers.com/mcfletch/programming/sunriseset.py Yet another conversation on Embedding Python in Server Side Web Development, this one someone without early mention of Zope *or* the recent ASP articles. http://groups.google.com/groups?hl=en&ie=ISO-8859-1&oe=ISO-8859-1&threadm=23891c90.0203130444.3d8a1a3b%40posting.google.com&prev=/groups%3Fnum%3D25%26hl%3Den%26ie%3DISO-8859-1%26oe%3DISO-8859-1%26group%3Dcomp.lang.python%26start%3D150 Grant Edwards' question on packaging ends with an inspiring testimonial. http://groups.google.com/groups?hl=en&ie=ISO-8859-1&oe=ISO-8859-1&frame=right&th=16b685ee49ea98f2&seekm=slrna8qr56.16e.grante%40tuxtop.visi.com#link19 ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning, ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From tim.one at comcast.net Mon Mar 11 15:51:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 11 Mar 2002 15:51:10 -0500 Subject: PEP 284, Integer for-loops (fwd) In-Reply-To: Message-ID: [James_Althoff at i2.com] > ... > But if your protocol is > def getRowCount(): pass > def getColumnCount(): pass > def getValueAt(rowIndex,columnIndex): pass > def setValueAt(rowIndex,columnIndex): pass > then that option is not available. Hmm. The inability to pass a new value to setValueAt seems to make this a little feeble . Depending on how much overhead you're willing to bear, it's straightfoward to write wrapper classes (even using the old for/__getitem__ protocol) such that, e.g., adding 1 to every element in a table could be expressed via t = Table(original_table) for r in t.rows(): for e in r.elements(): e.set(e.get() + 1) Short of that, you could at least reduce the clumsiness by defining helper functions, like (assuming these are 0-based indices; fiddle to taste): def ri(table): "Return row indices for table." return range(table.getRowCount()) def ci(table): "Return column indices for table." return range(table.getColumnCount()) and then columns = ci(table) for i in ri(table): for j in columns: table.setValueAt(i, j, table.getValueAt(i, j) + 1) would save some typing yet be just as quick. Add def getter(table): "Return bound table.GetValueAt." return table.GetValueAt def setter(table): "Return bound table.SetValueAt." return table.SetValueAt and then get, set = getter(table), setter(table) columns = ci(table) for i in ri(table): for j in columns: set(i, j, get(i, j) + 1) would be about as fast as you can get in Python, short of defining a custom "add 1 to element and then store it back" function. If you're very concerned about speed, when you've got a choice the loop with the largest trip count should be innermost (as true in Python as in any other language, although this is clawing at what are usually third-order effects). From robin at jessikat.fsnet.co.uk Fri Mar 1 05:40:45 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 10:40:45 +0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> Message-ID: OK to be more precise I'm executing like this Python 2.1.2 (#31, Jan 15 2002, 17:28:11) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import os >>> import sys ... >>> cmd '"C:\\Program Files\\ReportLab\\Demo\\rml2pdf.exe" "C:\\Program Files\\ReportLab\\Demo\\rlextra\\pageCatcher\\PageCatchI ntro.rml" --outdir="C:\\Program Files\\ReportLab\\Demo\\Doc"' >>> i, o = os.popen4(cmd,'t') >>> t = o.read() >>> print t 'C:\Program' is not recognized as an internal or external command, operable program or batch file. >>> I can run the command directly C:\Program Files\ReportLab\Demo>"C:\\Program Files\\ReportLab\\Demo\\rml2pdf.exe" "C:\\Program Files\\ReportLab\\Demo\\r lextra\\pageCatcher\\PageCatchIntro.rml" --outdir="C:\\Program Files\\ReportLab\\Demo\\Doc" C:\Program Files\ReportLab\Demo> so somewhere something odd is happening. This is win2k. -- Robin Becker From ponderor at lycos.com Mon Mar 4 15:03:02 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 4 Mar 2002 12:03:02 -0800 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> Message-ID: > I wonder how much interest there would be in a revival? > > Dinu YES! I've found Python to be an excellent learning environment for personal development in software engineering and computer science. Especially since the advent of href="http://www.mindview.net/Books/TIPython" Bruce Eckel's _Thinking in Python_ and http://vig.pearsoned.com/store/product/0,,store-562_banner-0_isbn-0130409561,00.html" Thomas Christopher's _Python Programming Patterns_ Best Regards, Dean From kragen at pobox.com Wed Mar 20 03:49:36 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 20 Mar 2002 03:49:36 -0500 Subject: Need feedback - What are the elements of a good hosting service? References: Message-ID: <83lmcnhbdr.fsf@panacea.canonical.org> Skip Montanaro writes: > * Though their Acceptable Use Policy said they'd consider long-running > programs on a case-by-case basis, That's kind of a danger sign, isn't it? > * My almost idle webserver was getting lots of clear breakin attempts - > accesses to paths like /scripts/..%255c../winnt/system32/cmd.exe. That's Nimda. > I reported this to them and suggested it would be not much > more difficult for them to block and report such malicious > accesses for their entire suite of servers than for me to > block on an IP-by-IP basis. With what? You think they might have a ServerIron or a LocalDirector in a back closet, not being used? > After several go-rounds I finally got a note from one of their > sysadmins indicating they would block on the machine my > virtual server resides on. No word on actually reporting the > bad guys. You want them to report instances of Nimda infection? They're going to be awfully busy. > How do other peoples' experiences jive with mine? What do you feel it > important to ask going into the process over and above what I've referred to > as the "primary questions"? Do you agree that those that seem important to > me are actually of general importance? The questions that seem important to you are of general importance. They are the reasons I do not host web sites where I do not have root or personally know someone who does. From peter at engcorp.com Mon Mar 25 19:26:59 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 19:26:59 -0500 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3C9E53D8.4FA20F3D@engcorp.com> <3C9E7326.C3FD53DF@engcorp.com> Message-ID: <3C9FC053.29071985@engcorp.com> holger at trillke.net wrote: > > The Agent "servers" don't do much on themselves > but instead leave it to agents to provide "framework" and protocol > capabilities. So to decouple the agents i would probably > introduce a "RelationShip"-Agent managing couplings between > them. Exactly the approach I would take. Make the environment (I use that term to mean the surroundings for the agent) act as a proxy to any other agents that one agent wants to talk to, thus ensuring all agents run isolated from the others and, coincidentally, forcing them to call through your environment when necessary, thus giving you the ability to intercept those calls and even terminate the agent by raising an exception (provided they don't blindly ignore such exceptions). Phew... sorry for the run-on sentence... > > a low-performance hack until you have time to implement the > > modification in the interpreter :-), which would be to > > stick a flag check into a routine inserted with sys.settrace(). > > interesting suggestion! Doesn't this cause a lot of overhead unless > done in C? Oh very likely! I did say it was "low-performance". Just a thought that might give you some ideas. -Peter From mmiller3 at iupui.edu Wed Mar 13 17:17:08 2002 From: mmiller3 at iupui.edu (Michael A. Miller) Date: 13 Mar 2002 17:17:08 -0500 Subject: python and analyze image format? References: Message-ID: <87n0xcgljv.fsf@lumen.indyrad.iupui.edu> >>>>> "Steven" == Steven Majewski writes: > Are you referring to the Mayo Foundation's "Analyze" ? That's the one. From alien275 at libertysurf.fr Fri Mar 1 12:21:13 2002 From: alien275 at libertysurf.fr (Riss Nicolas) Date: Fri, 1 Mar 2002 18:21:13 +0100 Subject: Ping Message-ID: Bonjour, on ma dit que je pouvais ?crire en francais alors j'?crit en francais. Je voudrais pouvoir v?rifier toutes les 5 min que une machine ping une autre machine et si elle ne ping pas qu'elle execute un script. Comment faut il faire avec python pour pinger une machine et v?rifier qu'elle r?pond?? Merci de votre aide. From dwelch91 at attbi.com Fri Mar 8 23:31:10 2002 From: dwelch91 at attbi.com (djw) Date: Sat, 09 Mar 2002 04:31:10 GMT Subject: Python and computer graphics References: <3C8785EA.5010509@student.kun.nl> Message-ID: www.vpython.org maybe? D "husam" wrote in message news:3C8785EA.5010509 at student.kun.nl... > hi, > can anybody points me to usefull resources (books, urls) about using > python for computer graphics that help for building skills in this > subject from scrash? > > thanks in advance > From erik.wilsher at iname.com Wed Mar 13 02:54:18 2002 From: erik.wilsher at iname.com (erik_w) Date: 12 Mar 2002 23:54:18 -0800 Subject: python -c cmd bug? Message-ID: When I do >python -c "import sys;print sys.argv" ['-c'] (Python 2.1.2 on NT4) Is this the right behaviour? I would expect that the -c was an option to the python interpreter, not to my script. If I do >python -O -c "import sys;print sys.argv" ['-c'] the -O switch is not reflected in sys.argv BR EW From MaximilianScherr at t-online.de Mon Mar 4 12:39:56 2002 From: MaximilianScherr at t-online.de (Maximilian Scherr) Date: Mon, 4 Mar 2002 18:39:56 +0100 Subject: server problems (long post) References: <20020228141109.1fe13f7c.logiplexsoftware@earthlink.net> Message-ID: <000901c1c3a3$999a5b00$0a00a8c0@maximilian1> Hello, I'm sorry, that i post this here, but i really have no clue why it doesn't work, how it could work... so i post my code on the list, and cry for help:) So if anyone can tell me to get this server(engine) to work I would be very happy. Here's the hex string the server receives(it's originaly in binary): fe01025301020304000000004d61780000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000005741303100000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000303636360000000000000000 00000000000000000000000000000000000000000000000000fe6400090300000000fe640009 0300000001fe6400090300000002fe6400090300000003fe6400090300000004fe6400090300 000005fe6400090300000006fe6400090300000007fe6400090300000008fe64000903000000 09fe640009030000000afe640009030000000bfe640009030000000cfe640009030000000dfe 640009030000000efe640009030000000ffe6400090300000010fe6400090300000011fe6400 090300000012fe6400090300000013fe6400090300000014fe6400090300000015fe64000903 00000016fe6400090300000017fe6400090300000018fe6400090300000019fe640009030000 001afe640009030000001bfe640009030000001cfe640009030000001dfe640009030000001e fe640009030000001ffe6400090300000020fe6400090300000021fe6400090300000022fe64 00090300000023fe6400090300000024fe6400090300000025fe6400090300000026fe640009 0300000027fe6400090300000028fe6400090300000029fe640009030000002afe6400090300 00002bfe640009030000002cfe640009030000002dfe640009030000002efe6400090300 Here's my code: import os.path import os import threading import SocketServer import binascii import string class Program: def Start(self): ucisfile = os.path.isfile('uoslserver.cfg') pcinfohandler = PCInfoHandler() pcinfohandler.CheckFile() ohandler = OHandler() ohandler.CheckFile() if ucisfile == 0: ohandler.WriteO('Couldn\'t find uoslserver.cfg!') elif ucisfile == 1: readuc = open('uoslserver.cfg') try: address = eval(readuc.readline()) try: ohandler.WriteO('Starting up...') ihandler = IHandler() serverthread = Server(address) serverthread.setName('serverthread') ihandlerthread = threading.Thread(None, ihandler.ReadI) ihandlerthread.start() serverthread.start() ohandler.WriteO('...finished!') except: ohandler.WriteO('...aborted!') except: ohandler.WriteO('Couldn\'t read uoslserver.cfg') class OHandler: def CheckFile(self): ulisfile = os.path.isfile('uoslserver.log') if ulisfile == 0: writeul = open('uoslserver.log', 'w') writeul.close() elif ulisfile == 1: os.remove('uoslserver.log') writeul = open('uoslserver.log', 'w') writeul.close() def WriteO(self, string): writeul = open('uoslserver.log', 'a') print string writeul.write(string +'\n') writeul.close() class Server(threading.Thread): def __init__(self, address): self.address = address self.serverstate = 1 threading.Thread.__init__(self, None, self.Start) def Start(self): server = SocketServer.ThreadingTCPServer(self.address, RequestHandler) while self.serverstate == 1: server.handle_request() def ShutDown(self): pcinfohandler = PCInfoHandler() pcinfohandler.SetInfoAll() functionhandler = FunctionHandler() for op in functionhandler.ListOnlinePlayers(): op.Close() self.serverstate = 0 class RequestHandler(SocketServer.StreamRequestHandler): def handle(self): clienthandlerthread = ClientHandler(self.request) clienthandlerthread.start() class ClientHandler(threading.Thread): def __init__(self, sockobj): self.sockobj = sockobj threading.Thread.__init__(self, None, self.Recv) def Recv(self): datahandler = DataHandler() while self.sockobj: data = self.sockobj.recv(1024) returnvalue = datahandler.Start(data, self.sockobj) if returnvalue != 0: self.setName(returnvalue[0]) self.pcname = returnvalue[1] self.pcpass = returnvalue[2] self.pcx = returnvalue[3] self.pcy = returnvalue[4] self.pcz = returnvalue[5] self.pcdir = returnvalue[6] pcinfohandler = PCInfoHandler() pcinfohandler.SetInfoSingle(self.getName(), self.pcname, self.pcpass, self.pcx, self.pcy, self.pcz, self.pcdir) ohandler = OHandler() ohandler.WriteO(self.pcname +' logged off!') def Close(self): self.sockobj.close() pcinfohandler.SetInfoSingle(self.getName(), self.pcname, self.pcpass, self.pcx, self.pcy, self.pcz, self.pcdir) ohandler = OHandler() ohandler.WriteO(self.pcname +' logged off!') class DataHandler: def Start(self, data, sockobj): converteddata = binascii.b2a_hex(data) if converteddata[:4] == 'fe01': pcserial = converteddata[8:16] pcname = string.replace(converteddata[24:340], '00', '') pcname = chr(int(pcname, 16)) pcpass = string.replace(converteddata[1116:1190], '00', '') pcpass = chr(int(pcpass, 16)) pcinfohandler = PCInfoHandler() returnvalue = pcinfohandler.GetInfo(pcserial) functionhandler = FunctionHandler() ohandler = OHandler() if returnvalue != 0: if functionhandler.CheckPass(pcserial, pcpass) == 0: sockobj.close() return 0 elif functionhandler.CheckPass(pcserial, pcpass) == 1: ohandler.WriteO(pcname +' logged on from client address '+ sockobj.getsockname()) return returnvalue elif returnvalue == 0: if functionhandler.CheckPass(pcserial, pcpass) == 0: sockobj.close() return 0 elif functionhandler.CheckPass(pcserial, pcpass) == 1: ohandler.WriteO(pcname +' logged on from client address '+ sockobj.getsockname()) return [pcserial, pcname, pcpass, 554, 576, 0, 0] else: return 0 class FunctionHandler: def CheckPass(self, pcserial, pcpass): pcinfohandler = PCInfoHandler() returnvalue = pcinfohandler.GetInfo(pcserial) threadhandler = ThreadHandler() if returnvalue != 0: for pcinfo in returnvalue: for op in self.ListOnlinePlayers(): if op.pcpass != pcpass or pcinfo[2] != pcpass: return 0 elif pcinfo[2] == pcpass: return 1 elif returnvalue == 0 and threadhandler.GetThreadObj(pcserial) != 0: return 0 elif returnvalue == 0 and threadhandler.GetThreadObj(pcserial) == 0: return 1 def ListOnlinePlayers(self): oplist = [] for threadobj in threading.enumerate(): if threadobj.getName() != 'server': oplist.append(threadobj) return oplist class PCInfoHandler: def CheckFile(self): pdisfile = os.path.isfile(os.getcwd() + '\\data\\pc.dat') if pdisfile == 0: writepd = open(os.getcwd() + '\\data\\pc.dat', 'w') writepd.write('[]') writepd.close() def GetInfo(self, pcserial): readpd = open(os.getcwd() + '\\data\\pc.dat', 'r') pcinfolist = readpd.readline() readpd.close() try: pcinfolist = eval(pcinfolist) for pcinfo in pcinfolist: if pcinfo[0] != pcserial: return 0 elif pcinfo[0] == pcserial: return pcinfo except: ohandler = OHandler() ohandler.WriteO('Couldn\'t read pc.dat') def SetInfoSingle(self, pcserial, pcname, pcpass, pcx, pcy, pcz, pcdir): readpd = open(os.getcwd() + '\\data\\pc.dat', 'r') pcinfolist = readpd.readline() readpd.close() try: pcinfolist = eval(pcinfolist) for pcinfo in pcinfolist: if pcinfo[0] != pcserial: pcinfolist.append[[pcserial, pcname, pcpass, pcx, pcy, pcz, pcdir]] elif pcinfo[0] == pcserial: pcinfolist.remove(pcinfo) pcinfolist.append[[pcserial, pcname, pcpass, pcx, pcy, pcz, pcdir]] except: ohandler = OHandler() ohandler.WriteO('Couldn\'t read pc.dat') writepd = open(os.getcwd() + '\\data\\pc.dat', 'w') writepd.write(str(pcinfolist)) writepd.close() def SetInfoAll(self): readpd = open(os.getcwd() + '\\data\\pc.dat', 'r') pcinfolist = readpd.readline() readpd.close() try: pcinfolist = eval(pcinfolist) for pcinfo in pcinfolist: functionhandler = FunctionHandler() for op in functionhandler.ListOnlinePlayers(): if op.getName() == pcinfo[0]: pcinfolist.remove(pcinfo) pcinfolist.append[[op.getName(), op.pcname, op.pcpass, op.pcx, op.pcy, op.pcz, op.pcdir]] except: ohandler = OHandler() ohandler.WriteO('Couldn\'t read pc.dat') writepd = open(os.getcwd() + '\\data\\pc.dat', 'w') writepd.write(str(pcinfolist)) writepd.close() class ThreadHandler: def GetThreadObj(self, threadname): for threadobj in threading.enumerate(): if threadobj.getName() == threadname: return threadobj else: ohandler = OHandler() ohandler.WriteO('Couldn\'t find thread with name \''+ threadname +'\'!') return 0 class IHandler: def ReadI(self): ihandlerstate = 1 ohandler = OHandler() while ihandlerstate == 1: input = raw_input() if input == 'c': ohandler.WriteO('Input: '+ input) ohandler.WriteO('Valid commands:') ohandler.WriteO('c -- show this list') ohandler.WriteO('s -- shut down') elif input == 's': ohandler.WriteO('Input: '+ input) ohandler.WriteO('Shutting down...') ihandlerstate = 0 threadhandler = ThreadHandler() serverthread = threadhandler.GetThreadObj('serverthread') serverthread.ShutDown() ohandler.WriteO('...finished!') program = Program() program.Start() Thanks in advance, Max From pearu at cens.ioc.ee Fri Mar 15 10:28:48 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Fri, 15 Mar 2002 17:28:48 +0200 Subject: Which class method will be used when calling it? Message-ID: Hi, Let's define classes class A: def f(self): pass # define default method f class B(A): def f(self): pass # define specific method f class B1(B): pass # specific B.f is available class C(A): pass # no specific method f, default is available and instances: a = A() b = B() b1 = B1() c = C() Given one of these instances, how to tell which method will be called, the default f or a specific f, if calling .f()? To make my question clearer, I need the following codelet if : pass else: x.f() So that if x=b or x=b1, then its method f is called. But if x=a or x=c, then the pass statement is executed. A special solution would be = hasattr(x.__class__,'f') but it only works if certain conditions are satisfied (x.__class__ is directly derived from A). It obviously fails in the b1 case. Are there less restrictive solutions available under Python 2.2? Thanks, Pearu From akuchlin at ute.mems-exchange.org Thu Mar 21 12:49:22 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 21 Mar 2002 17:49:22 GMT Subject: FastCGI References: Message-ID: In article , Johannes Stiehler wrote: > Is there anybody out there who uses python together with fastcgi for > realizing large scale applications. And if so, which FastCGI-Wrapper > is the most recommendable? We haven't had any problems with fcgi.py. The copy of fcgi.py hiding inside Quixote has had a few minor bugfixes and some minor optimization (using the struct module for packing and unpacking data, for example). mod_fastcgi, on the other hand, seems to be subject to occasional random hangs that occurred once every few weeks. --amk (www.amk.ca) Is this thing reliable? -- Grace, asking about the TARDIS, in "The Enemy Within" From James_Althoff at i2.com Tue Mar 5 17:54:52 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 14:54:52 -0800 Subject: Status of PEP's? Message-ID: [David Eppstein] >[James_Althoff] > > > And note again also, that (the equivalent of) > > > > def __contains__(self,x): > > raise TypeError > > > > could be added to class int if the anguish proved to be > > insurmountable <0.1 wink>. > > That would cause me much more anguish than even PEP 276 in > its present form. Right. So we have a clear choice between "anguish" and "much more anguish"; I will note that in the PEP (sorry Tim D. ;-). > I really like the fact that "for ...stuff..." loops over exactly those > values for which "...stuff..." is true. I know you do. And I can appreciate that. > I don't want to see that broken. Jim From op73418 at mail.telepac.pt Wed Mar 13 13:31:07 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 13 Mar 2002 18:31:07 +0000 Subject: Why I think range is a wart. References: Message-ID: On 13 Mar 2002 12:53:50 -0500, com-nospam at ccraig.org (Christopher A. Craig) wrote: >Gon?alo Rodrigues writes: > >> For starters, range (and xrange) is a perfectly sensible, reasonable and >> useful built-in. But the biggest use I make of it is in iterating through >> a list, e.g. as in >> >> for index in range(len(mylist)): >> >> >> and in the body I need to make use of the indexes. I am not >> sufficiently qualified to say if this is Pythonic or not, but I find >> myself doing this quite often. > >I don't understand how range is a reasonable and useful built-in if >this use is not. There are other useful, reasonable and sensible uses for the range built-in. My comment is that this particular use looks warty to me because any sequence, especially if it obeys the "list-protocol" (that is, it has methods like __getitem__, __setitem__, etc.) should be able to generate the indexes (or keys) of its members. Just like a dictionary. > >If you have a list [2, 3, 5, 7, 11] and you want to iterate through it >you don't need range: > >for item in list: > > >If, on the other hand, you want to iterate though the indicies of said >list rather than the items themselves you need to come up with some >way to generate a zero based list of integers up to one less than the >size of the list (i.e. a list of indicies). When you create this list >you aren't doubling information that the list already has. A list >does not contain a list of indicies into itself. The list knows its >elements, in order, and how many elements it has. From this you can >generate a list of indicies, but there are no 'keys' stored in a list >object like there are in a dictionary. This is where I beg to disagree. If the elements are in order, as they are in a list, it is perfectly reasonable to ask, "you are a list, right? then hand me the indexes of your members." If the list has the keys in memory or not, that is an implementation issue. Prolly the best way to implement this is to add a single method (iteritems?) that gives an iterator through the indices. > >To go from the information that is stored in the list (an ordered list >of elements, and the size of said list) to the information you need to >iterate through indicies (an ordered sequence of indicies valid for the >given list) you need to take the length of the list (N), and create a >new list of N integers from 0 to N-1. 'range(len(mylist))' says >precisely that. I don't see how this is the least bit kludgey. > >.keys() and .items() methods on lists seem odd to me. That is >inforamtion that the list does not contain. Sure it can easily be >generated given information the list does contain, but why can't the >programmer generate it himself from the same information? Of course the programmer can do it for himself. But since the idiom expounded in my post seems to be prevalent it would be at least reasonable to make it a built-in. Best regards, Gon?alo Rodrigues From jamie.carl at salientnetworks.com.au Mon Mar 18 23:44:48 2002 From: jamie.carl at salientnetworks.com.au (Jamie Carl) Date: Tue, 19 Mar 2002 04:44:48 GMT Subject: Serial Ports Message-ID: <3c96c220$1_1@news.iprimus.com.au> Hi all, I'm still fairly new to Python so forgive me. I'm hoping someone can point in the right direction regarding how I would go about accessing a serial com port from Python. I'd like to do it mainly under Linux, but hopefully it will work under windows aswell. Is it possible? Can someone point me to some documentation or code samples? Thanks in advance. Jamie Carl From andy at reportlab.com Fri Mar 8 15:42:10 2002 From: andy at reportlab.com (Andy Robinson) Date: Fri, 08 Mar 2002 20:42:10 GMT Subject: Autodiscovery of proxy settings from a python script References: <7EHvmJAipQi8Ew$x@jessikat.demon.co.uk> Message-ID: "Robin Becker" wrote in message news:YFx3GIA6KRi8EwK8 at jessikat.demon.co.uk... > in fact inside urllib there seems to be some support built in for the > registry attack under nt. > > ie urllib.getproxies() is supposed to return a dictionary mapping > services to proxies urls. Doesn't on my machine though. > -- Mine neither. Does anyone get anything back from this on win32? I am hampered in my researcg by not actually being behind a corporate firewall for a change :-) - Andy From martinkaufmann at yahoo.com Tue Mar 12 17:16:15 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Wed, 13 Mar 2002 11:16:15 +1300 Subject: Question about scientific calculations in Python References: <3C8DFF7B.7EF0EAC6@kfunigraz.ac.at> Message-ID: <9dvs8u8aulpr2ceppipnakdk78e9bipneo@4ax.com> On Tue, 12 Mar 2002 14:15:39 +0100, Siegfried Gonzi wrote: >Projecting this experience to Python. I would assume (but without any >detailed study) that Python in combination with the numeric library >will serve you very well. But it depends whether you can use a >straightforward algorithm (like the FFT) or you must solve your own >integral. See my other post containing the code. There is no integral... >> Are there any libraries or other resources that would help? I used the >> Scientific Python library for the histogram but it was much slower >> than my DIY approach. > >How much slower? A performance penalty of 100 would be of great concern; >a factor of 5 should not mind you (but this is my personal view). Okay, >if you have to wait in C or C++ 1 hour then even a factor of 5 is >somewhat bothersome. Even a factor of 5 is not really nice if you have to run it for several hundred times... Regards, Martin From mmoore at cablespeed.com Wed Mar 6 12:34:57 2002 From: mmoore at cablespeed.com (Michele Moore) Date: Wed, 06 Mar 2002 12:34:57 -0500 Subject: Is there any wxPython turtor? References: Message-ID: <3C865341.8D190235@cablespeed.com> Ricky wrote: > I have downloaded wxPython 2.3. But, I found that the document come with it > is not well enough. Is there any recommended good tutor of wxPython itself?? > > BTW: I don't know why I can't connect to www.wxpython.org, is it still > alive? You might consider visiting: http://wiki.wxpython.org/index.cgi/How_20to_20Learn_20wxPython Most of the actual API documentation is written for the C++ implementation underneath, wxWindows, which is very thorough. Here's a good reference for a number of tutorials: http://www.wxwindows.org/docs2.htm BTW, I was able to go to http://www.wxpython.org just fine just now. Michele From dale at riverhall.NOTHANKS.co.uk Fri Mar 29 05:55:53 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Fri, 29 Mar 2002 10:55:53 +0000 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: Syver Enstad wrote: >Oh but it is, I have it on my machine. I just nicked some registry >stuff from the exe file key in HKEY_CLASSES_ROOT and py and pyw file >behave beautifully when dropped files on. > >Here's what you need: > > >REGEDIT4 > >[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] >@="{86C86720-42A0-1069-A2E8-08002B30309D}" > >[HKEY_CLASSES_ROOT\Python.NoConFile\shellex\DropHandler] >@="{86C86720-42A0-1069-A2E8-08002B30309D}" > Neat. Thanks for that. -- Dale Strickland-Clark Riverhall Systems Ltd From gerson.kurz at t-online.de Sat Mar 30 01:32:56 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sat, 30 Mar 2002 06:32:56 GMT Subject: decision tables Re: Another stab at a "switch/case" construct (new proposal): References: Message-ID: <3ca55b4a.6988843@news.t-online.de> On Sat, 30 Mar 2002 08:33:13 +0300 (MSK), Roman Suzi wrote: >However, I'd liked to see a good paradigm for expressing >decision tables like this one: > >F1 F2 F3 R >0 0 * do1 >0 1 0 do2 >0 1 1 do3 >1 * * do4 just an idea: subclass dict, implement pattern matching in the lookup func? derived_dict( (0,0,2) : do1, (0,1,0) : do2, (0,1,1) : do3, (1,2,2) : do4 ) with lookup d[F1,F2,F3](args) From nsbase at yahoo.co.uk Fri Mar 15 06:19:20 2002 From: nsbase at yahoo.co.uk (Noel Smith) Date: 15 Mar 2002 03:19:20 -0800 Subject: Windows NT shell + extended characters. Bug or what? Message-ID: <10095d00.0203150319.12f9cbf9@posting.google.com> I've been recently using the Python shell on Linux as a handy way to get character numbers from various extended LATIN-1 characters. i.e. For UK pound and Yen currency signs: >>> print ord('?') 163 >>> print ord('?') 165 Which are the correct values. However I've recently installed python 7.2 on Windows NT4 and found it gives the following results when using the command line shell: >>> print ord('?') 156 >>> print ord('?') 157 Which is clearly wrong although strangely enough when I type the same thing into IDLE on Windows NT, it produces the correct results. Is this a bug or is there some windows character mapping going on behind the scenes which I've missed out? Is there any configuration that I've missed out? Any help would be really appreciated. Noel Smith From ngps at madcap.netmemetic.com Fri Mar 8 09:58:54 2002 From: ngps at madcap.netmemetic.com (Ng Pheng Siong) Date: 8 Mar 2002 14:58:54 GMT Subject: [Announce] M2Crypto 0.07 snapshot #3 Message-ID: Hi, M2Crypto 0.07 snapshot #3 is now available. This snapshot sports a Distutils setup.py that uses bundled SWIG-generated files; this should make it easier to build and install M2Crypto. Also available are Win32 binaries for Pythons 2.2, 2.1 and 1.5.2. On the minus side, ZServerSSL does not work with Zope 2.5.0. I expect to release 0.07 once I fix this. As usual, M2Crypto is here: http://www.post1.com/home/ngps/m2/ Your feedback is welcome. -- Ng Pheng Siong * http://www.netmemetic.com From gerhard at bigfoot.de Wed Mar 20 08:19:35 2002 From: gerhard at bigfoot.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 20 Mar 2002 14:19:35 +0100 Subject: shared memory block References: <3C988A9F.51137D54@mathworks.fr> Message-ID: <3C988C67.2010008@bigfoot.de> Boris Huart wrote: > I am trying to allocate a shared memory block from a python script so > that a Java applet can access the data shared. This won't work. If it works at all, you'll have to use the C interface of both Python and Java. Using JNI in a Java applet, if at all possible, needs serious hacking of your Java and Browser environment. There sure is a very simple solution to your problem. Except we don't know what the problem actually is. So please try to describe it. Do you need to somehow communicate between a Python script and a Java applet? Then one of XML-RPC, SOAP, CORBA will do the trick. If you have complex data structures, AFAIK CORBA is best. Gerhard From thoa0025 at mail.usyd.edu.au Fri Mar 29 22:44:27 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sat, 30 Mar 2002 03:44:27 GMT Subject: execfile() - change python version? References: <3CA53165.E3A765A4@engcorp.com> Message-ID: running the following set of commands in a script: import xml.dom.minidom dom = xml.dom.minidom.parseString(somexmlstr) using the above in python2.1 from my account: WORKS using the above in python2.1 from the web: WORKS using the above in python2.2 from my account : WORKS using the above in python2.2 from the web : FAILS! so im forced to used 2.1 because of xml libraries #!/local/usr/bin/python as aposed to #!/local/usr/bin/python2.2 it probably does not work because of some environmental variable not being set, which when run from the web fails to find the SAX parser.. fast translation of tracedump: i execute xml.dom.minidom.parseString(xmlstr) and it fails to create the SAX reader in the xml.sax.__init__. i believe it is perhaps python can not find the required libraries in 2.2 but able to find them in 2.1. here is the raw tracedump: [('/usr/cs3/thoang/lib/html/q.cgi', 43, '?', 'execfile("handle-projects.py", namespace)'), ('handle-projects.py', 14, '?', "projects = mods['xmlagent'].getProjects()"), ('/usr/cs3/thoang/lib/html/xmlagent.py', 16, 'getProjects', 'dom = xml.dom.minidom.parseString(datamine)'), ('/usr/local/lib/python2.2/xml/dom/minidom.py', 965, 'parseString', 'return _doparse(pulldom.parseString, args, kwargs)'), ('/usr/local/lib/python2.2/xml/dom/minidom.py', 951, '_doparse', 'events = apply(func, args, kwargs)'), ('/usr/local/lib/python2.2/xml/dom/pulldom.py', 340, 'parseString', 'parser = xml.sax.make_parser()'), ('/usr/local/lib/python2.2/xml/sax/__init__.py', 93, 'make_parser', 'raise SAXReaderNotAvailable("No parsers found", None)')] what are your thoughts? "Peter Hansen" wrote in message news:3CA53165.E3A765A4 at engcorp.com... > Trung Hoang wrote: > > > > Hi, > > > > i was wondering if there is a way to change which version of python > > processing the file when execfile(). > > No. execfile() is basically "execute this file using the currently > running version of Python". > > > i wish to use python2.2 on the main file, and python2.1 on the file passed > > into the argument of execfile(). > > Don't use execfile(). Use os.system() and run the version you want instead. > > > reason being: there is some sort of mis configuration error on the server i > > am using python on. > > Sounds like there must be an easier way to solve the problem. Can > you give more detail on this "misconfiguration error"? From Moo at houston.rr.com Wed Mar 6 16:07:18 2002 From: Moo at houston.rr.com (Avi Homes) Date: Wed, 06 Mar 2002 21:07:18 GMT Subject: Dictionaries in Lists Message-ID: I was attempting to make a list of dictionaries, which to me feels like the C equivlant of an array of structs, kind of. anyway, after making a dictionary and putting some values into it, and trying to append it to a list, python is not liking this. Am I approaching the idea the wrong way? i would like to keep the data organized as dictionaries.. the code looked something like Info{'IName':"Voodoo2",'IDescription':"blahblah} Listing=[] Listing.append(Info) From bass at slinkp.com Fri Mar 8 18:06:49 2002 From: bass at slinkp.com (Paul Winkler) Date: 8 Mar 2002 15:06:49 -0800 Subject: [OT] range() for unix shell References: <2adab837.0203071409.76588265@posting.google.com> <2adab837.0203071734.1a3bee80@posting.google.com> <5e8bd451.0203080308.6665d155@posting.google.com> Message-ID: <2adab837.0203081506.fd13680@posting.google.com> kp87 at lycos.com (kevin parks) wrote in message news:<5e8bd451.0203080308.6665d155 at posting.google.com>... > Paul (see you on Csound from time to time!) > > see the useless python page: > > > http://www.lowerstandard.com/python/uselesspython2.html That's cute. The formatting string is a really good idea. I haven't been on the csound list in a long time now... anything interesting going on there? --PW From d95-bli.no at spam.nada.kth.se Fri Mar 8 05:59:57 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-1?Q?Bj=F6rn?= Lindberg) Date: Fri, 08 Mar 2002 11:59:57 +0100 Subject: Order of constructor/destructor invocation References: Message-ID: <3C8899AD.78B134DE@spam.nada.kth.se> Christian Tanzer wrote: > Agreed. I relied on that. > > > In this example s1 will be constructed first followed by s2. > > And here I am wary. Does the standard prescribe this? For normal > expressions at least, you can't rely on evaluation order. But then, in > comma separated expressions you can. So maybe this is safe after all. I believe it is, but I'm not certain. As you say, evaluation order for comma separated expressions are defined. I'd have to ask someone with a copy of the standard handy for this. Anyway, what I AM certain of is that the destruction order is opposite of the construction order. Bj?rn From tejarex at yahoo.com Fri Mar 29 18:00:12 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 29 Mar 2002 23:00:12 GMT Subject: List problem References: Message-ID: <%l6p8.157527$2q2.12783856@bin4.nnrp.aus1.giganews.com> "Bjorn Pettersen" wrote in message news:mailman.1017438528.28926.python-list at python.org... [snip] > > # Word dictionary > dict = "c:\data\dict.txt" Try either r"c:\data\dict.txt" or "c:\\data\\dict.txt". or "c:/data/dict.txt" , which is both clear and safe. However, I believe \d == d. In any case, he had 4000+ words of the proper length so this does not seem to be the problem. Terry J. Reedy From gh_pythonlist at gmx.de Wed Mar 13 05:49:21 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 13 Mar 2002 11:49:21 +0100 Subject: dictonary In-Reply-To: <3C8F27DC.F69B1F54@stud.cs.uit.no> References: <3C8F27DC.F69B1F54@stud.cs.uit.no> Message-ID: <20020313104920.GA1656@lilith.hqd-internal> Le 13/03/02 ? 11:20, Daniel Nyg?rd ?crivit: > How do I insert a dictionary into a database (_mysql)? Don't use _mysql. Use MySQLdb instead. > db = _mysql.connect() > string = { > hello:'wow', > something:'nothing', > nothing : 'something', > number : 5, > name : 'daniel'} > > then I have a database with the same attributes as the keys in the dict. > above. > How do I insert the whole dict into the database. This is one way to do it, I bet there's a better one: dict = {'name': 'Andy', 'age': 39} columns = ",".join(dict.keys()) # I hope using only %s works for MySQLdb. It does work like this for pyPgSQL. placeholders = ",".join(['%(' + k + ')s' for k in dict.keys()]) sql = "insert into table(" + columns + ") values (" + placeholders + ")" # This should do the proper parameter quoting: cursor.execute(sql, dict) The author of MySQLdb has a module called SQLDict on his homepage (just google for it). Maybe you'll find it useful. Cheers, Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 16.0 ?C Wind: 1.7 m/s From wurmy at earthlink.net Sun Mar 24 12:30:02 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Sun, 24 Mar 2002 17:30:02 GMT Subject: MS Sql Server References: <788n8.60257$bj1.19179906@news02.optonline.net> Message-ID: <3C9E0D99.F8336C50@earthlink.net> Chase wrote: > > Hi... > > Wondering what the most accepted practice is, for communicating to Sql > Server Databases. Is it the ODBC module ? mxODBC ? Is there an ADO module ? > > Any hints/help appreciated. Besides the more obvious solutions, SQL Server 2000 also has a thing called SQLXML, allowing you to talk to a database through HTTP, using specialized URLs or XML. Pro: No drivers necessary. You can write a nice, portable, pure-Python interface. Access database from anywhere. Con: It's as fast as your HTTP connection (although that may not be much of a problem if you're running your database local or on a LAN). And, AFAIK, there's no generic SQLXML module (or package) for Python yet. (Although I might be allowed to publish some of code I've written for my current project...) -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From Oschler at earthlink.net Tue Mar 5 10:08:41 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 5 Mar 2002 10:08:41 -0500 Subject: (OT) Way to search HTML help? Message-ID: This is a bit off-topic, but does anyone know how to search the HTML help that comes with PythonWin? It has a link to the HTML help Python files, but I can't figure out how to do a text search on the HTML help like you can with WinHelp help files (something that would crawl the interdocument HTML links). This all came about when I was trying to find info on Python's getFrame() method which I couldn't find in the "Python Essential Reference" book. Thanks. From mwh at python.net Wed Mar 13 13:16:11 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 13 Mar 2002 18:16:11 GMT Subject: trackers (was: zlib vulnerabilities and python) References: Message-ID: Trent Mick writes: > [Michael Hudson wrote] > > Time to look at roundup again? The tracker on sf is starting to piss > > me off (even more). > > If you *are* going to get motivated to look at a different tracker *please* > consider bugzilla. You will find it a much more appropriate than roundup. Perhaps. I'm a bit scared of bugzilla (on the admin side). OTOH, the support request I submitted to sf has been bumped to priority 9, so perhaps this is all premature. > p.s. I am gonna regret feeding this. Huh? Cheers, M. -- If Unicode is a horde of zombies with flaming dung sticks, the hideous intricacies of JIS, Chinese Big-5, Chinese Traditional, KOI-8, et cetera are at least an army of ogres with salt and flensing knives. -- Eric S. Raymond, python-dev From robin at jessikat.fsnet.co.uk Sun Mar 24 18:23:14 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 24 Mar 2002 23:23:14 +0000 Subject: 2.2 open References: <1UtsCLAcngn8EwWc@jessikat.fsnet.co.uk> Message-ID: In article , Just van Rossum writes ..... >(Also note that open is now an alias for the new "file" builtin, which >considering how things now work is the more logical name. The builtin >functions int, float and str (among others) are olso type objects these >days.) > >Just yes, but presumably abs is not the same as type(abs(1.2)) so this only applies to certain factories rather than all functions. So the question now is, how do I tell if __import__ is the built in one even if the import system is not fully initialized. -- Robin Becker From db3l at fitlinxx.com Wed Mar 27 17:16:04 2002 From: db3l at fitlinxx.com (David Bolen) Date: 27 Mar 2002 17:16:04 -0500 Subject: thread-safe swap References: <833cyl3gfe.fsf_-_@panacea.canonical.org> Message-ID: Kragen Sitaker writes: > Someone recommended using the idiom > > spam, eggs = eggs, spam > > to get a thread-safe swap. Does this really work? (...) > So if this thread loses control anywhere between the first LOAD_FAST > and the last STORE_FAST, a value could get stored by another thread > into "b" which would then be lost. There isn't anything keeping this > from happening, is there? Nope. In general not even a simple assignment is necessarily thread safe since performing the assignment may invoke special methods on an object which themselves may require a number of operations. Hopefully the object will have internally locked its "state" values, but that's not always the case. But it's really dictated by what "thread safety" means in a particular application, because to my mind there are many levels of granularity of such safety so it's hard to talk about "thread safety". About the only thing the Python interpreter is going to give you for free is that a built-in data type should be safe from internal corruption even with native threading. In other words if two threads have "a=0xff" and "a=0xff00", a will end up with one or the other, but not accidentally "0xffff" as might be possible in some other languages if a isn't protected. With that said, Python also tends to execute in such a fashion that you can get away with an awful lot without formal locking, if you're willing to live on the edge a bit and have implied dependencies on the actual objects in use. There was a decent discussion along those lines here in c.l.p a while back - search groups.google.com for the "Critical sections and mutexes" thread among others. Personally, I explicitly lock shared state (or use constructs designed for exchanging shared information properly amongst threads, such as Queue.Queue) in any multi-threaded application. To my mind it's the best protection against maintenance and evolution down the road. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From martin at v.loewis.de Thu Mar 7 02:59:38 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 07 Mar 2002 08:59:38 +0100 Subject: hash(unicode(string)) == hash(string) sometimes (was Re: Why KeyError ???) References: <7dee885c.0203051843.36efa5c2@posting.google.com> <7xvgcabcti.fsf@ruckus.brouhaha.com> Message-ID: sjmachin at lexicon.net (John Machin) writes: > If the "fix" for this would involve making hash(string) always do > hash(unicode(string)) then I sure hope that (borrowing timbot > phraseology) somebody optimises the snot out of it. The real solution, IMO, is to never change the system default encoding. Then auto-conversion will only apply to ASCII strings, and dictionary lookup will either succeed properly, or fail with a UnicodeError - which will indicate a bug in the program, as it would need to explicitly apply a non-default encoding. Regards, Martin From jason at jorendorff.com Mon Mar 4 23:52:45 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 4 Mar 2002 22:52:45 -0600 Subject: OT - file permission checks on Windows In-Reply-To: <15491.48228.515787.419778@beluga.mojam.com> Message-ID: Skip Montanaro wrote: > Given this simple file access permission code: [...] > how would I do this under Windows? The following is not a joke. Any Windows programmer would just "return 1". It's not in the Windows application development culture to care about file permissions. Besides, 98% of the time this is the right answer on Windows. Why write a bunch of messy Win32 API calls code going after the other 2%? I think the typical thing is to just go ahead and try to use the file. If something goes wrong, pop up a message box with a none-too-friendly error message. ("Error - An error has occurred." is about par for the course.) Note that even on Unix, the code you quoted isn't perfect. Users can belong to multiple groups these days. ## Jason Orendorff http://www.jorendorff.com/ From dswegen at software.plasmon.com Thu Mar 21 03:53:07 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Thu, 21 Mar 2002 08:53:07 +0000 Subject: #define equivalents and config files In-Reply-To: <3C9964FF.46805590@engcorp.com> References: <3C9963BD.1040304@verizon.net> <3C9964FF.46805590@engcorp.com> Message-ID: <20020321085307.GB10214@software.plasmon> On Wed, Mar 20, 2002 at 11:43:43PM -0500, Peter Hansen wrote: > Rich Salz wrote: > > > > > Is there a pythonic way of doing something similiar to Cs #define? > > >... are globals the only way to go? > > > > You can at least make them class attributes > > class constants: > > pi = 3.14159 > > e = 2.71828 > > adding your own setattr can serve to make them read-only. > > That wouldn't help when one needed to change the values... I'm basically after a single file where such values can be stored, and then used in various parts of the program without having to pass extra configuation variables around. Cheers Dave From arthur.siegel at rsmi.com Sat Mar 16 18:49:22 2002 From: arthur.siegel at rsmi.com (arthur.siegel at rsmi.com) Date: Sat, 16 Mar 2002 18:49:22 -0500 Subject: return type question - operator oveloading Message-ID: Given: class Complex(complex): def __mul__(self,other): other=Complex(other) t = complex.__mul__(self,other) return Complex(t.real,t.imag) __rmul__ = __mul__ def __add__(self,other): other=Complex(other) return Complex(self.real.__add__(other.real),self.imag.__add__(other.imag)) __radd__ = __add__ Then: print type(Complex(5,4) * 7) >> print type(7 * Complex(5,4)) >> print type(Complex(5,4) + 7) >> But: print type(7 + Complex(5,4)) >> Multiple choice: That the result at But is a surprise to me because I am missing: 1)Something obvious about __radd__ or general classic syntax 2)Something related to new style classes 3)Other Art From tim.one at comcast.net Fri Mar 29 19:22:45 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 29 Mar 2002 19:22:45 -0500 Subject: string copying In-Reply-To: <3CA4F5CB.E8961330@engcorp.com> Message-ID: [Peter Hansen] > The only one I've been able to think of is the surprisingly > common situation of trying to consume vast quantities of memory > quickly by something like: > > a = [0] * 1000000 > for i in xrange(1000000): > a[i] = 'bigstringsuckinguplotsofmemory' Hmm. A much easier way to consume vast quantities of memory quickly is to skip the for-loop and just increase the multiplier on the first line. If you're on a 32-bit machine, and want to consume N bytes, use N/4 as the multiplier. From rloisel at helicon.net Wed Mar 20 08:45:28 2002 From: rloisel at helicon.net (Rodney Loisel) Date: Wed, 20 Mar 2002 08:45:28 -0500 Subject: error:"_imaging C module is not installed" Message-ID: <3C989278.9189857C@helicon.net> Just upgraded from PY 1.5.2 to 2.2.1c1 and TCL 8.3 Also installed PIL (Python Imaging Library) All paths seem okay in autoexec.bat I have an image viewing program the worked fine in 5.2 now getting message "ImportError: The _imaging C module is not installed" Have 2 files (_imaging.pyd and _imagingtk.pyd) which I assume are the C imagaging modules and have put copies of them in all the directories that they might be accessed in: DLL PIL TCL\BIN but still get everything: canvas buttons etc but no image. Below is the error readout in the output window. Any and all help appreciated. ---------------------------------------------------------- There are 923 images Traceback (most recent call last): File "", line 1, in ? File "H:\ClickView2.py", line 46, in ? scrapbook = Scrapbook(root) File "H:\ClickView2.py", line 27, in __init__ self.getImg(0) File "H:\ClickView2.py", line 34, in getImg self.img = ImageTk.PhotoImage(self.masterImg) File "C:\PYTHON22\PIL\ImageTk.py", line 86, in __init__ self.paste(image) File "C:\PYTHON22\PIL\ImageTk.py", line 108, in paste im.load() File "C:\PYTHON22\PIL\ImageFile.py", line 125, in load self.load_prepare() File "C:\PYTHON22\PIL\ImageFile.py", line 175, in load_prepare self.im = Image.core.new(self.mode, self.size) File "C:\PYTHON22\PIL\Image.py", line 43, in __getattr__ raise ImportError, "The _imaging C module is not installed" ImportError: The _imaging C module is not installed ------------------------------------------------------------ rloisel at helicon.net (Rod Loisel Enfield NH USA) From kalath at lycos.com Sun Mar 3 11:41:01 2002 From: kalath at lycos.com (Mark Brady) Date: 3 Mar 2002 08:41:01 -0800 Subject: PEP 262 (database of installed Python packages) References: <3wgg8.685$Qo2.70120@news02.tsnz.net> Message-ID: "Andy Elvey" wrote in message news:<3wgg8.685$Qo2.70120 at news02.tsnz.net>... it would be *truly* wonderful if there were a (standard?) database > of *all* installed packages (Python, Ruby, and whatever else) - maybe in a > directory called "search". In Linux, this could be "/search" , in Win32 > "C:\search". I uderstand where you are coming from but I personally don't think that this is a good idea. I love the idea of a Python module database and infact I always try to use distutils to build a wininst or rpm so that I can easily see and manage the packages I have installed. I like Ruby, Perl, etc. but they all have their own ways of doing things. I don't think a Python PEP is the place to try and solve their package management problems as well as our own. However if we do use a fairly generic solution maybe it would become a de-facto standard. Anyway have a nice day everyone, Mark Brady. From bokr at oz.net Wed Mar 20 00:03:28 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Mar 2002 05:03:28 GMT Subject: Passing command line arguments when debugging with IDLE References: Message-ID: On 20 Mar 2002 03:26:44 GMT, bokr at oz.net (Bengt Richter) wrote: >On Tue, 19 Mar 2002 20:43:33 -0500, "Nigel-Fi" wrote: > >>A newbe question from someone more familiar with devstudio type >>environments... >> >>I have a python program which takes command line arguments and i'd like to >>debug it with IDLE but I cant see how to specify them when I open the py >>file or run it within IDLE. >> >I'd just make a temporary assignment to sys.argv right after the import sys, e.g., > > import sys > sys.argv = ['arg0', '-opt', 2, 'etc.'] > Oops, that 2 should also have quotes. Every arg from sys.argv will normally be a string. >and then pretend it was set normally. Comment out when ready to run from command line >or other starting method that passes cmd line parameters. > >HTH Sorry 'bout that. > >Regards, >Bengt Richter > > From donn at u.washington.edu Fri Mar 1 11:51:47 2002 From: donn at u.washington.edu (Donn Cave) Date: 1 Mar 2002 16:51:47 GMT Subject: Useful, robust shell utilities References: Message-ID: Quoth Jonathan Gardner : | I tried to use the shutil module... and to tell you the truth, it stinks. | Is there an effort to make a robust, useful shutil module that has the | equivalent of the unix shell utilities? Go ahead. Then keep an eye out on comp.lang.python, and after some years pass finally someone will mention it: "it stinks", they'll say, with no particular explanation. | I think it would be nice to make things like 'grep' even... | | Here is my wish list. Each of these should implement a significant portion | of what the GNU utils do. They should be robust, and give reasonable | results, and reasonable exceptions. | | touch, chmod, chown, chgrp, touch | df, du | cp, dd, install, mv, rm, shred Some of them are essentially POSIX 1003.1 functions, hence supported in the posix module (which we usually call "os" so it will appear that these functions are supported on all platforms, whether they really are or not.) chmod == chmod() chown == chown() chgrp == chown() rm == unlink() mv == rename() dd ~= read(), write(), lseek() df == fstatvfs() Donn Cave, donn at u.washington.edu From peter at engcorp.com Mon Mar 4 19:19:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Mar 2002 19:19:18 -0500 Subject: Windows GUI - which way? References: <3C7EC855.5844B19F@engcorp.com> <3C83D003.411FEE3F@ccvcorp.com> Message-ID: <3C840F06.B3D3CE97@engcorp.com> Spencer Ernest Doidge wrote: > > It happens that I want to do all this with scripts that are all under my > control, so there is a lot of good news here in your answer. > One further question: Should the two processes communicate with each other > via mmap? Might depend. What's the nature of the communication involved? Lots of data, a few simple messages, complex objects, or something else? That is, are there constraints? Personally, I would not use mmap. Maybe that's because I have never looked at it (or, apparently, needed it). Is Queue adequate for your needs? (I suspect mmap is not thread-safe but I could be wrong.) From sjmachin at lexicon.net Thu Mar 7 18:59:55 2002 From: sjmachin at lexicon.net (John Machin) Date: 7 Mar 2002 15:59:55 -0800 Subject: Bug in the standard module random ? References: <3C8791B1.6BBC1981@Spam.Please> Message-ID: Weet Vanniks wrote in message news:<3C8791B1.6BBC1981 at Spam.Please>... > Hi, > > The gammavariate function of the standard module is documented as > taking two parameters, the first one alpha is required to be > -1 and > the second beta is required to be >0. > However, examining the implementation, it seems that the requirement for > alpha is to be >0. > > In spite of this, I still have a problem since I called the gammavariate > function with a parameter alpha equal to 0.2 and it fails logically on > the following line: > ainv=_sqrt(2.0 * alpha - 1.0) > > Apparently, the implementation requires alpha to be > 0.5. > Am i missing something or is it a bug? Yes *and* yes :-) Reading on further in random.py, one finds that stdgamma() uses the ainv, bbb, and ccc etc arguments only if alpha > 1.0 Further, stdgamma() is called (inside random.py) only from the line you quoted. The module exposes both gammavariate() and stdgamma() --- stdgamma() with those three extra args seems useless to me. The documentation says there is a gamma() but doesn't mention gammavariate() and stdgamma(). The exposed function shold be called "gammavariate" (a) for consistency (b) to avoid the perceived need to explain that this "gamma" is not the gamma function!!! As you have noticed, the usable range of alpha is incorrectly documented also. You should be able to fix this yourself; if not, let me know your real e-mail address and I'll send you a fixed version (and submit it to SF). > > Best regards > > Weet > > > ## -------------------- gamma distribution -------------------- > > def gammavariate(self, alpha, beta): > # beta times standard gamma > ainv = _sqrt(2.0 * alpha - 1.0) > return beta * self.stdgamma(alpha, ainv, alpha - LOG4, alpha + > ainv) From dgrisby at uk.research.att.com Thu Mar 21 05:13:28 2002 From: dgrisby at uk.research.att.com (Duncan Grisby) Date: 21 Mar 2002 10:13:28 GMT Subject: Python/CORBA References: <3C98DD6E.EB227047@lfpt.rwth-aachen.de> Message-ID: In article <3C98DD6E.EB227047 at lfpt.rwth-aachen.de>, Viatcheslav Kulikov RWTH Aachen wrote: >Can anyone probably answer a question why Python 2.1 sends me an >exception message "INITIALIZE: Minor: 0, Completed: COMPLETED_NO." while >I am trying to initialize omniORB CORBA interface with: > >from omniORB import CORBA >orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) The networking set-up on your machine is probably broken. Do other network server applications work? Try running the program with command line arguments -ORBtraceLevel 10. That will indicate where (in the omniORB C++ code) the exception is coming from, and help track it down. Cheers, Duncan. -- -- Duncan Grisby \ Research Engineer -- -- AT&T Laboratories Cambridge -- -- http://www.uk.research.att.com/~dpg1 -- From Jonathan_Epstein at nih.gov Thu Mar 7 11:42:49 2002 From: Jonathan_Epstein at nih.gov (Jonathan Epstein) Date: Thu, 7 Mar 2002 11:42:49 -0500 Subject: Python/C - Memory-Management References: Message-ID: <4xMh8.1$f5.1383@mencken.net.nih.gov> I have a similar problem with SWIG, which I haven't gone back to in a while. When I do get back to it, though, I plan to either purchase a license for Rational Purify, or just see how much I can accomplish using a free trial license. I believe that Purify runs on Windoze, Solaris and Irix. If one or more of these platforms are available to you, I suggest giving it a try. It's pretty expensive, but about half the price on Windoze ($750?) as I recall. http://www.purify.com/products/purify_unix/index.jsp http://www.purify.com/products/purify_nt/index.jsp Oh, and please let me know how effective this is if you try it ;-) -Jonathan "Heiko Wolf" wrote in message news:d013da35.0203070154.64411e59 at posting.google.com... > Hi there, > > I've got some C-functions that shall be adressed from Python. Thats no > problem, thanks to SWIG. > > But now there is a problem about the memory management: One of the > C-functions allocates memory for all the other functions. In C it > works that way: > > static char *memory = NULL; > > int init_mem (void) > { > > memory = (char *)malloc(sizeof(char) * 1000); > } > > int free_mem (void) > { > > free(memory); > } > > If another function calls init_mem, it can use memory until free_mem > is called... I want to do the same now in Python, but it seems as if > the static memory isnt kept somewhere? When I try accessing it, I get > a Segmentation Fault... Any suggestions? > > Cheers, Heiko From edream at tds.net Sat Mar 9 12:36:18 2002 From: edream at tds.net (Edward K. Ream) Date: Sat, 09 Mar 2002 17:36:18 GMT Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> Message-ID: <3C8A4810.85A56A1@tds.net> > > Dynamic tracing is trivial to implement. More importantly, it is > > simpler to use and more flexible than any static scheme such as the one > > described in 282. > > except that in real systems, the end user couldn't care less > about what/when/how your Python functions are called. > > they do care about syslog-compatibility, severity levels, and > trivial things like getting the same logging messages also after > you've refactored your program... I was talking about functionality, not packaging. Naturally, a logger would be a class. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From gerson.kurz at t-online.de Sat Mar 9 14:33:21 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sat, 09 Mar 2002 19:33:21 GMT Subject: List of lists: caveat? References: Message-ID: <3c8a6335.54994765@news.t-online.de> On Sat, 9 Mar 2002 15:09:30 -0500, George Thomas wrote: >What are the exact semantics of the line marked (I) above? If there is a I fell for that one, too. There is an entry in the FAQ for it: http://www.python.org/doc/FAQ.html#4.50 From peter at engcorp.com Fri Mar 15 08:13:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 15 Mar 2002 08:13:24 -0500 Subject: socket References: Message-ID: <3C91F374.831A3061@engcorp.com> Billy Ng wrote: > > I am trying to write a python program to verify the email address. Here is > what I am going to do: > [...] > In fact, I could send VRFY: to shorten the code, but I > notice so many SMTP server does not allow VRF command. I also notice the > many SMTP server denies the RCPT TO command too. If you have down something > like this, please tell how did you do it. Why are you trying to verify email addresses? If you can let us know the overall purpose of the program we can probably provide you with better advice about how to accomplish the goal. -Peter From irmen at NOSPAMREMOVETHISxs4all.nl Wed Mar 27 18:39:30 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Thu, 28 Mar 2002 00:39:30 +0100 Subject: unicode experiments + questions -- PythonWin?? References: Message-ID: Brian Quinlan wrote: > >>> e=u'\u20ac' > >>> e > u'\u20ac' > >>> print e > ? (<--- this is an Euro symbol on my screen) >Is this what actually happens? Did you change your default encoding to >be something other than ASCII, possible by modifying site.py? I changed it back to the default, "ascii". The example is from within PythonWin (the GUI!). There is something with that: when I do "print e" in PythonWin it prints the Euro, ?. When I do "print e" in the console python, it throws an exception ASCII encoding error: ordinal not in range(128) Print redirection to a file using print >> also throws the encoding exception in PythonWin. Only directly printing to the GUI console appears to work. Hmmm... What does PythonWin do!?? > The print does not do any conversion; it just sends bytes to the output stream. Hmm... how does it send the unicode string to the output stream? Not as raw unicode (unconverted), because print redirection throws an encoding exception. Irmen From michael at stroeder.com Fri Mar 29 09:49:40 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 29 Mar 2002 15:49:40 +0100 Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> <3CA3D86A.7080806@yahoo.com> <67abb823.0203290500.3a3a7da1@posting.google.com> Message-ID: <3CA47F04.1080602@stroeder.com> Sloth wrote: > > The reason that I'd like to find a native Python script is as follows: > I started to build a proof of concept Web app for a company that > queried a customer database and generated search results. The company > loved it and wanted to have me create a few "pilots" for salespeople. > If I can simply have them install Python and install an additional > module or two, it would be easier than asking non-technical sales > folks to also install Apache. This is exactly the point. Install Python, unzip the web app package and double-click on a start script. That's easy. I usually write my web apps that they run under both environments. I strongly recommend to use file objects for output instead of print statements. This makes it easy to write a bunch of wrappers around the web app for various web server APIs (FastCGI, mod_python, BaseHTTPServer, etc.) by just passing file objects for output, error log and a dictionary containing the CGI-BIN environment. Ciao, Michael. From sam_collett at lycos.co.uk Fri Mar 1 12:12:40 2002 From: sam_collett at lycos.co.uk (Sam Collett) Date: 1 Mar 2002 09:12:40 -0800 Subject: Javascript to Python Message-ID: <2030665d.0203010912.1bb9c0ae@posting.google.com> Does anyone know of any good sites on Javascript > Python examples? I have a function in javascript that returns the file extension: function FileExtension(sFilePath) { return Right(sFilePath,sFilePath.length-sFilePath.lastIndexOf(".")) } so FileExtension("/path/to/file.doc") would return .doc I would also want to return the filename (file) and the path (/path/to/). How would I go about that? What equivalents to the functions Right and Left (right side of string, left side of string) Also is there an easier way to do number incrementing (just me being lazy): while r<5 print r r=r+1 I have tried r++ to add 1 each time, and r-- to take away one, but this does not work, so is the only way r=r+1 or r=r-1 ? TIA From loewis at informatik.hu-berlin.de Sun Mar 17 12:43:57 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 17 Mar 2002 18:43:57 +0100 Subject: sunstring References: <0r4l8.22204$P4.1955815@newsread2.prod.itd.earthlink.net> Message-ID: "Billy Ng" writes: > Would anybody tell me how to do substring in python? >>> s="Hallo" >>> s[2:4] 'll' HTH, Martin From jkraska at san.rr.com Wed Mar 13 19:59:25 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 14 Mar 2002 00:59:25 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8FBDD6.9906E423@ccvcorp.com> Message-ID: <6utv8u8o6kodq4537a6d86qtfp97p6sd47@4ax.com> >> Rather, it seems to me that Microsoft is saying that they will not >> allow their products to be used in any way that might potentially >> compel Microsoft to disclose any of their own source code. No one, other than Microsoft, can use Microsoft's products in such a way as to compel Microsoft to disclose their source code. They don't need a license for that, and there is no legal ambiguity _what so ever_. C// From jeff at ccvcorp.com Thu Mar 28 14:23:13 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 28 Mar 2002 11:23:13 -0800 Subject: Extension Modules in C References: Message-ID: <3CA36DA1.7A4DA872@ccvcorp.com> Michael Saunders wrote: > I am trying to wrap an existing C API as an extension module for Python. Some of > the functions have parameters that are both input and output. > Can this function be wrapped to have a similar API from python. For instance in > Pytyon: > > isOk = SomeModule.GetSomeInfo(None, count, size) > if isOk: > print count, size The "Pythonic" way of doing this would be: isOk, count, size = SomeModule.GetSomeInfo(None, count, size) Actually, it'd be even more Pythonic to drop the isOk return, and raise an exception if it's *not* okay. Jeff Shannon Technician/Programmer Credit International From eppstein at ics.uci.edu Thu Mar 7 19:39:06 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 07 Mar 2002 16:39:06 -0800 Subject: PEP 284, Integer for-loops (code bash?) References: Message-ID: In article , Gustavo Cordova wrote: > So, I propose an answer to this, and here it is. > > Just do a "from ints import Ints" at the beginning of the program. Your ints module is nice, and I think if it were in the standard library I'd be a lot less motivated to push PEP 284. But, the objection to it will be that it only creates closed intervals, where other Python objects create half-open ones and it would be nice to have a syntax that would allow any combination of open and closed interval endpoints. From philh at comuno.freeserve.co.uk Sat Mar 30 14:53:53 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 19:53:53 +0000 Subject: PEP 285: Adding a bool type References: Message-ID: On Sat, 30 Mar 2002 00:39:10 -0500, Guido van Rossum wrote: >Abstract > > This PEP proposes the introduction of a new built-in type, bool, > with two constants, False and True. My first reaction to this was "shit, this will break every non-trivial program". However the details of the proposal are such that it won't, it goes out of its way to implement backwards compatibility. >Rationale > > Most languages eventually grow a Boolean type; even C99 (the new > and improved C standard, not yet widely adopted) has one. That's hardly a valid reason. Should we scrap syntactic indentation and use BEGIN and END keywords instead? Most languages do some varient of that. > Here are some arguments derived from teaching Python. When > showing people comparison operators etc. in the interactive shell, > I think this is a bit ugly: > > >>> a = 13 > >>> b = 12 > >>> a > b > 1 > >>> > > If this was: > > >>> a > b > True > >>> That *is* a valid reason. However, it must be decided whether Python's primary goal is to be easy to learn or easy to use. This proposal makes it easier to learn in some respects, but adds difficulty as well, as the user must learn a new data type, albeit a rather simple one. > it would require one millisecond less thinking each time a 0 or 1 > was printed. This would be true the first 2 or 3 times someone sees a 0 or 1 in response to a boolean query. > There's also the issue (which I've seen puzzling even experienced > Pythonistas who had been away from the language for a while) that if > you see: > > >>> cmp(a, b) > 1 > >>> cmp(a, a) > 0 > >>> > > you might be tempted to believe that cmp() also returned a truth > value. If ints are not (normally) used for Booleans results, this > would stand out much more clearly as something completely > different. That's true, but it's not a biggy. > Other languages (C99, C++, Java) name the constants "false" and > "true", in all lowercase. In Python, I prefer to stick with the > example set by the existing built-in constants, which all use > CapitalizedWords: None, Ellipsis, NotImplemented (as well as all > built-in exceptions). Python's built-in module uses all lowercase > for functions and types only. But I'm willing to consider the > lowercase alternatives if enough people think it looks better. I prefer True, False. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From peter at engcorp.com Wed Mar 27 23:02:20 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Mar 2002 23:02:20 -0500 Subject: Sorting distionary by value References: Message-ID: <3CA295CC.9682E2DB@engcorp.com> Jim Dennis wrote: > > The core loop is something like: > > freq = {} > for line in file: > for word in line.split(): > if word in freq: freq[word] += 1 > else: freq[word] = 1 > > (assuming Python2.2 for file interation and dictionary membership > support using "in." I *really* like those 2.2 features! They make > my psuedo-code so executable!) Something like freq[word] = freq.get(word, 0) + 1 would probably be faster, and it's a little simpler I think, although I could see an argument that it's less readable. Also doesn't depend on 2.2. -Peter From jkraska at san.rr.com Sun Mar 10 21:38:06 2002 From: jkraska at san.rr.com (Courageous) Date: Mon, 11 Mar 2002 02:38:06 GMT Subject: Translating Python to C (was Re: Modulo operator : differences between C and Python) References: <3C8BE537.74E55963@mega-nerd.com> Message-ID: >> Just recently I prototyped a relatively complex algorithm in Python >> before converting it to C. I'm curious about your experiences. I did something myself recently, creating a fairly sophisticated prototype in Python and then implemented it in C++. Given that I had all the algorithms worked out and thoroughly debugged, it was astounding to me how difficult it was to get properly translated and then validated. It took literally 3 times as long or longer to get the C++ version implemented and provably functional, this in spite of the design time work being included in what it took to do the Python implementation. Programming in C++ genuinely depresses me. And I'm an old veteran. I've been using it since the days of C Front, if anyone around happens to know what that means. :-) C// From logstx at bellatlantic.net Fri Mar 29 17:13:25 2002 From: logstx at bellatlantic.net (logistix) Date: Fri, 29 Mar 2002 22:13:25 GMT Subject: Slice objects. How to apply them to strings? References: <04g9au4kn4dtg92584l12n0ut001c7rb9m@4ax.com> Message-ID: <9G5p8.587$AE1.529@nwrddc03.gnilink.net> > > > >If 'item' is a slice object, shouldn't I just be able to say: > > > > self.s[item] > >? > > Yes, it would be sensible. No you can't do it. For some reason you can't apply slice objects to built-in types. Ultimately, this is because slice objects are just a hack for operator overloading purposes. I honestly don't know how difficult it would be to modify the interpreter to allow types to accept slice objects, but I imagine it's one of the things on the list for "class/type unification" Here are a few things if you think your code is too ugly. First of all, "step" is not valid in builtin objects, so you can ignore that case. You can also use a boolean short-circuit trick to take care of start: def __getitem__(self, item): if type(item) == types.IntType: return self.s[item] elif: return self.s[item.start or 0, item.stop] else: raise TypeError, "sequence index must be interger or slice object" That's about as short as you can safely get on the routine. From dalke at dalkescientific.com Wed Mar 13 00:15:43 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 12 Mar 2002 22:15:43 -0700 Subject: Question about scientific calculations in Python References: Message-ID: Martin Kaufmann: > for s in s_vector[1:]: > sum = 0 > for r in r_vector[1:]: > x = 2 * pi * r * s > sum = sum + (2 * (sin(x))/x) > intensity = atoms * pow(f_s_vector[n], 2) * (1 + sum / atoms) > i_vector.append(intensity) > n = n + 1 Here's some performance improvements you can make def ... # Precompute the 2*pi*r, which is a constant inside of the s loop precomputed_r1_vector = [2 * pi * r for r in r_vector[1:]] local_sin = math.sin # local variables have fast lookup # using the zip gets rid of the extra n+1 and [n], at the expense # of making a new list. I suspect it's faster, but I'm not sure for s, f_s_vector in zip(s_vector[1:], f_s_vector): sum = 0.0 for scaled_r in precomputed_r1_vector: x = scaled_r * s sum = sum + 2 * (local_sin(x)/x) # Did some algebra here to merge the first and last terms, # which gets rid of the division. Also replaced the function call # to 'pow' with the equivalent use of **2 i_vector.append((f_s_vector**2) * (atoms + sum)) Some of these changes are only faster for sufficiently long arrays, so you should test them out yourself. The biggest trick is to precompute as much as possible (Python doesn't optimize constant expressions). This includes precomputing lookups of functions references, like the "local_sin". Also, you could precompute the lookup of i_vector.append, as in i_vector_append = i_vector.append ... for ... i_vector_append((f_s_vector**2) * (atoms + sum)) >Now the histogram code where the radii are binned in the histogram >hist and only the bins with a value are used: That code is almost identical with the previous code, so you can do the same optimization tweaks. You could also precompute which hist elements have entry[1] == 0 so you don't do that check every time in the loop. (As it is now, the "if" check is probably more expensive than the calculation, even if you know it's zero, unless there are a lot of zeros.) If your lists are really long (O(100,000) or more?) then you might find that the append starts taking too long -- append is asymptotically O(n**n) in Python -- so that precomputing i_vector = [None] * len(s_vector - 1) then keeping an index 'n' to replace i_vector.append( ...) with i_vector[n] = ... is faster. But this is unlikely. Probably the best optimization you can do, if PyInline is an acceptable approach, is to write put that sinc sum into C code. It reduces to taking two lists and returning a float. Andrew dalke at dalkescientific.com From mats at laplaza.org Mon Mar 4 09:23:34 2002 From: mats at laplaza.org (Mats Wichmann) Date: Mon, 04 Mar 2002 14:23:34 GMT Subject: Minor, minor style question References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> <7le58u86cc6u7ibsdobuj7jk8gqobuluq5@4ax.com> Message-ID: <3c8382f3.291759938@news.laplaza.org> On Sun, 03 Mar 2002 16:09:03 -0800, Tim Roberts wrote: :claird at starbase.neosoft.com (Cameron Laird) wrote: : :>Why would I prefer :> string = "" :> string = string + "abc " :> string = string + "def " :> string = string + "xyz" :>over :> string = "abc " + \ :> "def " + \ :> "xyz" :>? I see a lot of the former in contexts I associate :>with Visual Basic- or JavaScript-majority folkways. :>Is there an attraction to the redundancy (and fragil- :>ity!) I'm missing? Are \-s *so* deprecated? : :Visual Basic programmers write things this way because VB didn't support :line continuation characters until relatively recently. Until then, you :either had to write your concatenated strings as one VERY long line, or via :your first method. I'm far from being a Javascript expert, but I thought it was missing there, too. My one bit of Javascript coding a few years back I ended up having to do something like this to make mutiline text messages. Of course, Python can do the multiline messages natively... Mats Wichmann From sandskyfly at hotmail.com Thu Mar 14 03:59:50 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 14 Mar 2002 00:59:50 -0800 Subject: jython for a large-scale web site? Message-ID: Hi folks, I work with a web company that has about 180,000 registered users, and pretty good weekly traffic stats. Their current platform of development includes Oracle for the data server, AOLServer for web serving platform and TCL to script the whole thing together, with everything running on Solaris on a few fat multiprocessor Sun machines. I just had a chat with the CTO (I've been trying to get him to look into python for a while) and it seems his resistance has finally broken (-: he spent a real weekend with the python and his initial misgivings about significant whitespace have disapeared, and now he's raving about how well the language 'flows'. Suddenly, this recent convert wants to incorporate python into the next generation build of the web site. Now he is leaning towards using a combination of jython and java to reimplement and refactor the design as he likes the support and momentum behind java and doesn't want to give up the productivity benefits of a scripting language. Now, I'm really happy to have turned the top tech decision-maker in the company on to python (kinda validates my fascination with the language internally :-) But I'm worried about things like performance and scalability: is it wise to service this number of customers with jython servlets running on tomcat for example? Any advice would be much appreciated. Thanks. Sandy From brueckd at tbye.com Wed Mar 27 13:02:59 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 27 Mar 2002 10:02:59 -0800 (PST) Subject: instrumenting Python code In-Reply-To: <15521.63244.469114.753420@beluga.mojam.com> Message-ID: On Wed, 27 Mar 2002, Skip Montanaro wrote: > > Dave> Now, about profiling multithreaded applications. Do you have any > Dave> suggestions? > > Other than looking at Python/ceval.c and Modules/_hotshot.c to see what > needs to be done, no. A quick peek at the slides from Fred's hotshot talk > at IPC10 suggests that multithreading is either not yet supported or not > well-supported. Fred probably has a better idea what still needs to be done > if you want to tackle it. Ok, thanks, I'll talk to him. -Dave From cppdan at dansmart.com Fri Mar 29 00:33:39 2002 From: cppdan at dansmart.com (Dan Smart) Date: Fri, 29 Mar 2002 05:33:39 GMT Subject: Python & Poetry References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> <7396d2b2.0203271554.5a564e1b@posting.google.com> Message-ID: d_blade8 at hotmail.com (Lemniscate) wrote in news:7396d2b2.0203271554.5a564e1b at posting.google.com: > In our case, coding is conveying an idea of a behavior to the > computer. Minor disagreement. Computers will read any old dross, a computers requirements for "clarity of expression" are strict but minimal. Really great code tells a story to other programmers, and is indeed literature. The greatest compliment I've ever been paid, was when someone said of my code: "I picked it up, and I knew what it did". Dan "Computers on the other hand have always known what my code did, even when I didn't" Smart -- Dan Smart. C++ Programming and Mentoring. cppdan at dansmart.com From DeepBleu at DeepBleu.org Fri Mar 1 13:21:05 2002 From: DeepBleu at DeepBleu.org (DeepBleu) Date: Fri, 1 Mar 2002 12:21:05 -0600 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> Message-ID: "Anthony_Barker" wrote in message news:899f842.0203010812.6151d817 at posting.google.com... > "DeepBleu" wrote in message > > Deitel and Deitel book on Python? I personally would not touch it. Give me > > a book written by Lutz, Holden or Hammond any time. But not from the > > establishment of Deitel. I bet you they do not even know how to program in > > Python. All their books are churned out by what resembles an > > industry-complex with standard issue. > > Long ago I discovered a mistake in their old C++ How to Program. I sent > > them an e-mail. The answer still brings vivd memories of when you feel like > > throwing up. Arrogant bunch of oppurtunists who are not worth the price of > > the paper their books are printed on. > > You want books on Python: Buy Beazley, Lundh, Holden, Hammond, Greyson > > etc.... > > Leave Deitel alone! > > DeepBleu > > [...........] That said, > more books on the python landscape is a good thing. And as the > previous poster said, programming books are a personal thing. > I certainly agree with you on this one. I had formed a negative bias about them out of my old encounter with them over the error in C++ How to Program. > > I would love to see books on Algorithms with Python (makes a perfect > fit), and more advanced topics such as threads and extending python. I'd love to see something like that specially on threads and extending Python. This is something I can use. DeepBleu From syver-en+usenet at online.no Tue Mar 12 14:49:11 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 12 Mar 2002 19:49:11 GMT Subject: Manage Windows shortcut in Python References: <3C8E4514.3E8D6684@impathnetworks.com> Message-ID: As often when things are about windows, win32all is the answer. (I think the package is called something with shell) -- Vennlig hilsen Syver Enstad From thoa0025 at mail.usyd.edu.au Sun Mar 24 15:18:15 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 24 Mar 2002 20:18:15 GMT Subject: no access to lib dir References: Message-ID: Just a note, Since i wish to run the script on a university server, i have no access to where python keeps it's libraries for me to put my script there. I still strive to believe there is a way - and that someone knows and can help me. Cheers -- Trung Hoang Final year Undergraduate of Computer Science and Technology University of Sydney, Australia. "Trung Hoang" wrote in message news:Ooqn8.5968$EE4.23248 at news-server.bigpond.net.au... > I've located the problem down to this. i have a file "xml.py" which has a > function "getProjects()" which i would like to access from c. In the > interpreter i execute the following commands: > > Python 2.1.2 (#2, Jan 18 2002, 11:23:35) > [GCC 2.95.2 19991024 (release)] on sunos5 > Type "copyright", "credits" or "license" for more information. > >>> modname = "xml" > >>> mod = __import__(modname) > >>> mod > > >>> > > so that says that the module is locatable by the interpreter. but when i > compile and run the following program: > > #include > > int main (int argc, char *argv[]) { > // declare variables > PyObject *modname = NULL; > PyObject *mod = NULL; > > // init > Py_Initialize(); > > modname = PyString_FromString("xml"); > mod = PyImport_Import(modname); > if (mod == NULL) printf("mod is null\n"); > > Py_XDECREF(mod); > Py_XDECREF(modname); > Py_Exit(0); > } > > it prints out "mod is null" meaning it cant find the module. > > Does anyone have a working example of Pure Embedding? It's for my personal > private project - for fun, supposedly, well before it was, not my > assignment. > > Please :( > Cheeeeeeeeeeers > > -- > Trung Hoang > Final year Undergraduate of Computer Science and Technology > University of Sydney, Australia. > > From cmaloney at physics.ucsb.edu Fri Mar 1 12:25:46 2002 From: cmaloney at physics.ucsb.edu (Craig Maloney) Date: 1 Mar 2002 09:25:46 -0800 Subject: Scripting C++ -- 2 -- a more concrete example. References: <3C7E6642.2030202@physics.ucsb.edu> Message-ID: <6bf54244.0203010925.38d237ed@posting.google.com> Donovan Rebbechi wrote in message news:... > In article <3C7E6642.2030202 at physics.ucsb.edu>, Craig Maloney wrote: > > If using a wrapper generator (e.g. SILOON) I don't see a way around the > > marshalling of the call to get at the atom data structure. > > I don't really understand exactly what the problem is. > > > > Of course, this would be taken care of by a revamp of the design of the > > class library... maybe making the crystal an atom factory that produces > > new atoms in its own address space. But I would like to avoid thinking > > Now I'm really confused. If you're not using CORBA, the atoms are in the > same address space, aren't they ? This is how I presumed that Boost also worked -- I must be mistaken. After having seen yours and Ralf's comments, I now have the impression that Boost works it's magic differently. Perhaps Craig Rasmussen could enlighten us as to how SILOON deals with co-location issues such as the one above? >From the SILOON doc/design.html page : ----------------------------------------- The goal of SILOON is to generate bindings so that users can access the functionality of an existing application or library from a scripting language. In order to accomplish this, the essential functionality of SILOON is separated into three separate modules: 1. Client Interface. The client script is responsible for calling the client interface using a low level invoke function with the name of the function to be invoked and with function parameters. The client interface is responsible for translating the function name received from the client into a function identifier (an integer), which is associated with the requested function on the server. The function identifier is marshalled into a buffer, along with function arguments received from the scripting client. This buffer is then handed off to the transport layer to be delivered to the compute server. On completion of the function call, the transport layer returns the buffer and the client interface is responsible for unmarshalling the return value and passing it on to the client. The remote method invocation is done synchronously with the client blocking until the call has completed. The client interface also comprises user-friendly script wrapper classes and an alias mechanism that lets the user redefine names of functions. 2. Transport Layer. The transport layer is responsible for delivering the argument buffer to the server and subsequently returning the buffer to the client interface when the method invocation has completed. 3. Server. The responsibility of the server is to unmarshall the function arguments from the received argument buffer and then to call the correct function. After the function has finished executing, the returned value is marshalled into the argument buffer and the buffer is returned to the transport layer. -------------------------------------------------------------------------- From gh_pythonlist at gmx.de Tue Mar 19 02:11:45 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 19 Mar 2002 08:11:45 +0100 Subject: Chewing international (unicode) filenames on windows? In-Reply-To: References: Message-ID: <20020319071145.GA385@lilith.hqd-internal> * Andrew Markebo [2002-03-19 07:33 +0000]: > I am messing a bit with my bookmarks [...] Just as a remark: Maybe you could use XBEL (XML Bookmark Exchange Language). IIRC it was invented for Grail, a Python/Tkinter based web browser. There's even support for it in the Python/XML package. Some other browers support it nowadays: It's now Konqueror's native bookmark format and Galeon can import and export it. On my homepage (=> sig) you can find a IMO nice XSLT stylesheet for it. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From wecaputo at thoughtworks.com Sat Mar 9 02:01:08 2002 From: wecaputo at thoughtworks.com (logosity) Date: Sat, 09 Mar 2002 07:01:08 -0000 Subject: short-circuit behavior anomaly? Message-ID: Hi, I was working through this tutorial: http://gnosis.cx/publish/programming/charming_python_13.txt Which shows the statements in the following functions (imp and fn) as equivalent: def pr(s): print s def imp(): if x == 1: pr('one') elif x == 2: pr('two') else: pr('other') def fn(): (x == 1 and pr('one')) \ or (x == 2 and pr('two')) \ or (pr('other')) Here is a sample program: x = 1 imp() x = 2 imp() x = 3 imp() print x = 1 fn() x = 2 fn() x = 3 fn() When run, this produces the following output: one two other one other two other other IOW, the third clause gets evaluated regardless of the outcome of the first two clauses. However, substituting the following in fn() will produce the same result as imp(): print (x == 1 and ("one")) or (x == 2 and ('two')) or ('other') Implying something to do with the function calls -- if I replace the pr('one') call in the line again will cause 'other' to be printed after 'one') I am wondering, is this a mistake in the tutorial, a change in behavior between versions (I am using 2.1 and the tutorial seems to be written against 2.0), a bug in Python, or something else? I have looked through the FAQ, browsed the bug list at SF, read the relevant sections of the language reference and searched (as best I could) the mailing list archive here (and at google), but I can't find out what the deal is. Anyone have any thoughts? Thanks, Bill From bokr at oz.net Fri Mar 15 17:31:23 2002 From: bokr at oz.net (Bengt Richter) Date: 15 Mar 2002 22:31:23 GMT Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: On Fri, 15 Mar 2002 12:26:30 -0800, "Nick Arnett" wrote: >Anybody have any experience generating word frequencies from short documents >with Python and Perl? Given a choice between the two, I'm wondering what >will be faster. And a related question... any idea if there will be a It'll take 15 minutes to get a program working in Python ;-) Ok, maybe a bit longer if your docs have tricky syntax to write a splitting regex for ;-) >significant performance hit (or advantage?) from storing the data in MySQL >v. my own file-based data structures? > If all you want is to be able to get it back within another (or the same, later) Python program, check into the pickle module. You could just dump the directory of directories I describe below, I believe. >I'll be processing a fairly large number of short (1-6K or so) documents at >a time, so I'll be able to batch up things quite a bit. I'm thinking that >the database might help me avoid loading up a lot of useless data. Since >word frequencies follow a Zipf distribution, I'm guessing that I can spot >unusual words (my goal here) by loading up the top 80 percent or so of words >in the database (by occurrences) and focusing on the words that are in the >docs but not in the set retrieved from the database. > >Thanks for any thoughts on this and pointers to helpful examples or modules. > I'd just code up a short Python program using a python dictionary with words as keys and counts as values for each file, and put all these word frequency dictionaries in a file dictionary with keyed by file name. I'd bet everything fits in memory, unless you have an incredible corpus of words in your files, or small memory. Isolating words will depend on document syntax etc. You may be able to do it by splitting with a compiled regular expression for a combination of white space and punctuation. Regards, Bengt Richter From tbabbitt at commspeed.net Thu Mar 7 11:10:16 2002 From: tbabbitt at commspeed.net (Tom Babbitt) Date: Thu, 7 Mar 2002 09:10:16 -0700 Subject: very newbie question References: <61ff32e3.0203070659.28cf5e1c@posting.google.com> Message-ID: <1015517718.445890@news.commspeed.net> "ron nixon" wrote in message news:61ff32e3.0203070659.28cf5e1c at posting.google.com... > I've got a script called snakes saved to my c: drive and I want to run > it from IDLE. By when I do file open and run script, I get an invalid > syntax message. Likewise if I write the script in IDLE and hit "run > script" it get a message saying that says "the buffer for Python Shell > is not saved. Please save it first." Soooo. With all that being said. > How do I save a script and then get python to execute it from IDLE(and > where in the documentation is this?) > > Thanks in advance It's not clear why you want to run your program from IDLE, you mite want to just run it with phython (ie 'c:\Python22\python snakes.py' (you could need to rename the filename to *.py)). Tom Babbitt From grante at visi.com Sun Mar 10 01:20:03 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 06:20:03 GMT Subject: wxPython: generating event IDs? Message-ID: I'm trying to figure out a simple way to attach commands to buttons in wxPython. The standard method seems to be 1) Define a unique ID number 2) Assign that ID number to the button 3) Hook a closure to that ID number with EVT_XXXX() This seems a bit complicated compared to other toolkits where you just hook the closure to the button when the button is created. I'm sure the wxPython approach has advantages I haven't stumbled across yet, but all the examples I've found could have been handled by the simpler method. There must be a way to eliminate the need to predefine unique ID numbers. I hate trying to maintain lists of numbers like that (well, more accurately, I'm just bad at it). I tried using id(self.Command), but all of the bound methods of an object seem to have the same id (as do all of the unbound methods). This seems quite weird: id(self.x) == id(self.y) is true self.x is self.y is false According to my reading of the language reference, this isn't possible, since "is" compares the id's of the objects. I thought about using the id() of the button, but you don't know that until after the button is created, and you need to pass the ID in when the button is created. There must be a simple solution that I've overlooked... -- Grant Edwards grante Yow! Do you have exactly at what I want in a plaid visi.com poindexter bar bat?? From moxie_is at yahoo.com Sun Mar 17 19:54:46 2002 From: moxie_is at yahoo.com (moxie) Date: 17 Mar 2002 16:54:46 -0800 Subject: Python/JXTA Message-ID: It may be a good idea to create Python bindings for JXTA (P2P [peer-2-peer] networking solution from Sun)... http://www.jxta.org/project/www/background.html Just a thought ;) ~= moxie =~ From chris.gonnerman at newcenturycomputers.net Fri Mar 1 00:27:49 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 28 Feb 2002 23:27:49 -0600 Subject: Can somebody kill getpathp for me? Message-ID: <00bb01c1c0e1$d9045940$0101010a@local> In the PC subdir of the Python-2.1.2 build directory is a module called getpathp.c, which sets up the initial sys.path value. It is well known by Python programmers on Windows that the sys.path initialization includes directories plucked from special registry keys... unless you are using the PythonWare version. I thought, great, I can use this (the PythonWare version) to create Python runnables on CD-ROM; but now I discover a fly in the ointment. If the computer already has an installed Python interpreter, the paths set in the registry are added, and BEFORE the paths from the PythonWare PYROOT variable are added. Gah. What I want is a version of either python.exe or python21.dll (whichever contains the offending getpathp.c module) with the registry-probing code disabled. Ideally it should still apply the paths from PYROOT (basically in this case it must). Can anyone help with this? I am experienced in Linux programming but a novice at Win32, and I don't have MSVC in any event. (Yeah, I know, you can build Python with MinGW32, but it's a PITA.) Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From damononnews at hotmail.com Wed Mar 6 23:47:09 2002 From: damononnews at hotmail.com (Damon Lynch) Date: 6 Mar 2002 20:47:09 -0800 Subject: [Newbie] Code for web-based "members" database? Message-ID: Hi everyone, Does anybody have any suggestions for finding code that will help solve the following problem: I have a members database whose main purpose is to allow members to view other members based on interest areas (and geographical location, projects etc. etc.). The database should reflect that areas of interest are related to one another in non hierarchal ways. For instance, supposing an area of interest is biodiversity conservation, and another area is urban air pollution, and another is organic agriculture. Anyone doing a members' search on environment should find people with those areas of interest. But someone doing a search on agriculture should find organic agriculture, and not urban air pollution. It would be nice if people could suggest new areas of interest for validation. The database is currently stored in a flat file (yuck!). It could be stored in a relational database, assuming that is the best way of storing it. Or any other manner I suppose! Unsurprisingly, access to this database is over the web. A relatively minor point is that I use e-mail addresses from to send out regular e-mail updates. Is there already-existing python code that handles this type of problem? Thanks in advance! Damon From mwh at python.net Thu Mar 21 08:22:14 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Mar 2002 13:22:14 GMT Subject: How to install pychecker? References: Message-ID: Dale Strickland-Clark writes: > I thought I'd try this out. > > In the absence of any instructions (that I can find) I tried unzipping > it to a directory and running setup.py. > > I got this: > > C:\Program Files\pychecker-0.8.10>setup.py > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: no commands supplied > > What am I supposed to do? python setup.py install Did you try setup.py --help or setup.py --help-commands ? Cheers, M. -- Of course, it obviously is beta hardware so such things are to be expected, but that doesn't mean that you can't point your fingers and generate a nelson style HAHA at a multi billion dollar corporation's expense. -- CmdrTaco on slashdot.org From olc at ninti.com Wed Mar 27 13:49:04 2002 From: olc at ninti.com (Michael Hall) Date: Thu, 28 Mar 2002 04:19:04 +0930 (CST) Subject: Python Web Programming Book? Message-ID: I'm wondering if anyone can suggest the best (or a selection of the best) books available covering the use of Python in a web and database environment? It's OK if the book deals with other stuff, as long as its treatment of web programming and database integration is good. Is a book that also deals with Zope, Cheetah and Albatross or related topics (embedded Python, I suppose) asking just too much? A good text will certainly cut down my newbie questions to this list. So far I have Mark Lutz' "Python Programming" and Andre Lessa's "Python Developer's Handbook" on my shortlist. Mick From barry at zope.com Wed Mar 20 01:55:38 2002 From: barry at zope.com (Barry A. Warsaw) Date: Wed, 20 Mar 2002 01:55:38 -0500 Subject: Still same bug even with email ver. 1.2 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> Message-ID: <15512.12906.262129.702973@anthem.wooz.org> Thanks Sheila and David for their private email heads-up; I sadly don't have much time to follow c.l.py. Also, thanks to Andrew for filing the SF bug. >>>>> "SK" == Sheila King writes: SK> OK, I got the latest email module from the CVS. I installed SK> it. I ran the tests for the module. Everything tested out SK> fine. SK> I now eagerly get out my code from last night, that was SK> causing the 'int' has no attribute .lower error, and run it, SK> hoping for different results. SK> No good. Same results. :( I now know what's going on, why I thought the bug was fixed, why others disagreed , and I think I have a solution. I'm cc'ing mimelib-devel at lists.sf.net because my proposed solution has two parts, one for Python 2.2.1 and one for Python 2.3. Background: In Python 2.2, if you have a Message instance with a MIME type of multipart/* but you have only one subpart, the Generator would throw the exception that Sheila describes. This is because the payload of the outer part isn't a list, but the Generator expects a list for multipart/* parts. A multipart/* with one subpart, must have a payload which is a list of length one, i.e. element zero would be the single subpart. What I fixed, and what is in Python 2.2.1, is the Parser class, which takes a plain text representation of the message, and produces the message object tree. In the Parser, I always make sure that the payload is a list for multipart/* MIME types by doing this: # Ensure that the container's payload is a list if not isinstance(container.get_payload(), ListType): container.set_payload([msgobj]) else: container.add_payload(msgobj) This works fine -- for object trees that are built by the parser from flat text. It doesn't work so well when you're building the object tree from scratch, unless you employ the same kludge! I gather from the c.l.py thread that folks are going through the third example in the Python 2.2 documentation http://www.python.org/doc/current/lib/node389.html finding themselves with a directory with just a single file in it, and are seeing Generator blow up when they end up with a multipart/* object with a non-sequence payload. Well, the example doesn't employ this kludge, so it crashes. Let me first outline what I think is the Right Fix and then what I propose for Python 2.2.1. The right fix is to clean up the messy semantics of Message.add_payload(), where the first time you call it, it will set the message's payload to the payload argument (a scalar), but the /second/ time you call it, it transforms the payload into a list, then appends the new payload to this list. This is really pretty gross, and it rubbed me the wrong way when I designed it, but I didn't have any better ideas at the time so there you have it. I believe this is the heart of the breakage. What I think we ought to do is to deprecate Message.add_payload() but leave its semantics unchanged, change Message.attach() to not be an alias for add_payload(), and define the semantics of attach() to always set the payload to a list. Thus, the first time you call attach(). I think attach() should retain the semantics that if the MIME type isn't multipart/* it should throw an exception (i.e. you can't attach() to a non-multipart; use set_type() first). This means that if never set, a Message's payload would be None. After the first attach() it would be a list of length one, and subsequent attach()'ments would increase the length of the payload. To get the old, initial semantics of add_payload(), you'd instead call set_payload() which always just sets the message's payload to the method's argument. This would be used, for example, when you have a message/rfc822 MIME type and want to set the payload to an instance of a MIMEMessage, or if you have a image/gif and want to set the payload to an instance of MIMEImage. For Python 2.3 (and for the next version of the standalone email package), I'd like to add a DeprecationWarning to add_payload(), then make the semantic change to attach(). The downside is that this might break code that relied on these semantics, however, I think if you had such an object tree, you wouldn't be able to use the Generator to flatten it anyway. I'm open to suggestions here. There's a problem though: this isn't a change that should be made in Python 2.2.1! It changes the API to the email package, and that should only be done in Python 2.3, IMO. For Python 2.2, I /think/ I can fix Generator._handle_multipart() to watch out for subparts that are scalar[1]. If so, then the patch to the Parser described above probably ought to be backed out. As long as the unit tests pass, I think we'd be okay. This is probably a good patch to keep for Python 2.3, just to be safe. I'll try to work out a patch for Python 2.2.1 tomorrow. Comments? -Barry [1] There's a related problem for when there's no payload at all for a multipart/* message. I think the same fix to Generator._handle_multipart() can be made to handle this case, but fixing the Parser will be a little more difficult. I'll try though. From phd at phd.pp.ru Mon Mar 11 07:48:38 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 11 Mar 2002 15:48:38 +0300 Subject: Homepage of Gadfly not available? In-Reply-To: <3C8CA56B.7050505@med.uni-tuebingen.de>; from rupert.kolb@med.uni-tuebingen.de on Mon, Mar 11, 2002 at 01:39:07PM +0100 References: <3C8C8DA1.5040901@med.uni-tuebingen.de> <20020311140817.L25769@phd.pp.ru> <3C8CA56B.7050505@med.uni-tuebingen.de> Message-ID: <20020311154838.O25769@phd.pp.ru> On Mon, Mar 11, 2002 at 01:39:07PM +0100, Rupert Kolb wrote: > >>for weeks, I'm trying to reach the home page of the Gadfly DB. > >> http://www.chordate.com/gadfly.html doesn't work. > >>Is this my fault? > > > > No, it is down for some time, and probably forever. The original author > > stopped working on it. > > > > Are the sources available somewhere? > Is there a new home page for Gadfly? > Is there anybody who will maintain such a page? My answer is no better than http://sourceforge.net/projects/gadfly/ Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From wade at lightlink.com Tue Mar 5 07:30:03 2002 From: wade at lightlink.com (Wade Leftwich) Date: 5 Mar 2002 04:30:03 -0800 Subject: Python song? (Re: Python isn't necessarily slow) References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> <3C8451E1.B2CD032@cosc.canterbury.ac.nz> Message-ID: <5b4785ee.0203050430.1ab41c9d@posting.google.com> "Tim Legant" wrote in message news:... > Greg Ewing writes: > > > Siegfried Gonzi wrote: > > > > > > Python isn't necessarily slow: > > > > That sounds like a great title for a Python > > song: "It Ain't Necessarily Slow!" > > > > Anyone want to contributes some lyrics? > > Things that you're liable > To read in Deitel & Deitel > Ain't necessarily so... > > Hmm. Not exactly right... > > Strings that you're liable > To search for, from Friedl > Ain't necessarily slow! > > > That's better, > > Tim You say "Free - del", and I say "Fry - del" ... -- Wade From mwh at python.net Mon Mar 25 08:46:25 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 25 Mar 2002 13:46:25 GMT Subject: Memory sizes of python objects? References: <3C9E06A0.EC4D51E3@engcorp.com> Message-ID: Erno Kuusela writes: > | The difference in memory consumption between creating a list > | of size 1,000,000 filled with 0's and the same size list filled > | with integers from 0 to 999,999 is rather large... > > you make it sound more mysterious than it is - only numbers under > 100 and identifier-like string literals get interned, afaik. One character strings too. Also the empty string and the empty tuple. M. -- I'm sorry, was my bias showing again? :-) -- William Tanksley, 13 May 2000 From jbell at iinet.net.au Wed Mar 27 03:31:01 2002 From: jbell at iinet.net.au (John Bell) Date: Wed, 27 Mar 2002 16:31:01 +0800 Subject: Can I use python code to login a website? References: Message-ID: <3CA18345.3020205@iinet.net.au> newgene wrote: > Hi, group, > > I am wondering if possible to use python code to login a website > need username and password, like mail.yahoo.com. Another type of > website is poping up a authorization box asking for username and > password instead of a input form within the webpage. It sure is! The main modules you'll need to look at are httplib, urllib and urllib2. However, web programming is a pretty big topic and it would probably be best to tackle it methodically. Mark Lutz' "Python Programming" devotes several hundred pages to internet scripting. Somewhere on the web (I can't locate the reference at the moment) someone's putting together a Python text processing book. Look in the mail list archives for details. This also has a section on these topics, but from memory not yet written. > > Thanks you in advance. > > Newgene > From cliechti at gmx.net Sun Mar 24 17:18:37 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Mar 2002 23:18:37 +0100 Subject: The OOM-Killer vs. Python References: <3c9e2b5f.9993062@news.t-online.de> Message-ID: gerson.kurz at t-online.de (Gerson Kurz) wrote in news:3c9e2b5f.9993062 @news.t-online.de: > I have a python-based SMTP server (see http://p-nand- > q.com/shicks.htm) > running on our server, and in general it has worked flawless (since > about nov 2001). However, in the recent week that dreaded linux OOM > killer twice killed the python process. [The machine has 768mb ram > call me oldfashioned but that SHOULD be enough for both Linux & > Python > to get along, really. OK, its running KDE, and has only 256mb for > swap, but still...] maybe you have some other leaking app and the OOM killer just picks the largest. if you want a reliable server i wouldn't use it as workstation too :-) > Anyway, even though I believe that this is more of a fault of the > Linux Kernel VM quality than the script (the system has been > running > fine for months and now two kills in one week - that smells fishy you can put the server in inetd.conf or initab so its atleast restarted after the kill (to limit downtime...) > to me) - how CAN I controll the memory usage for pythons GC? Is > there a way to easily find out in python which memory is allocated > at runtime, and by which objects? don't know. you could periodicaly save "top" outputs and see which process grows. chris -- Chris From owen at xastrox.xwashingtonx.edu.invalid Thu Mar 14 12:13:16 2002 From: owen at xastrox.xwashingtonx.edu.invalid (Russell E. Owen) Date: Thu, 14 Mar 2002 09:13:16 -0800 Subject: Why I think range is a wart References: Message-ID: In article , Gon?alo Rodrigues wrote: >For starters, range (and xrange) is a perfectly sensible, reasonable and >useful buit-in. But the biggest use I make of it is in iterating through >a list, e.g. as in > >for index in range(len(mylist)): > > >and in the body I need to make use of the indexes. I am not >sufficiently qualified to say if this is Pythonic or not, but I find >myself doing this quite often. I agree. In particular, I often find myself wanting to deal with items from multiple lists of equal length. Often map or zip would do the job (though at the cost of creating a new list for which I have no use!) but a cleaner way to express it would be appreciated, something like: for item1, item2 in list1, list2 # lots of code here Regarding the suggestion to add the dictionary iterators methods to lists: nice idea. The analogy is nice. If any such methods are added, I'd vote for adding the full suite (iterkeys, itervalues, iteritems...), for consistency. I doesn't completely solve the problem I'm facing, but would clean up the notation a little and it makes plenty of sense. -- Russell -- Return owen address astro garbled washington in header edu From martin at v.loewis.de Fri Mar 15 19:40:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Mar 2002 01:40:43 +0100 Subject: Iterator slicing? References: Message-ID: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) writes: > Or perhaps this is better suited for a specific wrapper in the > (possibly) upcoming iterator module... Hm. I would think so. It is also debatable whether an iterator slice should support indexing, or should be an iterator of its own. I'd say there are applications for both, so just make them functions. Regards, Martin From Dag at animagicnet.no Thu Mar 28 07:19:35 2002 From: Dag at animagicnet.no (Dag) Date: 28 Mar 2002 12:19:35 GMT Subject: webmin modules in python Message-ID: I've started working on a webmin (www.webmin.com) module. However I would really like to write it in python rather than perl, which seems to be the standard. However webmin seems to assume that all modules are to written in perl and thus all the common functions come from perl scripts. Has anybody written a python wrapper or found any other way to easily write python modules for webmin. I suppose I could write a perl 'middleware' broker which sends commands between webmin and my python script, but I was looking for a clean sollution. Dag From ralph at inputplus.demon.co.uk Sun Mar 24 05:38:43 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 24 Mar 2002 10:38:43 GMT Subject: Python-2.2.1c1 Build Problems on Linux and AIX. References: Message-ID: Hi, > > With Python-2.2.1c1, I find `make test' fails on my old version of > > Linux/x86 and it fails to build on an also old version of AIX. ... > > I can see the problem with the AIX build. Linux SIGSEGVs in > > test_calendar on a call to strftime. OK, I've raised all the AIX problems on SourceForge now. By working around them I can get a python executable and most of the library. (Modules/_cursesmodule.c fails to compile but I'm not sure if is intended to be widely buildable.) The Linux/x86 problem has also been fixed and thanks to Tim an overall improvement made, e.g. month_name[0]. Thanks for everyone's help, Ralph. From Chris.Barker at noaa.gov Fri Mar 8 15:10:59 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Fri, 08 Mar 2002 12:10:59 -0800 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> <2030665d.0203070126.55addc33@posting.google.com> <3C87A28B.549D9B1C@noaa.gov> <2030665d.0203080406.5b1b008b@posting.google.com> Message-ID: <3C891AD3.ADA924B5@noaa.gov> Sam Collett wrote: > > How would you remove trailing 0's? > e.g. > Instead of 12.20kb it would be 12.2kb > 23kb instead of 23.00 etc I don't see a way to do it with format specifiers. %g doesn't print trailing zeros, but it goes into exponential notation for larger values. If you were sure if your values, you might be able to use it. Otherwise, you can write a little function with string methods (or maybe even a regular expression) that would strip them off for you. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From tejarex at yahoo.com Sat Mar 9 15:46:35 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 09 Mar 2002 20:46:35 GMT Subject: List of lists: caveat? References: Message-ID: "George Thomas" wrote in message news:Pine.LNX.4.44.0203091505530.12114-100000 at laureloak.cc.gatech.edu. .. > Hi everyone, Hi. > I just tried creating a 2D array the 'list-of-lists' way as follows: > two_d_array = [ [0] * 20] * 10 # Creates a 10 * 20 array -- (I) This creates a list (which I will call 'tda' hereafter) of 10 *identical* references to the *same* inner list object. And, similarly, the inner list consists of 20 *identical* references to the *same* integer object with value 0. You can verify both statements with id(object). You do not notice the inner sameness as much because a statement such as > two_d_array[0][3] = 1 # Sets element [0][3] to 1 destroys that sameness, but leaves the outer sameness untouched. > I expected nothing unnerving, except that > print two_d_array[1][3] > gives me 1 > as does print two_d_array[any valid index from 0 to 9][3] Since tda[0] is tda[1] ... is tda[9] by construction, and you have not changed it, why would you expect elsewise? (;<) If that sameness is not what you want, construct differently: tda = [None]*10 for i in len(tda): tda[i] = [0]*20 You now have 10 *different* references to 10 identity-different but value-equal lists, which you can independently modify. Again, use id() to check. Terry J. Reedy From gh_pythonlist at gmx.de Wed Mar 20 23:34:39 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 21 Mar 2002 05:34:39 +0100 Subject: Python & IRC In-Reply-To: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> References: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> Message-ID: <20020321043439.GA2043@lilith.hqd-internal> * Felix [2002-03-20 23:07 -0500]: > Greetings everyone, > > I'm not sure if you guys here might be able ot help me but i have been > looking up and down for a irc client that allows me ot script in > python. I've also looked for such a thing but haven't found anything usable. > I found one but it doesn't seem that the owners of this client are > making any type of head way in it's development. I know Xchat allows > to use python as a scripting language but that is with the linux > version not windows. xchat's Python support sucks. They even admit it in the docs. Btw. where's the problem in building Xchat with Python support yourself on Windows? Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 12.1 ?C Wind: 9.3 m/s From matthias_j at lycos.com Fri Mar 1 12:08:22 2002 From: matthias_j at lycos.com (Matthias Janes) Date: 1 Mar 2002 09:08:22 -0800 Subject: Can't seem to get it right: Win NT registry save and load Message-ID: Hi I would like in a python script to save a Win NT Registry entry to a file and load it later - but it's seems I can't get it right. win32api.RegSaveKey RegSaveKey(key, filename, sa) I could not realy figure out the 3 part (sa ) get always a error about the security rights. after I saved it how could I load it again? Any Help would be real nice. Matthias Janes From herrn at gmx.net Mon Mar 25 18:13:40 2002 From: herrn at gmx.net (Marco Herrn) Date: 25 Mar 2002 23:13:40 GMT Subject: starting a python program from within xemacs Message-ID: <1017098019.357959@DS9.ai-lab.fh-furtwangen.de> Hi there, sorry if this is the wrong newsgroup to ask, but I tried in comp.emacs.xemacs and nobody could help me, probably because too few people there code in python :-) I develop a program that uses the curses library in xemacs. But for testing my program I have to save it in xemacs, switch to a terminal and call python myprog.py. Because I use curses, a C-c C-c doesn't work because the xemacs output window isn't capable of using curses. Is there a way to execute the content of my current xemacs buffer in a terminal/x-terminal? Bye Marco -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From peter at engcorp.com Tue Mar 26 22:59:51 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Mar 2002 22:59:51 -0500 Subject: Deeply embedded Python still alive? References: Message-ID: <3CA143B7.DED16DF5@engcorp.com> Grant Edwards wrote: > > > On Tue, 26 Mar 2002 17:10:10 GMT, grante at visi.com (Grant Edwards) wrote: > > > >>The link I have for the Deeply Embedded Python port > >> has been broken for > >>several months now. Anybody know what happened to that > >>project? > Further googling found this paper describing the project: > > http://www.tucs.fi/Magazin/Page.cgi?ID=2000.N2.LilDeEmPy Thanks for the link, Grant. In case anyone is remotely interested, between 1.5 and 1 year ago we were deeply into porting Python to our own PC104-based environment which at the time was a 386SX board with 1MB of RAM and 1MB of flash, running at 33MHz. For a variety of reasons, listed below, we abandoned the project after prototyping and have since moved on to a higher powered board (thankfully we had that option) running standard Linux and standard Python, now with 32MB RAM and CompactFlash modules (currently the image is around 24MB) on a 100MHz 486. The main reasons for leaving the embedded effort were, in descending order of importance to us: 1. Non-standard persistent storage: 1MB flash could not be treated as a hard drive and code had to run from RAM while reprogramming it. With CompactFlash under Linux we just see a small hard drive and use open(). 2. Performance: Python on a 33MHz 386 is just not the fastest thing on the planet, and more to the point was insufficient for our needs. If (1) hadn't been a killer this would have. 3. Cost of supporting our own proprietary port: I mean proprietary in the sense of we had to worry about it, not that it had to remain closed. Going standard let's us get the application out faster and moves us faster towards contributing source back to the community (which in the interim I thank most earnestly for the shoulders we're standing on and ask patience for those like us who have to take time working on ancient corporate attitudes and first-to-market concerns before we can give anything back). The most beautiful thing about the whole effort is that it took almost no effort to "port" our code from the experimental platform to the current one. Python is easily the most portable language I've had the good fortune to program in. The only changes we made were for low-level code which interfaced to a dual-port memory, the serial port interface code, and some low-level locking/ messaging code which we "mocked" for a while until we refactored and ditched the old stuff since it was made almost entirely redundant by Queue and friends. Just thought I'd share while we're on the subject... -Peter From djc at object-craft.com.au Thu Mar 21 02:17:20 2002 From: djc at object-craft.com.au (Dave Cole) Date: 21 Mar 2002 18:17:20 +1100 Subject: ANN: Logging Module v0.4 released References: <2e37dc1.0203201754.50a15e80@posting.google.com> Message-ID: >>>>> "Richard" == Richard Jones writes: Richard> On Thu, 21 Mar 2002 12:54, Vinay Sajip wrote: >> A new version of the proposed Python standard logging module (as >> per PEP 282) has been released. You can get all the information >> from Richard> Having looked at the excellent work being done here, I wonder Richard> what's happening at the other end of the pipeline. That is, Richard> what's listening for the events that the logger is Richard> generating? Has anyone got any plans to write a logging sink Richard> for the other end? Richard> The sink would perform the following duties: - accept events Richard> from the logging module via all the logging module's handlers Richard> - present a display of the events to a user, either Richard> graphically or textually (the most basic of these would Richard> resemble the UNIX tail -f) - redistribution of events to Richard> other targets - filter incoming events, possibly aggregating, Richard> possibly dropping - have state which would be affected by the Richard> filters and may cause new events to be generated Richard> (ie. escalation) Richard> Anyone think this is a good idea? I don't think this is a good idea. I think this is a great idea. - Dave -- http://www.object-craft.com.au From geoff at gerrietts.net Thu Mar 7 14:34:47 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 7 Mar 2002 11:34:47 -0800 Subject: hotmail In-Reply-To: References: Message-ID: <20020307193447.GD29379@isis.gerrietts.net> Quoting Bertrand Geston (bergeston at yahoo.fr): > Seems to be magic, thanks for the question and for the response. Really > interesting. > I would like to retrieve mails from Hotmail and I wonder if it is not > 'better' to use COM/DOM on Outlook express that can, if I am not mistaken, > retrieve mails from Hotmail using http requests. By 'better', I mean less > linked to the hotmail site layout (but OK linked to the Oultook DOM > interface) and probably quicker. > > Any thought, idea, code snippets ? I did some research on this once upon a time, and I think Outlook Express actually uses POP, but the POP authentication is hooked into the Microsoft Passport system. And I think newer versions of Outlook are supposed to support Hotmail, but older versions don't. I was able to locate one (commercial) product that would fetch mail from Hotmail as if it were an Outlook Express client, but it was a Windows product and I was really wanting something I could use on Linux. I settled on gotmail and moved my free email to yahoo, where they let you POP if you agree to let them spam you with ads, but stuff still trickles into my hotmail -- give me a shout if you get something working "the hard way"! Hope the little bit of informational content in this message helps.... --G. -- Geoff Gerrietts "Ordinarily he was insane, but he had lucid moments when he was merely stupid." --Heinrich Heine From Tjabo.Kloppenburg at unix-ag.org Sat Mar 23 06:56:04 2002 From: Tjabo.Kloppenburg at unix-ag.org (Tjabo Kloppenburg) Date: Sat, 23 Mar 2002 10:56:04 -0100 Subject: Extending the interactive mode [not really an ANN :) ] Message-ID: hi, I use python22 and dreamt about a comfortable way of using the interactive mode to find information about what methods/functions a class/module provides and what the helpful __doc__ string says (keeping ri [ruby] in my mind). The annoying way to do this in python interactive mode -- with lots of key strokes and many risks of mistypnig -- is to type: print mod.__doc__ +Enter print dir(mod) +Enter So I finally wrote a very small function to be loaded from PYTHONSTARTUP when using interactive mode. It is self explanatory and gives you information about a module by typing "info(mod)". Fairly easy... The mighty source: # Author: tk at bitsex.de aka tapo in #python # # this is a small function you can load when starting python interactivly: # - put it into ~/.pythonstartup # - do an "export PYTHONSTARTUP=$PYTHONSTARTUP:~/.pythonstartup # - restart "python" or "python22" without arguments # - now type: "info(info)" +enter :-) def info(mod): "\nThis is a small function to show some info about a module.\nUsage in python interactive mode:\n import sys\n info(sys)" print "Info for module/class '%s':" % (mod.__name__) print mod.__doc__ print "\nList of methods:" print dir(mod) Always on a mission to save the world, tk. :-) -- + 7jaB0 Kl0ppE|\|8\_/R6 + 7|<@B175Ex.[}E + [}3,3n + From peter at engcorp.com Thu Mar 7 08:15:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Mar 2002 08:15:57 -0500 Subject: PEP 284, Integer for-loops References: Message-ID: <3C87680D.CC8A546C@engcorp.com> Jonathan Hogg wrote: > > On 6/3/2002 16:41, in article > eppstein-BB3186.08413106032002 at news.service.uci.edu, "David Eppstein" > wrote: > > > One of the most common uses of for-loops in Python is to iterate > > over an interval of integers. [...] > > Is it that common? > > I did a quick grep over the 2.2 library and found that around 10% of for > loops used range. Of course, the library is pretty unrepresentative code > since, by design, it contains all the stuff you *wouldn't* want to do > yourself. > > I did the same grep over the random Python code in my projects directory and > found that 3% of my for loops use range. This was 12 ranges out of 408 loops > in about 18,000 lines of code. > > 12 times in the last 18,000 lines of code I've had to loop over a range. > > Am I unusual in saying that I really don't care? I don't think so, at least among programmers approaching Python programming in a Pythonic fashion. :-) I think I rarely use for with a range any more, because I tend to think "if I need to do something eight times, there are probably eight things I'm doing something to so I should just take those things and iterate over a list of them". And it's rare to have to prepare a list of exactly eight things (which would need the for/range since you don't have the "things" already). I don't care either, and in fact I care so little that I am against the PEP because it adds unnecessary clutter to special cases etc. as mentioned by others. -Peter From eppstein at ics.uci.edu Fri Mar 8 11:57:42 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 08 Mar 2002 08:57:42 -0800 Subject: PEP 284, Integer for-loops (code bash?) References: Message-ID: In article , Laura Creighton wrote: > By the way, for your students, what keeps you from doing this: ... > for index, value in zip(_indices, someList): > whatever_you_want() I find "for i in range(len(list))" adequate for looping over indices of a list. But much of the time, when I want to loop over integers, it's part of some dynamic program where the integers I want to loop over aren't the index set of any list, are in backwards order, aren't half-open intervals, etc., and the range syntax becomes more cumbersome. From emile at fenx.com Fri Mar 22 07:04:48 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 22 Mar 2002 04:04:48 -0800 Subject: How to set the Timestamp of a File References: Message-ID: J?rg Sch?tter > How can I set the timestamp of a file (especially under windows) with > python? In Unix/Linux there is a tool caled touch. > There is no problem to read the timestamp, but how can I set the > timestamp to a desired time? >>> print os.utime.__doc__ utime(path, (atime, utime)) -> None utime(path, None) -> None Set the access and modified time of the file to the given values. If the second form is used, set the access and modified times to the current time. HTH, -- Emile van Sebille emile at fenx.com --------- From hgg9140 at seanet.com Mon Mar 11 19:47:46 2002 From: hgg9140 at seanet.com (Harry George) Date: 11 Mar 2002 16:47:46 -0800 Subject: Rule Engine in Python References: Message-ID: lee.ingram at 432one.com (Lee Ingram) writes: > I have used Google to scour the web looking for an implementation of a > rules engine using Python. I need a mechanism whereby slightly trained > end users will be able to add / modify business rules and have them > execute. I previously used Blaze Software's Advisor rules engine to do > something similar. Has anyone seen, implemented, or tossed out this > idea previously? > If you are willing to use prolog as the rules language, there are python/prolog bindings (e.g., SWI prolog). We use python and prolog jointly in a C++ CADenvironment. > Inquiring minds want to know... > > TIA > > Lee Ingram -- Harry George hgg9140 at seanet.com From gh_pythonlist at gmx.de Sun Mar 17 21:20:07 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 18 Mar 2002 03:20:07 +0100 Subject: Windows Installation In-Reply-To: References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> Message-ID: <20020318022006.GB80883@lilith.hqd-internal> * Jonathan Gardner [2002-03-16 15:29 +0900]: > [...] > 2) Can someone on this list help me (by writing the installer for me?) > [Note: this is a plea for help out of desperation]. I'll have a look next time I reboot to Windows. Have been in FreeBSD for the whole weekend :) > Gerhard H?ring wrote: > > NSIS rocks. But AFAIR his problem is that he doesn't have a Windows > > box to build the installer on. > > > > What is NSIS? Google. First hit. Btw. I've installed WINE on FreeBSD 4.5-STABLE this weekend *without* using an existing Windows installation. I could install NSIS on FreeBSD using WINE and I can build installers here with it. No problem :) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 8.0 ?C Wind: 1.6 m/s From peter at engcorp.com Wed Mar 20 00:08:49 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Mar 2002 00:08:49 -0500 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> Message-ID: <3C981961.9F5E5383@engcorp.com> Ahmed Moustafa wrote: > > Peter Hansen wrote: > > Ahmed Moustafa wrote: > >>1. Where can I find an unbiased comparison between Java and Python? > >>2. Will Python dominate? > >>3. Who does support Python? [...] > > I think if you told us what your purpose is in asking the questions, > > the answers would be more useful and direct. _Why_ do you want > > to know? > > I'm interested in knowing which skills will(are) being looked for. Thanks for the clarification. In that case, these would be my answers to you: 2. Python will not dominate, any more than any other language will. Python is certainly in a growth period, but it seems unlikely it will attain the mass acceptance of Pascal, C, C++, and Java in their day. (Not to imply that Java's day has passed... that much is evident from the number of bookstore shelves devoted to it!) But who cares? If you go where the mass unwashed go, you'll get the same sorts of mundane and rote jobs as the mass unwashed do. 1. As others have said, there is no such thing as an unbiased comparison of almost anything, let alone programming languages, let alone two with such, uh, "dedicated" users as Java and Python. Nevertheless, even if we could find such a thing, the response would really depend entirely on the application area. Clearly Java is better suited for some applications, and Python for others. Without defining the type of work you want to do, any comparison is meaningless. (E.g. "Python programs tend to be much more readable" doesn't matter if your job involves writing Java on a Java team doing EJB stuff, unless you can get the whole team to use Jython instead.) 3. The best support for either Java or Python is probably in their respective newsgroups. Python's is widely known as being one of the most polite and helpful. The language has been around a little longer as well, and as it's not largely a commercial venture this might suggest that the "support" question is a bit of a red herring. Do you regularly contact the Microsoft for help with VB, or Sun for help with Java? (Or did you mean who is "backing" the language, ensuring its continued viability. The answer to that is twofold: look at the 11+ year age of Python as historical proof it's not a flash in the pan, and note it's _open source_ so it cannot, by definition, lose viability while people support and use it. You can always get the source.) Here's my best answer to you: I happen to hire programmers to work on my team in a wireless telecom company. Although we happen to have chosen to use Python in addition to C and a few minor languages like Javascript and Assembly, where necessary, the language we use is hardly the most important thing. Communication skills are, first and foremost, the thing I look for in hiring. This includes the softer social skills like how to work in a team and put aside one's programming ego. Next are adaptability, as in how easily someone can pick up new skills and apply them effectively. Design skills are useful. Debugging skills are very valuable, though rather unfortunately rare. Probably some others that don't come to mind in today's economy (we're not hiring now :-). Way, way down the list of things I look for in a resume is the programming languages a candidate has. Not entirely unimportant, but useful only taken as a whole. I don't care whether somebody knows Python, and have found and hired only one such programmer yet (and not because he knew Python). The others had a variety of backgrounds including Java, C++, Delphi, VB, C, BASIC, assembly of various kinds, and so forth. Those with only a single language, or maybe two, probably didn't get hired. Those with a dozen were more able to demonstrate their flexibility to me. When they were hired, they went to work learning Python. About a week later, most of them were already contributing in a productive way. A month later any of them could code Python as well as they could code in any of their previous languages. For the most part, I would have expected the same of them even if we used Java (though perhaps with a somewhat longer learning curve). The point is, I would never hire you or anyone _because_ you knew Python, or Java. I would hire you because I thought you were capable of learning it and using it effectively. I actually tend to shy away from people with great lists of "certifications" in languages because it suggests to me they have difficulty learning and think it's a very impressive thing that they managed to learn enough to write an exam which tests knowledge of syntax but little about programming skill. My suggestion then is to "get over" the comparison thing, and make sure you know both, and throw in others as you come across them and have opportunity to learn. This will make you a better programmer, because of the learning and generalization your brain will do, not because of the specific skills you have. Not all companies hire in this way, of course, but all the best ones do. :-) -Peter P.S.: If you are considering Python as a massive growth area where ex-Java programmers can go to get lucrative jobs, you're bound to be disappointed. As in programming, there is no silver bullet. From tejarex at yahoo.com Mon Mar 11 11:20:27 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Mon, 11 Mar 2002 16:20:27 GMT Subject: Is Python an object based programming langauge? References: Message-ID: "Graz Bukanoff" wrote in message news:f240ab4a.0203110731.3e5bec3c at posting.google.com... > Is Python an object based programming langauge? Given that everything in Python *is* an object, yes. In addition. its class/instance system is nice for learning OO programming. On the otherhand, OO fanatics might demur, since it does not force an OO programming style and allows procedural and even functional styles. Most of us are more concerned that it is a good-to-program-with language. Terry J. Reedy From ralph at inputplus.demon.co.uk Sun Mar 31 17:16:37 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 31 Mar 2002 22:16:37 GMT Subject: PEP 285: Adding a bool type References: Message-ID: Hi, > [Ralph Corderoy, to Guido] > > What do you think of `truth(x)' for all the good reasons listed > > elsewhere in the thread? You used truth yourself instead of > > Boolean above. > > Actually, he didn't. Yes he did. You just snipped it so you'd have something to say ;-) Guido wrote: "IMO, bool(x) is the right way to "normalize" any value into a truth value." So there he is, using `truth' as opposed to `any value into a Boolean value'. Ralph. From ykingma at accessforall.nl Tue Mar 26 15:59:37 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Tue, 26 Mar 2002 21:59:37 +0100 Subject: [OT] Re: Programming Puzzle for you Experts out There References: <3c9fa91e.506871@news.earthlink.net> Message-ID: <3CA0E131.77BD2E8D@accessforall.nl> Joe, you wrote: > > First a little background: > > I'm in the process of writing a fatigue and damage tolerance analysis > program using python. One of the things the math engine can do is > compute the remaining strength of the material after it has sustained > damage. However, there are two problems: > > 1) Redisual strength is influenced by two competing physical > properties of the metal. So far, nobody has developed a method for > evaluating the transition between these properties so the conventional > wisdom is to "eyeball" a curve between them. > > 2) Sometimes, the damage or fatigue involves a "ligament break", this > will suddenly change the stress field and, not surprisingly, cause a > step change in the residual strength curve. > > So here is the problem...... > > I have two vectors that, when plotted against each other are mostly > smooth with occasional inflection points and step changes. I want to > keep the step changes but inscribe a smooth arc below the inflection > points that will eventually be tangent to the intersecting curves. > > Now, here is the hard part...... > > To get the boundary conditions, I must sample the vectors "as is". > Re-iterating the numbers to get better data will require me to go back > into the math engine which will suck up processor time. > > I've tried 4th order polynomial fits and hyperbolic fits but neither > have been robust enough to track all of the fracture scenarios I've > thrown at it without Gibb's overshoots or other issues. I have not > tried Fourier or other series fits as of yet. Probably try that next. > It's been quite a while that I did numerics, but this sounds like good fun. Some questions on finding the fractures: - how much noise is there in your data? - do you need those higher order techniques? - would the abs of the raw second time derivative provide enough information? - or even the abs of the first time derivative? A simple iteration might work like this: - fit the data to some smooth function, - stop when the fit is good enough, otherwise: - split the data on the few the most distant outliers, - recurse on the split off parts. With some heuristics you might even make the total amount of work close to linear in the number of points, eg. by always having a limited number of fractures in the data you are working on. Regards, Ype From thoa0025 at mail.usyd.edu.au Sat Mar 30 21:29:34 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 31 Mar 2002 02:29:34 GMT Subject: python cgi design patterns? References: Message-ID: no patterns? what a shame :( "Trung Hoang" wrote in message news:iDap8.1563$hi7.3406 at news-server.bigpond.net.au... > Greetings, > > im looking for python cgi design patters. does anyone have any cool urls? > i've found 1 and it's quite nice. > > http://www.webtechniques.com/archives/1998/02/kuchling/ > > Cheers > trungie > > From d95-bli.no at spam.nada.kth.se Tue Mar 5 17:19:23 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-1?Q?Bj=F6rn?= Lindberg) Date: Tue, 05 Mar 2002 23:19:23 +0100 Subject: Order of constructor/destructor invocation References: <3C8466F9.2080903@jerf.org> <_f7h8.5541$aP6.6480@rwcrnsc54> <3C851D41.3000902@jerf.org> Message-ID: <3C85446B.B389BB0F@spam.nada.kth.se> Jeremy Bowers wrote: > non-interpreted languages don't specify it either. In fact, even IF > C/C++ specifies the destructor order, which I don't care to look up > right now, I would not be surprised that not all compilers will destruct > in that order at the end of a function. You're thinking of C++, and yes, the destructor order is well-defined, and yes, all standards conformant compilers will follow this practice. In fact, this is often used eg to manage resources. I agree that the original approach doesn't look incredibly useful though. Bj?rn From grante at visi.com Thu Mar 14 23:43:35 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Mar 2002 04:43:35 GMT Subject: how to check how many bytes are available to read() ? References: <2b57f654.0203142026.68ec3fc7@posting.google.com> Message-ID: In article <2b57f654.0203142026.68ec3fc7 at posting.google.com>, wealthychef wrote: > I have a file object f. I want to know if there are any bytes > to read from it. A worthy and not infrequent desire. > I have tried using select.select([], [f], []), That will return when f is writable. In other words write(x) will not block. At least not for some values of x. If you do select.select([f],[],[]), then it will return return when f.read() will not block. Note: calling read() on a regular file never blocks, therefore select() returns immediately for regular files. > but I have found that select will return [],[f],[] even if > there is nothing to read in f, so that when I call > f.readline(), it blocks. Call select.select([f],[],[]) > Is there a function or some way i can peer into f and see if > it has any bytes for me? > > f is actually someprocess.fromchild, by the way. If f is a pipe, then you can use select -- at least under Unix. I don't know about Windows. -- Grant Edwards grante Yow! .. Like I always at say -- nothing can beat visi.com the BRATWURST here in DUSSELDORF!! From jmarshal at mathworks.com Mon Mar 18 16:50:08 2002 From: jmarshal at mathworks.com (Joshua Marshall) Date: 18 Mar 2002 21:50:08 GMT Subject: Initialization of base classes References: <52mc9u0ghanm3bg0ajt8aro58bqce6ki2s@4ax.com> Message-ID: I believe it's the case that __init__ is just called on the object created. So standard method-lookup rules apply. sorry.antispam at address.net wrote: > On pp 74 of Bealey's excellent book "Python Essential Reference, 2nd > Ed" it is written: > "When an instance is created [of a derived class], the __init__() > methods of base classes are not invoked. Thus, it's up to a derived > class to perform the proper initialization of its base classes, if > necessary" > Is this really true? If you have: > class A: > def __init__(self): > print "Class A" > class B: > def __init__(self): > print "Class B" > class C(A): > pass > class D(A, B): > pass > Then: > w = A() --> "Class A" > x = B() --> "Class B" > y = C() --> "Class A" > z = D() --> "Class A" > Hence, instantiating class C does in fact invoke the constructor of > class A, but not of class B. i.e., only the constructor of the first > base class is invoked. Is this a bug in the book, or a bug in Python > 2.1? > And if it's not a Python bug, what is the rationale for only calling > the constructor of the first base class, and not the other base > classes? > ...Edmund. From pajer at iname.com Thu Mar 14 23:05:45 2002 From: pajer at iname.com (Gary Pajer) Date: Fri, 15 Mar 2002 04:05:45 GMT Subject: Good book on Python? References: Message-ID: > > >I recently bought "Programming Python" by O'Really, > > > > Oh. Really? > > http://bofhcam.org/co-larters/index.html Incredible. One can't invent something new anymore, even by accident. I attended a lecture by Feynman once. He said that some years ago he made a new discovery in E&M theory. He later found out that someone had beaten him to it by about 25 years. His advice from the experience: "If you ever think you've discovered something new, think again." BTW, my $0.02: I like PP2E, and, oddly, I find "Python and XML" (also from Oh'Really) to contain some lucid descriptions of Python at my level (novice). Not a broadly based intro, however. From bokr at oz.net Thu Mar 28 21:46:45 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Mar 2002 02:46:45 GMT Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: On Thu, 28 Mar 2002 18:09:39 -0500, "Steve Holden" wrote: >"John Machin" wrote ... >> philh at comuno.freeserve.co.uk (phil hunt) wrote in message >news:... >> > On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen >wrote: >> > >Jim Dennis wrote: >> > >> freq = {} >> > >> if word in freq: freq[word] += 1 >> > >> else: freq[word] = >1 >> > >> > >Something like freq[word] = freq.get(word, 0) + 1 >> > >> > IIRC in Awk you can just say: freq[word] ++ and it works >> > correctly even when there is no pre-existing index of word in freq. >> > >> > IMO it's a pity Python isn't like that. >> >> Python *could* be made like that with the explict dict() constructor >> ... something like: >> >> freq = dict(default=0) >> ... >> freq[word] += 1 > >This was a feature of the Icon language. But Icon had no explicit literal >representation for dictionaries (or tables, as I think they were called) as >far as I can remember, so it was easy to make the default value an argument >to a constructor function. It's not obvious how you could indicate the >default without calling a method. > empty_dict_with_default = {:default} with_one_key_value_pair = {:default, key:value} A little tweak in the grammar might do it? Regards, Bengt Richter Regards, Bengt Richter From dreed at capital.edu Tue Mar 12 18:17:42 2002 From: dreed at capital.edu (Dave Reed) Date: Tue, 12 Mar 2002 18:17:42 -0500 Subject: frustrated stupid newbie question In-Reply-To: (skurland@juggler.net) References: Message-ID: <200203122317.g2CNHgP21810@localhost.localdomain> > From: "Scott Kurland" > > Why isn't this $%^*#$% program working? > > #Searching for perfect numbers > > howhigh= input ("How high should I check?") > for number in range (1,howhigh): > factorsum = 0 > halfnumber=number/2 > for checking in range (1,halfnumber): > if number/checking == int (number/checking): > factorsum = factorsum + checking > if number == factorsum: > print number > > > > Flame away, I can't feel dumber than this. Two problems I see: number / checking does integer arithmetic. Try starting up the python interpreter and type: 5 / 2 Use: if number % checking == 0: this determines if the remainder is zero. Also, you need to go one past the half number since 2 is a factor for even numbers so you'll want the other factor. Again, with the python interpreter, type: range(1, 10) Try this: howhigh= input ("How high should I check?") for number in range (1,howhigh): factorsum = 0 halfnumber= number / 2 + 1 for checking in range (1,halfnumber): if number % checking == 0: factorsum = factorsum + checking if number == factorsum: print number Also, see: http://home1.pacific.net.sg/~novelway/MEW2/lesson1.html Dave From wilby31 at yahoo.com Wed Mar 27 14:54:16 2002 From: wilby31 at yahoo.com (wilby31) Date: Wed, 27 Mar 2002 19:54:16 -0000 Subject: new to python... Message-ID: Im running Linux and I would like to run a filename.py file..how do I go about running this program? through the command line ? I have version 1.5.2 and I do not have the control to upgrade it. thanks brent From skip at pobox.com Wed Mar 27 19:37:25 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Mar 2002 18:37:25 -0600 Subject: The Python Way Message-ID: <15522.26053.182066.263337@12-248-41-177.client.attbi.com> I wrote that I should look at replacing code like this self.cache_lock.acquire() try: fiddle_some_cache... finally: self.cache_lock.release() with code like this some_cache = self.some_cache_queue.get() fiddle_some_cache... self.some_cache_queue.put(some_cache) I eventually realized I can avoid the try/finally however. If something happens within fiddle_some_cache... in the second code example I'd wind up with an empty queue. So, if I needed try/finally in the acquire/release case, I will need it in the get/put case. Silly me... Skip From brian at sweetapp.com Fri Mar 15 04:03:51 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 15 Mar 2002 01:03:51 -0800 Subject: XML-RPC Question In-Reply-To: Message-ID: <005f01c1cc00$53588120$445d4540@Dell2> Jesper Olsen wrote: > Yes that works too. > I think it would be useful if the register_instance, registered > the name of the object as part of the method names, e.g. > > server.register_instance(MyClass(), "myob") You can create arbitrary hierarchies pretty easily using classes (not tested): class Container: myobj = MyClass() server.register_instance(Container) > It would then be clear to the client, that it is calling methods > on an object: > > server.myob.helloWorld() > server.myob.echo() > > I this example it does not matter much, but usually objects have a > state, whereas function calls give the impression of something state-less. > Of course the same can be achieved by registering these functions > individually: > > server.register_function(myob.helloWorld, "myob.helloWorld") > server.register_function(myob.echo, "myob.echo") I'm not sure that people have this sort of expectation. I certainly don't. Cheers, Brian From emile at fenx.com Thu Mar 21 10:17:54 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 21 Mar 2002 07:17:54 -0800 Subject: Java and Python References: <3C996234.9090506@verizon.net> <852630CB444A0E88.1C47E73805633E2D.6D8C67A72D42A034@lp.airnews.net> Message-ID: Cameron Laird > So, for example, I've heard that Python isn't as serious > as Java because it's not possible to hire "Zope-certified > Python Engineers". Sun does that for Java, Zope doesn't > for Python, therefore Python isn't as trustworthy as > Java. > When the day arrives that demand for certification from paying applicants outstrips supply -;), then I'm certain that many qualified certifiers will step up to the plate. The hard part will be determining what certified means. Perhaps there's a PEP in that. -- Emile van Sebille emile at fenx.com --------- From h_schneider at marketmix.com Mon Mar 11 09:25:09 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Mon, 11 Mar 2002 15:25:09 +0100 Subject: Homepage of Gadfly not available? References: <3C8C8DA1.5040901@med.uni-tuebingen.de> <20020311140817.L25769@phd.pp.ru> Message-ID: Maybe this helps: http://www.zope.org/Members/mcdonc/RelationalDatabaseWiki/GadFly http://cvs.zope.org/Products/ZGadflyDA/gadfly/#dirlist All the best, Harald "Rupert Kolb" schrieb im Newsbeitrag news:mailman.1015850417.6509.python-list at python.org... > Oleg Broytmann wrote: > > On Mon, Mar 11, 2002 at 11:57:37AM +0100, Rupert Kolb wrote: > > > >>for weeks, I'm trying to reach the home page of the Gadfly DB. > >> http://www.chordate.com/gadfly.html doesn't work. > >>Is this my fault? > >> > > > > No, it is down for some time, and probably forever. The original author > > stopped working on it. > > > > Then the next questions: > > Are the sources available somewhere? > Is there a new home page for Gadfly? > Is there anybody who will maintain such a page? > As far as I can remember there is some software, which needs gadfly. > > -- > Rupert Kolb > > > From jgardn at alumni.washington.edu Wed Mar 6 10:32:02 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Thu, 07 Mar 2002 00:32:02 +0900 Subject: Flushing stdout with raw_input - BUG References: Message-ID: Michael Hudson scribbled with his keyboard: > Jonathan Gardner writes: > >> I will write >> another bug report about the unresponsiveness to bug reports as well, as >> there are a lot of bugs that aren't even addressed at sourceforge. > > Oh, that will help, sure. It is a bug. There needs to be a fix for it. Do you need more volunteers? How do we get involved? Where do we sign up? What needs to be done? Maybe there needs to be more coordination and less coding at the top. I did a semi-thorough investigation on the matter, and there really isn't much information on how I make the move from being a python user to a developer. Apparently it's by invitation only. Do I just keep submitting bugs and patches and opinions and eventually someone will notice me, or do I have a place where I can stand up and say, "HEY! I WANT TO HELP! WHAT DO I DO?" > > Please note that Python is a volunteer effort. You have no right to > expect bug reports to be attended to. > I can expect what I want. I have no right to see my expectations fulfilled, unless I do the fulfilling. I understand that it is a volunteer effort. I am constantly appreciative of the effort you and others are putting into it. (http://sf.net/forum/forum.php?forum_id=154889) However, we can't go around saying Python is substandard because it is a volunteer effort. We should be saying we are held to a higher standard because we are a volunteer effort. Unlike Java or C#, we actually have to perform, because we don't have a huge advertising fund and pushy salespeople. > > However, they are. I know *I* scan through open bugs fairly > regularly. Martin von Loewis does the same. I can only fix the bugs > I have time to fix, and so fix the bugs that seem to me to be worth > fixing. I've spent multiple hours in just the past few days with my > head stuck deep in the Python internals, and TBH posts like this do > not make me think it was worth it. > The way I was tutored was that getting a bug report was a *good* thing. Anybody who thinks there are no bugs or few bugs should be shot. A programmer should appreciate a well-written bug report because it helps improve the code and lets him spend more time coding and less time testing. I tried to be strikingly clear, because this has been brought up before and it seemed to have been regarded as unimportant. I wanted to emphasize that at least in my opinion it is important, and shouldn't be shoveled off to the side. And TBH, are you doing this for yourself or for us? If you are doing it for us lusers who are unappreciative and consistently complaining and calling features bugs, then I am surprised you are still around. > > If you are interacting with a subprocess that is expecting to talk to > a user, you should probably be using pseudo-tty's. > That is a very good answer that I didn't think of. I did a search on Google and came up with the expect module for python located at http://sourceforge.net/projects/expectpy/ Still, not quite what I was looking for, but since C seems to do exactly what Python is doing, then maybe I need to help them at pyexpect and forget about making Python behave differently from C. That way, there won't be that nasty gotcha when they go and run a C program. I think I'll stop complaining about raw_input and start working with the expectpy group. Jonathan From cpbotha at i_triple_e.org Wed Mar 20 10:57:26 2002 From: cpbotha at i_triple_e.org (Charl P. Botha) Date: Wed, 20 Mar 2002 15:57:26 GMT Subject: Develop-test-debug cycle References: <24bh9u4lmkj47e1jufc1c26od21gd0eq50@4ax.com> Message-ID: In article <24bh9u4lmkj47e1jufc1c26od21gd0eq50 at 4ax.com>, Dale Strickland-Clark wrote: >>It seems to work here: >> >>[niemeyer at ibook niemeyer]$ echo 'a = 1' > mod.py >>>>> import mod >>>>> mod.a >>1 >> >>[niemeyer at ibook niemeyer]$ echo 'a = 2' > mod.py >>>>> reload(mod) >> >>>>> mod.a >>2 > > This is a rather simple case. More comlex cases with classes don't > behave so reliably. Interesting. So certain things in Python work reliably for "simple cases" but less reliably for "complex cases". How is the distinction made by the interpreter? This would be an interesting classifier... I will have to look in the code. :) In anycase, I have a rather large software platform that reloads modules with classes all the time. So, the platform itself keeps on running while I hack away at a new module; with every change I reload the module and my platform instantiates it AND I get to see the changes in action. Test. Modify. Repeat. Maybe the complex/simple case classifier in my version of Python is buggy? ;) Regards, -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From aahz at panix.com Sun Mar 10 11:39:09 2002 From: aahz at panix.com (Aahz Maruch) Date: 10 Mar 2002 08:39:09 -0800 Subject: financial calculations References: Message-ID: In article , tc wrote: > >Is there a python module for financial calculations ? Using floats would >give me too much problems with rounding errors. Not financial calculations per se, but your best bet until I finish my BCD module is Tim Peters's FixedPoint.py. Unfortunately, the old FTP link appears to be broken, so I've put up a copy on my Starship pages: http://starship.python.net/crew/aahz/FixedPoint.py -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From quinn at upchuck.ugcs.caltech.edu Tue Mar 12 03:08:59 2002 From: quinn at upchuck.ugcs.caltech.edu (Quinn Dunkan) Date: 12 Mar 2002 08:08:59 GMT Subject: augmented arithmetic operations References: Message-ID: On Mon, 11 Mar 2002 20:32:57 GMT, Mike Carifio wrote: >For example, suppose I introduced Point as a kind of number: > >class Point: > def Point(self, x, y): > self.x = x; self.y = y > def __add__(self, rhs): > return Point(self.x + rhs.x, self.y + rhs.y) > def __iadd__(self, rhs): > intermediate = self + rhs # bad form? > self.x = intermediate.x; self.y = intermediate.y Since you seem to know C++ , you could do it the usual C++-ly way and implement __add__ in terms of __iadd__: def __add__(self, rhs): p = copy.copy(self) p += rhs return p def __iadd__(self, rhs): self.x += rhs.x self.y += rhs.y From phr-n2002a at nightsong.com Fri Mar 8 21:59:07 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 08 Mar 2002 18:59:07 -0800 Subject: why is python slow? References: Message-ID: <7xvgc6fnus.fsf@ruckus.brouhaha.com> Fernando Pereira writes: > The irreducible fact is that Python needs extensive runtime type checks, > Java doesn't. One could argue that agressive inlining of built-in operations > and type checks followed by removal of redundant machine instructions might > have the effect of removing most type checks, but that needs to be shown. 40 years of Lisp compiler implementations have shown pretty conclusively that these problems are surmountable. From tejarex at yahoo.com Fri Mar 29 17:43:03 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 29 Mar 2002 22:43:03 GMT Subject: Breaking String into Values References: Message-ID: "robert garretson wright" wrote in message news:HD5p8.33836$tg4.398811 at vixen.cso.uiuc.edu... > I am working on reading in a data file format which is set up as a series > of lines that look like this: > > 3500035000010104A Foo 45 > > I want to break up into a variables as follows: > a = 35000, b = 35000, c = 10104, d = 'A', e = 'Foo', f = 45 > > My current code (auto-generated from a data dictionary) looks > something like this: > > temp = line[0:5] > a = int(temp) It would be slightly and to me easier to read without the 'temp' vars. ... > Is there a better way to do this? The files have around 1000-8000 lines each > so I would like it to be fast. What times are you trying to improve on? When I did comparable projects, (on a 3+ year old PC) input and conversion only took a few seconds, as I remember. Terry J. Reedy From narnett at mccmedia.com Mon Mar 25 11:07:03 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Mon, 25 Mar 2002 08:07:03 -0800 Subject: Web robot "freeze" solved, perhaps (was RE: Debugging on windows via print statements -- reliable?) In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Aahz > Sent: Monday, March 25, 2002 7:06 AM > To: python-list at python.org > Subject: Re: Debugging on windows via print statements -- reliable? [snip] > Ah. You're probably getting stuck in urllib. You need to use > http://www.timo-tasi.org/python/timeoutsocket.py I don't think that was the problem (urlretrieve showed me that the file was retrieved before the "freeze") but that's a function that I absolutely wanted to add shortly, so a big thank-you. Tim Bray, who wrote one of the first Web robots ever, had recently emphasized the importance of "kind" time-outs for robots on the robots mailing list, so this was very much on my mind. What appears to have finally solved this problem was a fix to a function I was calling to parse each new document. The function is below. I had earlier assigned self.onePage to be the page contents in the calling function, then decided to pass it to this function instead, but didn't change newParser (which is no longer an appropriate name, come to think of it) itself appropriately. def newParser(self,onePage): self.myParser.reset() self.onePage = string.replace(self.onePage,' \n',' ') self.onePage = string.replace(self.onePage,'\n',' ') self.myParser.feed(self.onePage) self.myParser.close() An extremely quick fix was to add "self.onePage = onePage" and then, of course, clean up the thing by getting rid of all of the self references for onePage. I suppose it's obvious that I was using self.onePage in the calling function, or this wouldn't have worked at all. I haven't quite sorted out what was happening or why it was intermittently misbehaving. But I have now run a few hundred iterations with no problems. I added timeoutsocket, but no timeouts have happened yet. However, I'm hitting a very robust site and my ISP is incredibly reliable. Most of the pages only take .2 seconds to be retrieved, rarely more than 1 second. Whew. Thanks, all! Nick From jeff at ccvcorp.com Thu Mar 28 14:05:42 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 28 Mar 2002 11:05:42 -0800 Subject: vwait in Python? References: <1017315455.8141.1.camel@lewis> Message-ID: <3CA36985.D67F9D02@ccvcorp.com> Ken Guest wrote: > On Thu, 2002-03-28 at 11:37, Ken Guest wrote: > > Anybody know if there's an equivalent to TCL's vwait keyword in Python? > > So is there no way, short of a 2 line while statement, to have code > hang around until the value of some variable has been changed? > > I have tried using variations of the simple while statement, but they > only result in the application hanging (going into an infinite loop > no doubt). You *could* make this work by using threads, but it's likely that there's a more effective way of solving the real problem. You could also require that the variable in question be changed through some proxy object, and have that proxy automatically execute some code (either hardcoded in or registered with the proxy at runtime) when the variable changes. (This could be done either by using an explicit setter method, or by use of proxy.__setattr__(). ) (By the way, being impatient for a response after only 4 hours, on Usenet, is kind of silly. Netnews can be slow to propagate, many people only read at particular times of day, etc, etc... I'd recommend waiting at least a day or three before you start presuming that nobody will answer.) Jeff Shannon Technician/Programmer Credit International From quinn at cruzeiro.ugcs.caltech.edu Sat Mar 9 14:56:56 2002 From: quinn at cruzeiro.ugcs.caltech.edu (Quinn Dunkan) Date: 9 Mar 2002 19:56:56 GMT Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 08:41:31 -0800, David Eppstein wrote: >Rationale > > One of the most common uses of for-loops in Python is to iterate > over an interval of integers. Not even close, for me. I usually iterate over sequences (which are not of consecutive integers). > Python provides functions range() > and xrange() to generate lists and iterators for such intervals, > which work best for the most frequent case: half-open intervals > increasing from zero. However, the range() syntax is more awkward > for open or closed intervals, and lacks symmetry when reversing > the order of iteration. That's because what you really want in those cases is a different function: def hrange(x, y): if x < y: while x != y: yield x x += 1 else: while x != y: yield x x -= 1 yield y > In addition, the call to an unfamiliar > function makes it difficult for newcomers to Python to understand > code that uses range() or xrange(). Anyone to whom the basic builtins are unfamiliar doesn't know python and can't be expected to understand it very well . >Specification > > We propose to extend the syntax of a for statement, currently Personally, I wouldn't mind seeing the rate of syntax extensions slow down a bit. So I can't really say I'm in favor of this one, sorry :( From edream at tds.net Mon Mar 4 19:23:37 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 05 Mar 2002 00:23:37 GMT Subject: Reorganizing python.org (was: Why isn't pychecker...) References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> Message-ID: <3C841006.634D0059@tds.net> Hi All, The main page at python.org is getting too long, IMO. At some point all the links on the main page become more clutter than helpful. I have lots of experience organizing things into outlines ;-) It would be best, I think, to create some "second level" pages referenced from python.org, something like this: python.org a page about releases of python itself a download page a page about major tools, idle, pychecker, pyunit, with links to the commercial products page, a page about related products & tools, MacPython, Jython, Pippy, Tkinter, etc. a links page, containing subpages or subsections for commercial products an events page the commercial products page. etc. The main rules of thumbs in any reorganization: Everything significant should be 1 or 2 clicks away from python.org. Everything significant should have its own place (maybe off-site). Every on-site page should mostly fit on a screen. In short: place for everything, and everything in its place. If more was "offloaded" to second-level pages we would get two big additional benefits: 1. There can be more second level pages so the material can be organized more effectively. 2. Each page, covering less, can do it better. It can be more "relaxed" because more will fit on the page. This applies to top-level pages as well as secondary pages. I find this error all over the web: we try to cram too much onto a single page, especially reference pages, with the result that one is constantly scrolling to find what one wants. This wastes huge amounts of time and is hard on the eyes. The solution is always the same, to reorganize the top-level page so that it can be seen at a glance, and add at least one extra level of organization. Examples: http://python.org/doc/current/ fits on a page, C:\Python22\Doc\lib\lib.html does not. C:\Python22\Doc\lib\lib.html would be so much easier to use if it contained only the top-level entries, that is, intro, front matter, entries 1-20, entries A,B,C and index. All pages can be more informative, and more relaxed. Another example, the otherwise superb intro to Tkinter, http://www.pythonware.com/library/tkinter/introduction/index.htm would be vastly more useful if it fit on a single page. Once again, first and second level pages could be both more useful and more relaxed. The Tk man pages themselves are well organized except for the very bottom pages, e.g., http://tcl.activestate.com/man/tcl8.4/TkCmd/menubutton.htm which cram everything about a particular class in one humongous mess. Perhaps this is done so that is can be printed as reference. If that is a goal, one can keep the bottom level page and add a mid-level page consisting of links into the bottom level page. The mid-level pages would contain real information(!), viz., the "big picture" of what is contained in bottom-level pages. As I write this, I realize that Leo's own "Complete Table of Contents", http://personalpages.tds.net/~edream/leo_TOC.html, is too long and could profitably be reorganized using these rules of thumb. OTOH, Leo's on-screen reference, LeoDocs.leo, is organized this way (and the user can reorganize it at will.) Browsing through Section 4 of the FAQ I came across 4.49 re pyunit, which I had also missed. Section 4 seems to be a catch-all, and too long. Taking these rules of thumb further, it might make sense to split section 4 into several sections: programming tools, like pychecker, pyunit and idle, etc., questions about basic constructs, and questions about typical errors. It would be easier to find things. Anyway, this is how I would organize things. YMMV. If people are interested, I would be happy to work on a reorganization of python.org. And yes, this posting violates these principles, as it hardly fits on any monitor :-) Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From fgeiger at datec.at Tue Mar 19 02:21:23 2002 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 19 Mar 2002 08:21:23 +0100 Subject: Want to convert images into HSL format References: Message-ID: The Sandard Lib - the undiscovered land... ;-). Works fine, thanks a lot for the hint! Best regards Franz GEIGER "Fredrik Lundh" schrieb im Newsbeitrag news:uzol8.25972$n4.5086912 at newsc.telia.net... > "F. GEIGER" wrote: > > > PIL can supply me with RGB data of an image. Does anybody know, how I can > > PIL have to transform this into the HSL (aka HSI) model? > > > > I'm new to image processing, but if I understand the chapter Introducint > > PIL -> Concepts -> Mode right, HSL is not mentioned there. Well, I have to > > admit, the only two color modes of the mentioned ones I understand are RGB > > and CMYK. > > PIL doesn't support HLS images. > > if you only need HLS values for individual pixels, you can use > the colorsys module in Python's standard library: > > >>> import Image > >>> im = Image.open("lenna.im") > >>> im.mode > 'RGB' > >>> im.getpixel((0, 0)) > (226, 161, 119) > >>> import colorsys > >>> colorsys.rgb_to_hls(*[x/255.0 for x in im.getpixel((0, 0))]) > (0.065420560747663545, 0.67647058823529416, 0.64848484848484833) > > see the library reference for details. > > > > From rnd at onego.ru Sat Mar 30 00:33:13 2002 From: rnd at onego.ru (Roman Suzi) Date: Sat, 30 Mar 2002 08:33:13 +0300 (MSK) Subject: decision tables Re: Another stab at a "switch/case" construct (new proposal): In-Reply-To: <004d01c1d797$401f2120$0101010a@local> Message-ID: On Fri, 29 Mar 2002, Chris Gonnerman wrote: >----- Original Message ----- >From: "Cliff Wells" >> >> Now which is cleaner? I think the perceived need for this type of >> construct is a holdover from thinking in other programming languages >versus >> thinking in Python. if-elif-else is a complete functional substitute for any kind of switch/case. I can't see why this topic is still discussed. Python has dictionaries, so many simple things could be made by them. More complex decision making pieces of code could be elegantly done with if's. * However, I'd liked to see a good paradigm for expressing decision tables like this one: F1 F2 F3 R 0 0 * do1 0 1 0 do2 0 1 1 do3 1 * * do4 in Python. (With lazy evaluation, of course). Any ideas? Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Saturday, March 30, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "Answers: $1 * Correct answers: $5 * Dumb looks: Free! *" _/ From skip at pobox.com Fri Mar 15 13:49:09 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 15 Mar 2002 12:49:09 -0600 Subject: syntax question: "<>" and "!=" operators In-Reply-To: <3dd808a4.0203151013.a37d0c4@posting.google.com> References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: <15506.16933.119089.728350@12-248-41-177.client.attbi.com> >>>>> "Joe" == Joe Grossberg writes: Joe> Is there any effective difference between the two? Nope. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From geoff at gerrietts.net Fri Mar 8 14:52:25 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 8 Mar 2002 11:52:25 -0800 Subject: Is current integer for-loop syntax a wart? In-Reply-To: References: Message-ID: <20020308195224.GD4569@isis.gerrietts.net> -Wart? As long as we're just offering opinions, mine falls somewhere between Wart? and Not a wart. I'll lean towards Wart? because I want to keep an open mind. The current syntax addresses my needs. It's pretty clear. The behaviour of the range() construct is well-defined and universal -- it's not specific to the "for" construct. In short, I would really need to be convinced that an alternative would be better rather than just convenient. Without registering opinions on either of the PEPs (which I haven't researched), I would hope that when Guido decides on these PEPs, he is thinking in terms of necessity. --G. -- Geoff Gerrietts -rw-rw-rw-: permissions of the beast From paul at boddie.net Fri Mar 8 10:27:35 2002 From: paul at boddie.net (Paul Boddie) Date: 8 Mar 2002 07:27:35 -0800 Subject: The language vs. the environment References: <23891c90.0203071057.57204175@posting.google.com> Message-ID: <23891c90.0203080727.30419fd8@posting.google.com> Michael Hudson wrote in message news:... > > This isn't true. You need to know how to use "cvs" and "diff", and > *some* bugs require a "Python internals skill level" of at least 11 > out of 10, but most don't and many probably don't require more that 3 > or 4 out of ten. Besides, what better way of acquiring the skill to > fix deep bugs than to practice fixing shallow ones? My point exactly. I increased my "skill level" by 1 point (alright, 0.5 points, then) when I went looking inside the import mechanism, although I then took the easy way out and passed the problem over to some willing Python gurus instead of fixing it myself. (Actually, I couldn't have fixed it definitively myself - there was a "policy" thing that needed addressing.) Paul From mwh at python.net Fri Mar 1 10:33:30 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 1 Mar 2002 15:33:30 GMT Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <20020227163411.71b4b4d8.alex@netWindows.org> Message-ID: aahz at panix.com (Aahz Maruch) writes: > In article , Michael Hudson wrote: > >Dennis Roark writes: > >> > >> The Python book appears substantially based on the templates of > >> their previous books. > > > >Certainly the first draft of chapter 2 that I reviewed[0] looked > >suspiciously like the corresponding chapter from Java:HTP. That went > >back with a lot of red ink on it... > > All right, let me ask: are there any reviewers who think that PyHTP looks > like a book written by Python programmers rather than a book written by > Java programmers? Well, the published version looks less like this than the initial version, at least. What worried me more was the fact that it seems to cover 101 topics -- I have a feeling it might give a reader enough knowledge to be really dangerous in some areas, but no more. > >[0] My, there were a lot of reviewers weren't there? > > Yup. A lot of *opinionated* reviewers, at that. In all fairness, it's > pretty clear that Deitel paid a fair amount of attention to our > comments, but thought it was more important to stick with the style of > their existing books. Well, some of the things that struck me as odd might have some thought behind them -- the repitition being one of the more obvious. > And, heck, they *did* pay well for my time. Yeah, though I'll be happier when I actually get paid... (this is my first encounter with the IRS). And I now have the 2.2 source on my home box (which is currently sundered from the internet). Must find a book to review as 2.3 is being prepared . Cheers, M. -- The meaning of "brunch" is as yet undefined. -- Simon Booth, ucam.chat From tim.one at comcast.net Tue Mar 19 20:20:36 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 19 Mar 2002 20:20:36 -0500 Subject: Python 2.2 seriously crippled for numerical computation? In-Reply-To: Message-ID: [jochen at bock.chem.unc.edu] > Ok, looking at SourceForge and google this seems to be fixed in cvs > HEAD. Would it be possible to put the same patch into the cvs > python-2.2 branch, please? [1] > > Greetings, > Jochen > > Footnotes: > [1] If it is in there, it doesn't work for me with current python cvs > branch release22-maint. I still have to manually add -lieee. > (RedHat-7.0 with current updates.) I don't know what "current" meant to you at the time you wrote this. Michael Hudson did backport the patch into 2.2.1c1, which was released yesterday. So please try 2.2.1c1, and if you still have a problem, file a bug report about it on SourceForge. 2.2.1 final is expected in about a week. From sholden at holdenweb.com Tue Mar 26 12:57:32 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 26 Mar 2002 12:57:32 -0500 Subject: Python Books Galore References: Message-ID: "Christopher Abraham" wrote in message news:cja-2603021134010001 at 192.168.1.42... > Raymond: > > It most certainly is a very fine sign. I am also interested, now that > there are so many and not so few, in finding a great trinity of Python > Books for use at work. One for introductory study, one for advanced > technique, and one as a reference book. Of course, this could be as many > as five-seven books, but three is a pretty appropriate number this week of > any. > > Cheers, > > Chris > > In article , "Raymond Hettinger" > wrote: > > [snip] > > I went back yesterday and found a full row (3 1/2 to 4 feet) filled with > > Python books. > [snip] > > This has got to be a good sign. Speaking as a recently-published Python author, I'd be happier if the books disappear from the shelves as fast as they appear. regards Steve From m.andrzejewski at dmz.com.pl Mon Mar 4 06:53:49 2002 From: m.andrzejewski at dmz.com.pl (marcin andrzejewski) Date: Mon, 4 Mar 2002 12:53:49 +0100 Subject: problem with locale References: Message-ID: U?ytkownik "Just van Rossum" napisa? w wiadomo?ci news:just-60231F.12461704032002 at news1.xs4all.nl... > In article , > "marcin andrzejewski" wrote: > I think your script is called locale.py: Python will find it before the > "real" locale.py is found when importing. that's right, thanks -- marcin andrzejewski m.andrzejewski at dmz.com.pl keson at post.pl From brueckd at tbye.com Sat Mar 2 14:11:27 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sat, 2 Mar 2002 11:11:27 -0800 (PST) Subject: Rotor in Jython? In-Reply-To: <7xr8n329oc.fsf@ruckus.brouhaha.com> Message-ID: On 1 Mar 2002, Paul Rubin wrote: > writes: > > Put another way: sorting by key length, AES beats rotors hands down. > > Sorting by computational cost, rotors always win because you can just make > > the keys longer (without having to reimplement your crypto). > > Longer keys are only relevant if breaking the cipher requires searching > for the key. Heheh... that's essentially what cryptanalysis is - finding the key since in most cases the algorithm itself is known. If you're referring to non-brute force key searches, then key length is relevent there as well (unless the algorithm itself is flawed). For example, in differential cryptanalysis of DES you're basically deducing bits of the key until you have so few remaining that a brute force attack becomes feasible. Longer key sizes (and a higher number of rounds) have an enormous impact on whether or not you'll ultimately be successful. -Dave From bernie at 3captus.com Tue Mar 5 02:38:29 2002 From: bernie at 3captus.com (Bernard Yue) Date: Tue, 05 Mar 2002 00:38:29 -0700 Subject: Brewster's Factor - was :Trouble running programs References: <200203041148.g24BmttB007592@ratthing-b246.strakt.com> Message-ID: <3C8475F4.46E94132@3captus.com> Laura Creighton wrote: > > Bernard Yue's sig is: > > > > There are three schools of magic. One: State a tautology, then ring > > the changes on its corollaries; that's philosophy. Two: Record many > > facts. Try to find a pattern. Then make a wrong guess at the next > > fact; that's science. Three: Be aware that you live in a malevolent > > Universe controlled by Murphy's Law, sometimes offset by Brewster's > > Factor; that's engineering. > > > > So far as I can remember, there is not one word in the Gospels in > > praise of intelligence. > > -- Bertrand Russell > > I wanted to know what Brewster's Factor was. I found out that the first > part of the quote -- the bit that ends with Engineering should be > attributed to Robert A. Heinlein (from The Number of the Beast). Number of the Beast!!! Read the book but don't remember the quote !! Thanks for the correction. > But the only Brewster Factors I can find have to do with polarised light, > or English Chrisitian Revivalist Victorian political parties, neither > of which I suspect is what I am looking for. Any ideas? Laura, I believe you found what you have looking for. I think in the quote Brewster Factor is refering to Brewster Law. Which states that non-polarized light will be reflected as polarized light (a special case in reflection) and reflected and refracted light will be in right angle. I see this as an analogy to Engineering, in which a system only works under certain conditions (Brewster Angle) and failed to function otherwise (Murphy's Law). Robert A. Heinlein should be able to another the question, but we are nearly 14 years too late. > > Laura Creighton I love this newsgroup. Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From romany at actimize.com Wed Mar 6 12:21:26 2002 From: romany at actimize.com (Roman Yakovenko) Date: Wed, 6 Mar 2002 19:21:26 +0200 Subject: PEP 284, Integer for-loops Message-ID: <7647A9F4B298E74DB6793865DA67285004ACF1@exchange.adrembi.com> What is about step ? for( int I = 0; I < 10; I+=2) do smth -----Original Message----- From: David Eppstein [mailto:eppstein at ics.uci.edu] Sent: Wednesday, March 06, 2002 6:42 PM To: python-list at python.org Subject: PEP 284, Integer for-loops Abstract This PEP proposes to simplify iteration over intervals of integers, by extending the range of expressions allowed after a "for" keyword to allow three-way comparisons such as for lower <= var < upper: in place of the current for item in list: syntax. The resulting loop or list iteration will loop over all values of var that make the comparison true, starting from the left endpoint of the given interval. Rationale One of the most common uses of for-loops in Python is to iterate over an interval of integers. Python provides functions range() and xrange() to generate lists and iterators for such intervals, which work best for the most frequent case: half-open intervals increasing from zero. However, the range() syntax is more awkward for open or closed intervals, and lacks symmetry when reversing the order of iteration. In addition, the call to an unfamiliar function makes it difficult for newcomers to Python to understand code that uses range() or xrange(). The perceived lack of a natural, intuitive integer iteration syntax has led to heated debate on python-list, and spawned at least four PEPs before this one. PEP 204 [1] (rejected) proposed to re-use Python's slice syntax for integer ranges, leading to a terser syntax but not solving the readability problem of multi-argument range(). PEP 212 [2] (deferred) proposed several syntaxes for directly converting a list to a sequence of integer indices, in place of the current idiom range(len(list)) for such conversion, and PEP 281 [3] proposes to simplify the same idiom by allowing it to be written as range(list). PEP 276 [4] proposes to allow automatic conversion of integers to iterators, simplifying the most common half-open case but not addressing the complexities of other types of interval. Additional alternatives have been discussed on python-list. The solution described here is to allow a three-way comparison after a "for" keyword, both in the context of a for-loop and of a list comprehension: for lower <= var < upper: This would cause iteration over an interval of consecutive integers, beginning at the left bound in the comparison and ending at the right bound. The exact comparison operations used would determine whether the interval is open or closed at either end and whether the integers are considered in ascending or descending order. This syntax closely matches standard mathematical notation, so is likely to be more familiar to Python novices than the current range() syntax. Open and closed interval endpoints are equally easy to express, and the reversal of an integer interval can be formed simply by swapping the two endpoints and reversing the comparisons. In addition, the semantics of such a loop would closely resemble one way of interpreting the existing Python for-loops: for item in list iterates over exactly those values of item that cause the expression item in list to be true. Similarly, the new format for lower <= var < upper: would iterate over exactly those integer values of var that cause the expression lower <= var < upper to be true. Specification We propose to extend the syntax of a for statement, currently for_stmt: "for" target_list "in" expression_list ":" suite ["else" ":" suite] as described below: for_stmt: "for" for_test ":" suite ["else" ":" suite] for_test: target_list "in" expression_list | or_expr less_comp or_expr less_comp or_expr | or_expr greater_comp or_expr greater_comp or_expr less_comp: "<" | "<=" greater_comp: ">" | ">=" Similarly, we propose to extend the syntax of list comprehensions, currently list_for: "for" expression_list "in" testlist [list_iter] by replacing it with: list_for: "for" for_test [list_iter] In all cases the expression formed by for_test would be subject to the same precedence rules as comparisons in expressions. The two comp_operators in a for_test must be required to be both of similar types, unlike chained comparisons in expressions which do not have such a restriction. We refer to the two or_expr's occurring on the left and right sides of the for-loop syntax as the bounds of the loop, and the middle or_expr as the variable of the loop. When a for-loop using the new syntax is executed, the expressions for both bounds will be evaluated, and an iterator object created that iterates through all integers between the two bounds according to the comparison operations used. The iterator will begin with an integer equal or near to the left bound, and then step through the remaining integers with a step size of +1 or -1 if the comparison operation is in the set described by less_comp or greater_comp respectively. The execution will then proceed as if the expression had been for variable in iterator where "variable" refers to the variable of the loop and "iterator" refers to the iterator created for the given integer interval. The values taken by the loop variable in an integer for-loop may be either plain integers or long integers, according to the magnitude of the bounds. Both bounds of an integer for-loop must evaluate to a real numeric type (integer, long, or float). Any other value will cause the for-loop statement to raise a TypeError exception. Issues The following issues were raised in discussion of this and related proposals on the Python list. - Should the right bound be evaluated once, or every time through the loop? Clearly, it only makes sense to evaluate the left bound once. For reasons of consistency and efficiency, we have chosen the same convention for the right bound. - Although the new syntax considerably simplifies integer for-loops, list comprehensions using the new syntax are not as simple. We feel that this is appropriate since for-loops are more frequent than comprehensions. - The proposal does not allow access to integer iterator objects such as would be created by xrange. True, but we see this as a shortcoming in the general list-comprehension syntax, beyond the scope of this proposal. In addition, xrange() will still be available. - The proposal does not allow increments other than 1 and -1. More general arithmetic progressions would need to be created by range() or xrange(), or by a list comprehension syntax such as [2*x for 0 <= x <= 100] - The position of the loop variable in the middle of a three-way comparison is not as apparent as the variable in the present for item in list syntax, leading to a possible loss of readability. We feel that this loss is outweighed by the increase in readability from a natural integer iteration syntax. - To some extent, this PEP addresses the same issues as PEP 276 [4]. We feel that the two PEPs are not in conflict since PEP 276 is primarily concerned with half-open ranges starting in 0 (the easy case of range()) while this PEP is primarily concerned with simplifying all other cases. However, if this PEP is approved, its new simpler syntax for integer loops could to some extent reduce the motivation for PEP 276. - It is not clear whether it makes sense to allow floating point bounds for an integer loop: if a float represents an inexact value, how can it be used to determine an exact sequence of integers? On the other hand, disallowing float bounds would make it difficult to use floor() and ceiling() in integer for-loops, as it is difficult to use them now with range(). We have erred on the side of flexibility, but this may lead to some implementation difficulties in determining the smallest and largest integer values that would cause a given comparison to be true. - Should types other than int, long, and float be allowed as bounds? Another choice would be to convert all bounds to integers by int(), and allow as bounds anything that can be so converted instead of just floats. However, this would change the semantics: 0.3 <= x is not the same as int(0.3) <= x, and it would be confusing for a loop with 0.3 as lower bound to start at zero. Also, in general int(f) can be very far from f. Implementation An implementation is not available at this time. Implementation is not expected to pose any great difficulties: the new syntax could, if necessary, be recognized by parsing a general expression after each "for" keyword and testing whether the top level operation of the expression is "in" or a three-way comparison. The Python compiler would convert any instance of the new syntax into a loop over the items in a special iterator object. References [1] PEP 204, Range Literals http://www.python.org/peps/pep-0204.html [2] PEP 212, Loop Counter Iteration http://www.python.org/peps/pep-0212.html [3] PEP 281, Loop Counter Iteration with range and xrange http://www.python.org/peps/pep-0281.html [4] PEP 276, Simple Iterator for ints http://www.python.org/peps/pep-0276.html Copyright This document has been placed in the public domain. -- http://mail.python.org/mailman/listinfo/python-list From emile at fenx.com Sun Mar 31 12:28:56 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 31 Mar 2002 17:28:56 GMT Subject: newbie question on lists, getting an error on basic addition References: Message-ID: John Warney > >>> alist = [1, 2, 3, 4] > >>> counter = 0 > >>> answer = 0 > >>> alist [snip] > >>> while counter < 6: > ... answer = answer + alist[counter] > ... counter = counter + 1 > ... > Traceback (most recent call last): > File "", line 2, in ? > IndexError: list index out of range > >>> answer > 10 > > why am i getting this error when it works??? > Rob You get the error because you're trying to loop six times through a list of four elements. What you've displayed is the accumulated total while the loop worked. -- Emile van Sebille emile at fenx.com --------- From philh at comuno.freeserve.co.uk Sat Mar 9 08:56:47 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 9 Mar 2002 13:56:47 +0000 Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> Message-ID: On Fri, 08 Mar 2002 23:50:04 GMT, Edward K. Ream wrote: >PEP 282 is more complex and less flexible than it could be. Instead, >Python's standard logging system could well use dynamic tracing. I recently wrote a logging system as part of my Herbrip application. I'm not sure that the python standard library needs a built-in logging system. Sure, it'll be useful to some people if done well and if it integrates in with logging in Unix-like OSes. But it is hardly rocket science to write one from scratch -- my logging.py is 200 lines long (including comments and blank lines) and wasn't mentally taxing to write. Furthermore it does logging in a way specific to Herbrip; a generalised solution would need to be extensively modified to do the functionality I weant, so it might not be worth learning its API to use it. I would suggest that the proponent of this system writes it, gets it used in several packages, makes changes and improvments based on comments received, then proposes adding it to the standard library. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From edream at tds.net Mon Mar 4 21:03:19 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 05 Mar 2002 02:03:19 GMT Subject: Editors for Python References: Message-ID: <3C842765.537604FD@tds.net> Moray Taylor wrote: > I am desperatly seeking a good python editor, so far JEdit is the best > I have found, but since it is written in Java, I find it painfully > slow, and PyBrowse, although good, a little flaky. You might try leo.py: Open Software, written entirely in Python. Requires Python 2.x and Tk 8.x. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From tdelaney at avaya.com Mon Mar 18 18:22:03 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 19 Mar 2002 10:22:03 +1100 Subject: open() error ---- what am I missing? Message-ID: > > In other words it was another case of: r"use raw strings for > > filename literals under Win Python!" > > Possibly another case of: """ > > In general, if you absolutely *must* hard-code filename literals in > Python scripts, don't use "\\name" (for example) or even r"\name", use > "/name"; the Windows API happily supports it. > > """ Or best of all, use os.path.normath('/name') to be absolutely certain ... Tim Delaney From tim.one at comcast.net Sun Mar 10 18:37:37 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 10 Mar 2002 18:37:37 -0500 Subject: Modulo operator : differences between C and Python In-Reply-To: <3C8BE537.74E55963@mega-nerd.com> Message-ID: [Erik de Castro Lopo] > Just recently I prototyped a relatively complex algorithm in Python > before converting it to C. During this conversion I noticed that > the modulo operator returns different results in C and Python if > the numerator is negative. For positive values they produce the same > result. Python defines the result of i%j to have the same sign as j; what C requires depends on which year's C standard you're looking at (it was left up to implementers' discretion before the 1999 standard); the C implementations I use return a result with i's sign, and I usually curse them for that. Note that this is related to what "i/j" returns. Both languages preserve i == (i/j)*j + i%j in non-pathological cases (j != 0, etc). From loewis at informatik.hu-berlin.de Mon Mar 4 12:04:26 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 04 Mar 2002 18:04:26 +0100 Subject: Memory leak when importing? References: Message-ID: Harald Kirsch writes: > Any ideas? Rough guesses? I'd invoke gc.getobjects() from time to time, to see whether the list gets longer. If that fails, you may want to build the pydebug version, to get the total list of objects; you can then see what the additional objects are. That should give a clue as to where they come from. Regards, Martin From BPettersen at NAREX.com Thu Mar 7 11:20:15 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 7 Mar 2002 09:20:15 -0700 Subject: PEP 284, Integer for-loops Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192215153@admin56.narex.com> > From: John Machin [mailto:sjmachin at lexicon.net] > > "Bjorn Pettersen" wrote in message > news:... > > > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > > Subject: PEP 284, Integer for-loops > > > > Thanks for writing the PEP. > > > > I see this as a general proposal for a range syntax, and I disagree > > with it because: > > [snip] > > > > - I would like range objects to be first class, ie. I would want > > to be able to pass ranges to functions, return them from > > functions, and do all the other things one can do with first > > class objects. > > I don't understand this. range and xrange *are* first-class > objects. You can do all of those things. Yes, but this new syntax is proposing itself to be *the* way of creating a range to iterate over. If it can only be used in one context in the language I'm left to wonder if it's not just extra "noise" for everyone to have to learn... -- bjorn From greg at cosc.canterbury.ac.nz Tue Mar 26 20:44:13 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 27 Mar 2002 13:44:13 +1200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Dale Strickland-Clark wrote: > > Or is Guido getting writing software and writing novels confused? I'd say the skills required to write clear, readable software and clear, readable novels are not entirely disjoint! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From mlh at vier.idi.ntnu.no Fri Mar 15 19:40:06 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 16 Mar 2002 00:40:06 +0000 (UTC) Subject: Why I think range is a wart. References: Message-ID: In article , Christian Tanzer wrote: > [snip] >> It happens to me too, mostly when I'm using a sliding window >> type algorithm, that is, I need to look at two adjacent members >> of the list. You can't do this easily by iterating through the list; >> unrolling the first entry and the last entry are a pain. > >I use a function pairwise to do such things: > > for l, r in pairwise(mylist) : > > >Probably not as fast as index manipulation, but IMHO much easier to >read/write/understand. As an apropos, I need sliding windows a bit too, and have been using the following solution in numarray: from numarray import * def windows(data, size): shape = (size, len(data)-size+1) return data[sum(indices(shape))] It can be used like this: >>> print windows(arange(10), 3) [[0 1 2] [1 2 3] [2 3 4] [3 4 5] [4 5 6] [5 6 7] [6 7 8] [7 8 9]] It took me a while to figure out exactly how to do it but figuring out how it works shouldn't be that hard ;) Of course these are overlapping windows (with step 1) -- a non-overlapping version is left as an exercise for the reader . -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From ws at mystrobl.de Sun Mar 17 08:26:14 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Sun, 17 Mar 2002 14:26:14 +0100 Subject: Windows NT shell + extended characters. Bug or what? References: Message-ID: 16 Mar 2002 01:06:45 +0100, martin at v.loewis.de (Martin v. Loewis): >"Jason Orendorff" writes: > >> Alas, the PC console uses a different character set called CP437, >> which is not Latin-1 compatible. In CP437, the pound sign >> is 156 and the yen sign is 157. > >This isn't really true. The console on Windows (I believe both Win9x, >and NTx) use what MS calls the "OEM" charset. Which code page that is >depends on the Windows installation. In the US English installation, >it is indeed CP437. In the European installations, it is CP852 most of >the time. ... or CP850 aka DOS Latin 1. CP852 is Latin 2 > >> [in Win2K console] >> >>> ord(u'?') >> 156 # uhhh, no >> >>> ord(u'\N{POUND SIGN}') >> 163 # correct answer >> >> I think it's fair to say this is a deficiency in current >> versions of Python. I believe it will be fixed > >This is rather unlikely, I doubt the interactive interpreter will ever >be able to properly identify the encoding of the console window. What's wrong with GetConsoleOutputCP, besides the restrictions documented in "Q99795 SetConsoleOutputCP Only Effective with Unicode Fonts"? This API function exits since Windows NT 3.1 was released - i.e. it's almost a year older than Python version 1.0.0. C:\e\consolecp>type conoutputcp.c #include main() { printf("Code page %d",GetConsoleOutputCP());} C:\e\consolecp> C:\e\consolecp>cl /nologo conoutputcp.c conoutputcp.c C:\e\consolecp>conoutputcp.exe Code page 850 C:\e\consolecp>chcp 1252 Aktive Codepage: 1252. C:\e\consolecp>conoutputcp.exe Code page 1252 C:\e\consolecp>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ord(u'?') 163 >>> -- Thank you for observing all safety precautions From matt at swordfish.havenrock.com Fri Mar 15 23:34:04 2002 From: matt at swordfish.havenrock.com (matt at swordfish.havenrock.com) Date: 15 Mar 2002 21:34:04 -0700 Subject: Gadfly mirrors? Message-ID: Hi, folks-- Does anyone know of an alternate download site for Gadfly? I have been unable to reach www.chordate.com all evening. -- Matt Gushee Englewood, Colorado, USA mgushee at havenrock.com http://www.havenrock.com/ From philh at comuno.freeserve.co.uk Sun Mar 10 08:39:28 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sun, 10 Mar 2002 13:39:28 +0000 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: On Sat, 09 Mar 2002 22:57:42 -0500, Peter Hansen wrote: > >I agree with much of what you say, especially the "consider skipping >C++ and just learn C part", but _what_ pragmatic point of view is it >that has one learning Perl, Java, or C++ when one uses Python already? >Not dissing those languages, but when would you really need them? I can think of several tasks for which C++ is better than Python, e.g. writing operating systems, network stacks, windowing systems, run-time interpreters, crypto algorithms, etc. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From mwh at python.net Tue Mar 19 04:14:40 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Mar 2002 09:14:40 GMT Subject: RELEASED: Python 2.2.1c1 References: Message-ID: Michael Hudson writes: > This being a bugfix release, there are no exciting new features -- we just > fixed a lot of bugs. For a moderately complete list, please see: > > http://http://sourceforge.net/project/shownotes.php?release_id=80208 That's a bit embarrassing. Oh well. here's-hoping-that's-the-worst-problem-of-this-release-ly M. -- C is not clean -- the language has _many_ gotchas and traps, and although its semantics are _simple_ in some sense, it is not any cleaner than the assembly-language design it is based on. -- Erik Naggum, comp.lang.lisp From martin at v.loewis.de Wed Mar 13 03:40:04 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Mar 2002 09:40:04 +0100 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: sandskyfly at hotmail.com (Sandy Norton) writes: > Martin v. Loewis wrote in message: > > Certainly true; there is little interest in Python.NET in the Python > > community (just as there is little interest in other branches, such as > > Stackless, Psyco, and, to some degree, Jython). > > I'm somewhat bewildered by this statement. You are surely > underestimating the interest of the community in the above projects. Maybe, but then, the community is not showing its interest very much. I don't count articles in a newsgroup saying "this is a good thing", "just continue with your efforts", "we definitely need this" as interest. Instead, people contributing code, reporting bugs, or just using the system in their applications show interest. This is the case for Jython, but I don't think Armin or Christian got much actual code contributions. Likewise, when Mark would not deliver a win32all build for a few weeks, people would complain - but nobody would actually step forward and publish a build herself. Regards, Martin From sjmachin at lexicon.net Wed Mar 6 18:10:29 2002 From: sjmachin at lexicon.net (John Machin) Date: 6 Mar 2002 15:10:29 -0800 Subject: hash(unicode(string)) == hash(string) sometimes (was Re: Why KeyError ???) References: <7dee885c.0203051843.36efa5c2@posting.google.com> <7xvgcabcti.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xvgcabcti.fsf at ruckus.brouhaha.com>... > "Raymond Hettinger" writes: > > > KeyError: šđčćž > > > >>> a == b > > > 1 > > > > Hmm. I don't get the same identity check results as you do: > > >>> a = '\xe7\xd0\x9f\x86\xa7' > > >>> b = unicode(a,'cp1250') > > >>> a is b > > 0 > > Try == rather than 'is'. The docs are a little bit imprecise about > what's supposed to happen here, but 2.2.7 "Mapping types" says about > numeric keys: > > A dictionary's keys are almost arbitrary values. The only types of > values not acceptable as keys are values containing lists or > dictionaries or other mutable types that are compared by value rather > than by object identity. Numeric types used for keys obey the normal > rules for numeric comparison: if two numbers compare equal (e.g. 1 and > 1.0) then they can be used interchangeably to index the same > dictionary entry. > > That makes it surprising if two unicode strings that compare as == > don't index the same dictionary item. We don't have two unicode strings here. a is NOT a unicode string. It is a string string. The comparison coerces the string string to unicode string (using the default encoding), so they compare equal. However dictionary keying uses a hash function as well as comparison. As currently implemented, hash(a) != hash(b) sometimes. The hashes are equal when the Unicode characters are merely zero-extended 8-bit characters, as will happen when the default encoding is ascii or Latin-1. However the hashes will not be the same when the encoding is more complicated, as in the OP's cp1250 example. If the "fix" for this would involve making hash(string) always do hash(unicode(string)) then I sure hope that (borrowing timbot phraseology) somebody optimises the snot out of it. BTW, I'm not so sure of the utility of hash(1) == hash(1.0) --- why on earth would anyone want to use floats as keys in a dictionary, anyway? Eveything one reads on floating-point fulminates against equality testing. Seems like extra code and extra run-time for little benefit. From skip at pobox.com Thu Mar 7 17:05:24 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 16:05:24 -0600 Subject: Problem with cgitb In-Reply-To: <1015532454.1203.4.camel@temp> References: <1015532454.1203.4.camel@temp> Message-ID: <15495.58404.946778.996505@beluga.mojam.com> Ken> While trying to work out an appropriate fix for my problems with Ken> sgmllib I decided to try Python2.2, at which point I could start Ken> using cgitb. Unfortunately cgitb has a problem when some of the Ken> data it outputs includes HTML, since it does not escape the Ken> appropriate bits and so the browser gets very upset. Can you post a bit of the fractured HTML it generates? If you think it's truly a bug and not just an issue that cgitb can't recover because of earlier generated HTML fragments, you should file a bug report on SourceForge. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From phr-n2002a at nightsong.com Wed Mar 27 09:41:56 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 27 Mar 2002 06:41:56 -0800 Subject: Primes.... References: Message-ID: <7x663iqdhn.fsf@ruckus.brouhaha.com> "FREDRIK HULDTGREN" writes: > I should have been more specific, yes I am talking about cryptology, and > sadly enough I am runnign win2k, the unix stuff goes out the window. As > for how large of numbers I am looking for, I'd say about 512bit numbers > should do it(perhaps larger, depens on how slow it becomes). Got any > URLs that explain Fermat/Miller-Rabin tests? By the way, use gmpy if you can. It's about 10x faster than Python's built-in arithmetic for long modexps. From aahz at pythoncraft.com Sun Mar 31 09:51:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 09:51:13 -0500 Subject: Most important extensions? References: Message-ID: In article , Nick Arnett wrote: > >Would sgmllib, htmllib and urllib count as two or three? I mention the >first two partly because they could benefit from some teaching; I had to >stare at examples for a while before I grasped what was going on. All three >replaced quite a lot of my old Perl. Does Tkinter/Pmw count as an >extension? Pmw does, but that's the only one. Sorry for not making clear that I was specifically referring to 3rd-party extensions. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From jhorneman at pobox.com Fri Mar 1 08:08:40 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: 1 Mar 2002 05:08:40 -0800 Subject: Trouble importing / using a custom text codec References: <9ac02e81.0202280152.5bb1bf25@posting.google.com> Message-ID: <9ac02e81.0203010508.4ebccd75@posting.google.com> Martin von Loewis wrote in message news:... > I recommend a different strategy. Aim for allowing "cp932" as an > encoding name. To achieve this, put the following (or something like > this) into MBCS_codecs/__init__.py Thanks. I had to actually solve the problem so I took my code out of the codecs and just called it directly, but at some point in the future I will try this approach. I'd still like to know why my approach didn't work, but oh well... > If you want this to happen at startup time of Python, just add a > MBCS_codecs.pth file in site-packages, which reads What is a .pth file? Jurie Horneman From morton at dennisinter.com Fri Mar 8 18:38:51 2002 From: morton at dennisinter.com (damien morton) Date: 8 Mar 2002 15:38:51 -0800 Subject: ' in ' works, why doesnt ' in '? Message-ID: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 'c' in 'the quick brown fox' 1 >>> 'fox' in 'the quick brown fox' Traceback (most recent call last): File "", line 1, in ? TypeError: 'in ' requires character as left operand is this by design? is there any reason why ' in ' shouldnt work? From fdrake at acm.org Fri Mar 29 16:24:15 2002 From: fdrake at acm.org (Fred L. Drake, Jr.) Date: Fri, 29 Mar 2002 16:24:15 -0500 Subject: "Don't Kill Opera" documentation release Message-ID: <15524.56191.459903.271423@grendel.zope.com> I've just made an "emergency" release of the 2.2 documentation (based on the release22-maint branch in CVS. If you use Opera 6.01, you can now feel a little safer on python.org. ;-) -Fred -- Fred L. Drake, Jr. PythonLabs at Zope Corporation From cliechti at gmx.net Sat Mar 2 11:59:52 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Mar 2002 17:59:52 +0100 Subject: Possible to fake object type? References: <3c80e76b@nntp.server.uni-frankfurt.de> <3c80fb6d@nntp.server.uni-frankfurt.de> Message-ID: Michael 'Mickey' Lauer wrote in news:3c80fb6d at nntp.server.uni-frankfurt.de: > Chris Liechti wrote: >> Michael 'Mickey' Lauer wrote >> in news:3c80e76b at nntp.server.uni-frankfurt.de: >>> So: Is it possible to fake the type of a class or >>> is it possible to magically override the method call "bouncing" to >>> the base class ? >> >> you can allways call the methods of on e of the supperclasses by >> using: >> >> Baseclass.method(self, args, ...) >> >> it's the same you do in __init__ to initilaize base classes: >> >> class Dockable(gtk.HandleBox): >> def __init__(self): gtk.HandleBox.__init__(self) >> >> def dosomething(self, arg): >> print "calling dosomething...", result = >> gtk.HandleBox.dosomething(self, arg) print "result = >> %r" % result return result > > Yeah, sure, but I'd have to do this for every single > function - which is not quite the elegant solution > I aimed to come up with by using the getattr magic. why not something like that?: def __getattr__(self, name): try: return self.__dict__[name] except NameError: return getattr(gtk.HandleBox, name) something similar can be done for setattr too of course. you could also google for the Proxy Design Pattern which can be implemented in such a way. -- Chris From tim.one at comcast.net Sun Mar 31 13:26:13 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 31 Mar 2002 13:26:13 -0500 Subject: string copying In-Reply-To: Message-ID: [Bengt Richter] > Does python run out of memory gracefully? [Tim] > Very. You should get a clean MemoryError exception if you try. > > >>> 'x' * 2**30 > Traceback (most recent call last): > File "", line 1, in ? > MemoryError [Steve Holden] > My laptop upgrade clearly takes my platform beyond the timbot conceptual > limit: it took about three minutes to start printing (I'm not thinking of > letting it finish) with no error message in sight. Then you clearly have enough VM for a gigabyte string: a MemoryError would be inappropriate on your box in this case. I suggest upgrading to Windows, which dies quickly much more often . From emile at fenx.com Thu Mar 7 08:07:34 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 7 Mar 2002 05:07:34 -0800 Subject: PEP 276 -- What else could iter(5) mean? References: <6qpu2gzktu.fsf@abnoba.intevation.de> Message-ID: Bernhard Herzog > The pep doesn't say anything about the other contexts in which iterators > are used (except for the sequence unpacking above). > > Do we really want all of these new behaviors? > No. -- Emile van Sebille emile at fenx.com --------- From aahz at pythoncraft.com Tue Mar 12 15:49:48 2002 From: aahz at pythoncraft.com (Aahz) Date: 12 Mar 2002 15:49:48 -0500 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: In article , A.M. Kuchling wrote: > >There does seem to be an increasing trend to vaporware announcements >about language unification, though. Witness Parrot, Mono, and >SmallScript [1], all of which talk about having support for many >languages including Python, but none of which have actually tried to >build that support or work with the Python community to build it. That seems a tad harsh WRT Parrot. Early on they checked with python-dev and got little in the way of interest, but they've been keeping us informed irregularly. They did explicitly ask for help in making sure that Parot would work with Python, and IIRC someone (Michael Hudson?) tried doing a bit of work with Parrot/Python as a proof of concept. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From sjmachin at lexicon.net Thu Mar 7 20:41:54 2002 From: sjmachin at lexicon.net (John Machin) Date: 7 Mar 2002 17:41:54 -0800 Subject: Bug in the standard module random ? References: <3C8791B1.6BBC1981@Spam.Please> Message-ID: Weet Vanniks wrote in message news:<3C8791B1.6BBC1981 at Spam.Please>... > Hi, > > The gammavariate function of the standard module is documented as > taking two parameters, the first one alpha is required to be > -1 and > the second beta is required to be >0. > However, examining the implementation, it seems that the requirement for > alpha is to be >0. > Yes, this is a doc problem. Some definitions of the gamma distribution define it (a) such that alpha > -1 and has the exponential distribution as a special case when alpha == 0; others take the tack (b) that the lower bound is zero and the exponential distribution is when alpha == 1. Example of (b): http://www.nag.com/numeric/cl/manual/pdf/G05/g05ffc_cl05.pdf Here we have the doc taking option (a) and the implementation taking option (b). So you probably want to call it with alpha set to 1.2, not 0.2, and then it won't blow up. However the implementation is still stuffed, as my earlier posting said. N.B. the following is VERY relevant: http://mail.python.org/pipermail/python-dev/2001-January/012181.html From herrn at gmx.net Sat Mar 9 16:15:19 2002 From: herrn at gmx.net (Marco Herrn) Date: Sat, 9 Mar 2002 22:15:19 +0100 Subject: how to set the background color of a window with curses In-Reply-To: <20020309164204.GB1466@lilith.hqd-internal> References: <20020309125336.GA2236@lurkabove.darkstar> <20020309164204.GB1466@lilith.hqd-internal> Message-ID: <20020309211519.GA3210@lurkabove.darkstar> On Sat, Mar 09, 2002 at 05:42:04PM +0100, Gerhard H?ring wrote: > Le 09/03/02 ? 13:53, Marco Herrn ?crivit: > > Hi, > > > > I am trying to set a backround color for a window and did it with > > > > stdscr.bkgd(' ', curses.COLOR_BLUE) > > > > But that doesn't work. It seems to do nothing. > > What am I doing wrong? > > You're confusing colors with attributes. I recently stumbled across that > one, too :) Hmm, that may be true.... ;) > This will do the trick: > > # define color 1 as black on blue > curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_BLUE) > stdscr.bkgd(' ', curses.color_pair(1)) No, that doesn't work for me. The whole screen remains black. I get no error message and any text that is displayed with color_pair(1) is correctly displayed in black on blue. Am I missing something else? > Btw. there's a curses howto on http://py-howto.sf.net/ in case you > didn't know. Yes, I did read it. It is a good starting point, but unfortunately doesn't go over my problem ;) Bye Marco -- Experience is something you don't get until just after you need it. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From martin at v.loewis.de Mon Mar 4 02:52:34 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Mar 2002 08:52:34 +0100 Subject: How can I use a foreign language char in Swing References: Message-ID: "Jason Orendorff" writes: > > I installed J2SDK 1.4.0 several days ago. I need to get some strings from > > database which stored in GB2312 encode method, and display it > > using Swing. I > > got correct result in Windows2000(Use China as default region and > > GB2312 as > > encode method.) While I??run it on Windows(English Edition), all I can see > > is ?????. > > > > What should I do? I think ResourceBoundle can't help me. Is there > > any other > > method can help me? [...] > 1. Missing Fonts. Seems unlikely. But if this is the problem, > it's easy to fix. :) Actually, this is quite likely: MS normally choses "?" as the replacement character, and you need to explicitly request CJK fonts when installing the English edition of W2k. If "Windows" really means "W9x" in this context, things are probably even worse. Regards, Martin From xscottgjunk at yahoo.com Fri Mar 1 16:29:45 2002 From: xscottgjunk at yahoo.com (Scott Gilbert) Date: 1 Mar 2002 13:29:45 -0800 Subject: pickle, cPickle, zlib, and the future Message-ID: <79b2b0bb.0203011329.79469c5b@posting.google.com> I'm serializing Python objects to one of three formats: Ascii, Binary, or Compressed (a, b, or c). I would like to be able to load them using just one function that correctly guesses how they were pickled. This is similar to what I'm currently doing: def dump_a(o): return cPickle.dumps(o) def dump_b(o): return cPickle.dumps(o, 1) def dump_c(o): return zlib.compress(cPickle.dumps(o, 1)) def load(s): if s[0] == 'x': return cPickle.loads(zlib.decompress(s)) else: return cPickle.loads(s) This only works if future enhancements to pickle/cPickle don't step on the first characted being 'x', and only if zlib always returns a string with the first characted 'x'. Looking in cPickle.c and pickle.py, I see that capital 'X' is used for type BINUNICODE, but no mention of lowercase 'x'. I can't find anything in zlib, but empirically it seems to be consistant. I figure this was either planned or lucky. If it was planned, a quick comment in the source would relax my fears that my code won't break in the next version of Python. If it was lucky, it might be nice to jump on the opportunity. So can I rely on the first character 'x' being reserved for zlib, and cPickle/pickle strings never starting with 'x'? Cheers, -Scott Gilbert (BTW: In cases somebody asks why I don't just prefix my dump strings saying where they came from: The dumps can be rather large (maybe 10's of megabytes), and I really don't want to have to create a multiple megabyte substring from the original.) From cfelling at iae.nl Sat Mar 2 19:00:23 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 3 Mar 2002 01:00:23 +0100 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: Emile van Sebille wrote: > "Carel Fellinger" ... >> I noted the smiley, but just in case someone might think you have a >> point: what would be the benefit of that? > Syntactic consistency with slice notation: > 5 :: [:5] as-3 :: [-3:] Bummers, forgot about that. > or maybe it should be: ;-) > 5 :: [:5] like -3 :: [:-3] alternatives, make things look even worse:) >> The tutorial could introduce it like: >> >> In python integers are objects too. And objects know how to do >> things, e.g. integer objects know how to add and just recently >> they learned how to count. Positive integers count from zero >> upto but not including the number itself, whereas negative >> integers count from -1 downto and including the number itself. > My my... I think you've converted... ;-) No no, I only think I understand it now:] I'm still not sure I like it, but on different grounds this time. > Couldn't we overload the '-' to reverse by itself? ;-) > >>> print " ".join([x for x in -s]) :) > My point, repeated a few times here , is that while I have no ... nice fussy pointing rambling snipped... > those who don't like iter(int), don't use it, or at least, . ;-) use it > as often as you use '>>'. > Bonus-points-for-each-point-found-here-ly y'rs, I just pick my points then:) low learning curve high `rememberability' (I don't want to look things up) One prefered way of doing it easy on the eyes (it should be extremely raedable) -- groetjes, carel From amir.hadar at israel.sun.com Wed Mar 20 08:16:58 2002 From: amir.hadar at israel.sun.com (Amir Hadar) Date: 20 Mar 2002 05:16:58 -0800 Subject: nested_scopes with execfile References: <10ecacee.0203190845.4fa4e35d@posting.google.com> Message-ID: <10ecacee.0203200516.32cb4d57@posting.google.com> Thanks for repalying. I suppose you are right but this is not the correct behaviore with nested_scopes on. As I anderstend execfile should behave as if I cut and past the file to that position my self (as appose to import). Therefore it should be enclosed with the env of the function "f()" in the Test1.py file. The resone why this is importent to me is because the Test2.py will be written by other ppl (Applicators) and I don't want them to get confused. I want to keep it simple. Thats way I don't want them to pass the above functions ("f1") to other functions ("f2") in order to be able to invock them. The only solution that I see is to execfile("Test2.py",globals(),globals()) but then I risk with name collision between the modules. Another solusion is to fix the Python Sources which seems to be not a simple task. --Amir Mohammed Lazreg wrote in message news:... > Here is what I believe is happening: > > when the interpreter enters the code block of f2 and finds f1 name, it > tries to resolve it using the nearest enclosing scope. So if you execute > Test2.py alone it will work because the enclosing scope is Test2.py > itself which does define f1 , but when you try to load Test2.py from > Test1.py the nearest enclosing scope of f2 scope is Test1.py which does > not define f1, hence the error.... > > If you change your Test2.py to this, it will works in both cases: > > ----------------- > def f1(): > print "OK it works" > def f2(arg): > arg() > > f2(f1) > ---------------- > > $ ../Python-2.2/python Test2.py > OK it works > $ ../Python-2.2/python Test1.py > OK it works > > > Mohamed > > Amir Hadar wrote: > > > Hi > > > > I've encountered a problem when executing a file within a function: > > > > #----- Test1.py ------------------ > > from __future__ import nested_scopes > > > > def f(): > > execfile("Test2.py") > > > > f() > > # EOF Test1.py ------------------- > > > > #--------Test2.py ---------------- > > def f1(): > > print "OK it works" > > def f2(): > > f1() > > > > f2() > > #EOF Test2.py -------------------- > > > > When executing the Test1.py the following error is displayed: > > Traceback (most recent call last): > > File "", line 1, in ? > > File "C:\PROGRA~1\Python22\Test1.py", line 6, in ? > > f() > > File "C:\PROGRA~1\Python22\Test1.py", line 4, in f > > execfile("Test2.py"); > > File "Test2.py", line 8, in ? > > f2() > > File "Test2.py", line 6, in f2 > > f1() > > NameError: global name 'f1' is not defined > > > > The reson that I need this is because I want to make a "Load" funtion > > that will execute the given file (e.g. Load("Yada.py")) and then will > > run a function in that file (e.g. def Init():). > > > > In the example I gave the second file ("Test2.py") is loaded to the > > local environment of the function f() in the first file (Test1.py). > > Therefore the functions f1 and f2 are in that env. Now, When f2 calls > > f1 it should resolve its variables in the enclosing environment which > > is the env of f (Test1.py) but it doen't. > > > > Help Me. > > Amir. > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > > This message has been 'sanitized'. This means that potentially > > dangerous content has been rewritten or removed. The following > > log describes which actions were taken. > > > > [ score: 10 ] > > 00189 Split long word(s) in header. > > > > Anomy 0.0.0 : sanitizer.pl > > $Id: sanitizer.pl,v 1.35 2001/02/01 00:10:46 bre Exp $ From sketerpot at chase3000.com Mon Mar 4 18:34:49 2002 From: sketerpot at chase3000.com (Peter Scott) Date: 4 Mar 2002 15:34:49 -0800 Subject: How do you print? Message-ID: <659f82ff.0203041534.34ad2f91@posting.google.com> How can you print to a printer in Python? I know that you can do platform-dependant things like using lpr (on UN*Xlike systems) or "wordpad -p myfile" on windows, but that doesn't seem to be the Python Way. I just need to print--for now--plain text. Can anyone help me? -Peter From mwh at python.net Sun Mar 3 12:04:24 2002 From: mwh at python.net (Michael Hudson) Date: Sun, 3 Mar 2002 17:04:24 GMT Subject: Why isn't pychecker mentioned prominently? References: <3C80ED0B.42292C99@tds.net> <3C811C18.1020208@attbi.com> Message-ID: Pete Shinners writes: > Edward K. Ream wrote: > > I just found out about pychecker (http://pychecker.sourceforge.net/) and > > I am wondering why it isn't mentioned prominently all over the Python > > web site: the tutorial, the links on the left and side of the home page, > > topics guides, general reference etc. I found out about it from reading > > one of Guido's recent presentations in which he mentions it as one of > > his favorite Python tools. So why is pychecker such a secret? I think partly because it's fairly new. > i heartily agree. i now try to use pychecker on absolutely everything > i do. i really wish it came as part of the standard distribution. it > could easily be enabled on the commandline with some sort of -wall. > > heck, python recently added the full "warning" framework. it seems > like an ideal place to tie that all in. then users can control if the > pychecker warnings were silenced, printed, or treated as exceptions. I think pychecker integration is a goal of 2.3. IIRC, one problem is that pychecker currently works by analysing bytecode, which is totally unportable to jython. It would be nicer if it used the compiler package to work off the syntax tree, but noone's gotten round to amending it yet. Patches welcome, I suspect. now-where's-that-cloning-machine-ly y'rs m. -- There are 'infinite' number of developed artifacts and one cannot develop appreciation for them all. It would be all right to not understand something, but it would be imbecilic to put judgements on things one don't understand. -- Xah, comp.lang.lisp From emile at fenx.com Thu Mar 21 10:16:51 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 21 Mar 2002 07:16:51 -0800 Subject: __file__ for relative imports References: <2OVMEJA7kKm8EweI@jessikat.demon.co.uk> Message-ID: "Michael Hudson" > No. I think there's a bug on sf about this. > > It would be a bit of a pest to implement, I think, but I may be > missing something. > If it's a bug now and you implement a bit of a pest, is it better? -- Emile van Sebille emile at fenx.com --------- From weeks at vitus.scs.agilent.com Wed Mar 6 13:14:29 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Wed, 6 Mar 2002 18:14:29 +0000 (UTC) Subject: HP-UX 10.2 deprecated? References: <1015292901.342132@cswreg.cos.agilent.com> Message-ID: <1015438469.628881@cswreg.cos.agilent.com> Michael Piotrowski (mxp at dynalabs.de) wrote: : When the ANSI C compiler is installed, cc always calls this compiler, : but without -Aa or -Ae it operates in K&R mode on 10.20. To ensure : that -Ae is always used, you can ... say : : CC='cc -Ae' ./configure With this, "make" does indeed create an executable. But "make test" fails both times on test_threads, dying at the end with: test_thread *** Termination signal 14 Stop. Oddly enough, signal 14 (ALRM) is ignored the first time "test_thead" is listed. Greg From gerhard at bigfoot.de Tue Mar 5 02:48:50 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 5 Mar 2002 07:48:50 GMT Subject: Status of PEP's? References: <7xwuwrofhk.fsf@ruckus.brouhaha.com> Message-ID: Bengt Richter wrote in comp.lang.python: > On Mon, 04 Mar 2002 19:59:03 -0800, David Eppstein wrote: > >>In article <7xwuwrofhk.fsf at ruckus.brouhaha.com>, >> Paul Rubin wrote: >> >>> Usually the term "natural numbers" don't include zero. >>> http://mathworld.wolfram.com/NaturalNumber.html >> >>I think "usually" is an exaggeration. For instance, a better authority >>than Weisstein, Ebbinghaus et al's _Numbers_ (Springer Graduate Texts in >>Mathematics 123, 1991, p. 14) disagrees. > > [...] > FWIW again, Wordnet agrees also: > [...] Just adding to the noise: gerhard at lilith:~$ dict "natural number" 2 definitions found >From WordNet (r) 1.7 [wn]: natural number n : the number 1 and any other number obtained by adding 1 to it repeatedly >From The Free On-line Dictionary of Computing (09 FEB 02) [foldoc]: natural number An {integer} greater than or equal to zero. A natural number is an {isomorphism class} of a finite set. (1995-03-25) At Uni, my two maths profs disagreed, too. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From amoustafa at pobox.com Tue Mar 19 23:31:35 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Wed, 20 Mar 2002 04:31:35 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> Message-ID: <3C98108D.5010002@pobox.com> Peter Hansen wrote: > Ahmed Moustafa wrote: > >>1. Where can I find an unbiased comparison between Java and Python? >>2. Will Python dominate? >>3. Who does support Python? >> > > Having read the other responses, you may see that your questions > are a little simplistic. > > I think if you told us what your purpose is in asking the questions, > the answers would be more useful and direct. _Why_ do you want > to know? I'm interested in knowing which skills will(are) being looked for. > > -Peter Ahmed From aahz at panix.com Sat Mar 9 10:56:44 2002 From: aahz at panix.com (Aahz Maruch) Date: 9 Mar 2002 07:56:44 -0800 Subject: Turn string into function call References: <1f5252d4.0203080545.3861adec@posting.google.com> Message-ID: In article , Grant Edwards wrote: > >I think it would also be good to mention the eval() method, and >the locals() method (and the problems with both). I started to >write up a FAQ yesterday but didn't get very far... You can add that to the new FAQ entry at http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.103.htp -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From fdrake at acm.org Mon Mar 18 13:33:30 2002 From: fdrake at acm.org (Fred L. Drake) Date: Mon, 18 Mar 2002 13:33:30 -0500 (EST) Subject: [development doc updates] Message-ID: <20020318183330.4F9B618ED52@grendel.zope.com> The development version of the documentation has been updated: http://python.sourceforge.net/maint-docs/ Documentation for 2.2.1 release candidate 1. From mcherm at destiny.com Tue Mar 26 11:03:42 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 26 Mar 2002 11:03:42 -0500 Subject: question on slices Message-ID: <3CA09BDE.9020907@destiny.com> > This makes sense and cleared it up. > Thanx > > Rob Happy to help! -- Michael Chermside From jjl at pobox.com Thu Mar 21 16:07:23 2002 From: jjl at pobox.com (John J. Lee) Date: Thu, 21 Mar 2002 21:07:23 +0000 Subject: "Zope-certified Python Engineers" [was: Java and Python] In-Reply-To: References: Message-ID: On Thu, 21 Mar 2002, Laura Creighton wrote: > > ( Or maybe this begs for a Slashdot like system to > > distribute the review, grading and selection of projects. ) [...] > You want something more like the scientific reviewing of a technical > paper than slashdot's 'all you need to vote is a pulse'. Otherwise This will not happen, as I'm sure you realise. :) Who would do it?? > in your selection committee). The best way to do this is to provide > a certain amount of meta-data with your assessment -- so we can > find out not only that Steven Majewski thinks that XXX is cool, but > also that Steven Majewski has a reputation around here, and most > people think that Steven Majewski's opinion of something is valuable. [...] > I think that this sort of metadata belongs in the sort of > cataloging system we should have to implement PEP 262, as well. > Of course, I am biased -- AB Strakt is building something to do > this, because we think that its a huge world problem that needs > fixing. There seem to be two ways to search for documents in a useful way, both of which are useful. One is to have lots of carefully and expensively maintained metadata. The other is to self-consistently rank the documents by looking at the links between them, as does Google (one of the wonders of the modern world, IMO). I think Google has demonstrated that ranking is better done using the self-consistent approach (though perhaps a little bit of metadata added to this approach would work even better? -- for example, Google has no conception of author AFAIK). In general, and for a Python archive in particular, I guess there are two problems: which metadata, and which software. So, what's wrong with the web + Google (not saying there isn't anything wrong, just interested in how you would improve on it)? [OT: A question I've asked many times and got no answer to is 'why has nobody done self-consistent ranking for academic papers'? I fear the answer is simply that most of the data is owned by a small number of companies who, as a result, have no real incentive to advance the state of the art. Still, maybe somebody out there is trying to do it...] John From deathtospam43423 at altavista.com Tue Mar 19 20:42:45 2002 From: deathtospam43423 at altavista.com (A.Newby) Date: 20 Mar 2002 01:42:45 GMT Subject: Q: Sound production with python? Message-ID: Being a beginner fiddle player, as well as a beginner python programmer, I want to write a little prog that trains the sense of pitch. How envisage it working is thus... It plays a simple 4 note melody, then repeats the melody with one of the notes (selected randomly) slightly off pitch ... say by 20% or 10% or 5%. The user then has to detect which note was off. What modules and commands should I use to generate this sounds? What's the best way to go about it? -- cdewin at dingoblue.net.au From martin at v.loewis.de Sat Mar 30 11:50:33 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 17:50:33 +0100 Subject: [Python-Dev] RE: PEP 285: Adding a bool type In-Reply-To: <200203301342.g2UDgTE01572@pcp742651pcs.reston01.va.comcast.net> References: <200203301342.g2UDgTE01572@pcp742651pcs.reston01.va.comcast.net> Message-ID: Guido van Rossum writes: > > Interestingly enough, the exception message says "__nonzero__ should > > return an int" but really means "__nonzero__ must return an int". > > You've been staring at standards too much, haven't you? The > difference between MUST and SHOULD isn't as clear-cut as most > standards people use them. Given Andrew's remark, it really should be "__nonzero__ shall return an in int" :-) Regards, Martin From greg at cosc.canterbury.ac.nz Sun Mar 3 19:20:17 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 04 Mar 2002 13:20:17 +1300 Subject: Status of PEP's? References: Message-ID: <3C82BDC0.C6A65F5F@cosc.canterbury.ac.nz> James_Althoff at i2.com wrote: > > > "for something" loops over all values of the variable that make > > "something" true. > > But that kind of definition isn't comprehensive enough because, for > example, it says nothing about the order of the variables as processed by > the for-loop. Obviously it doesn't serve as a complete *definition* of the semantics, but the complete definition is at least consistent with that view, for both "for i in x" and "for x < i < y". -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Wed Mar 13 17:36:00 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Mar 2002 22:36:00 GMT Subject: [ANN] istring 1.0.1 released; announce list created References: <3C86047F.1080601@stroeder.com> <20020313201539.2995aad0.andreas@mtg.co.at> Message-ID: On Wed, 13 Mar 2002 21:30:47 +0300, Oleg Broytmann wrote: >On Wed, Mar 13, 2002 at 08:15:39PM +0100, Andreas Kostyrka wrote: >> And what about: >> db.query("""SELECT foo, bar >> FROM %(table)s >> WHERE rsrc_id = %(rsrc_id)d >> AND name = '%(name)s'""" % locals()) >> >> pure standard Python :) > > This will fail if name = "O'Hara". Or name = 'Tutti"""Frutti'. > Ok, then how about: --- >>> table = 'theTable' >>> rsrc_id = 1234567 >>> class QEsc: ... def __init__(self,s): self.sesc = "\\'".join('\\"'.join(s.split('"')).split("'")) ... def __str__(self): return self.sesc ... >>> for badname in ["O'Hara", 'Tutti"""Frutti']: ... name = QEsc(badname) ... print """SELECT foo, bar ... FROM %(table)s ... WHERE rsrc_id = %(rsrc_id)d ... AND name = '%(name)s'""" % locals() ... SELECT foo, bar FROM theTable WHERE rsrc_id = 1234567 AND name = 'O\'Hara' SELECT foo, bar FROM theTable WHERE rsrc_id = 1234567 AND name = 'Tutti\"\"\"Frutti' >>> --- "pure standard Python :)" Regards, Bengt Richter From danieln at stud.cs.uit.no Wed Mar 13 07:53:40 2002 From: danieln at stud.cs.uit.no (Daniel Nygård) Date: Wed, 13 Mar 2002 13:53:40 +0100 Subject: MySQL Library or Interface? References: Message-ID: "Stephen Cox" wrote in message news:dIHj8.24208$nw3.3259904 at typhoon1.se.ipsvc.net... > Is there a MySQL library or some kind of framewrok available for Python? download this module: http://www.mysql.com/downloads/api-python.html Daniel Nyg?rd From spencer at efn.org Mon Mar 4 15:11:19 2002 From: spencer at efn.org (Spencer Ernest Doidge) Date: Mon, 4 Mar 2002 12:11:19 -0800 Subject: Windows GUI - which way? In-Reply-To: <3C83D003.411FEE3F@ccvcorp.com> References: <3C7EC855.5844B19F@engcorp.com> <3C83D003.411FEE3F@ccvcorp.com> Message-ID: Thank you, Jeff. It happens that I want to do all this with scripts that are all under my control, so there is a lot of good news here in your answer. One further question: Should the two processes communicate with each other via mmap? Spencer Doidge www.spencerdoidge.com On Mon, 4 Mar 2002, Jeff Shannon wrote: > > > Spencer Ernest Doidge wrote: > > > I want to maintain and use a library of Python scripts. I want to invoke > > ... Jeff wrote: > > The answers to your question depend on whether you intend to design the library > scripts specifically for this purpose, or if you're intending to use > "off-the-shelf" scripts from elsewhere. If you're able to modify the scripts to > ... From bergeston at yahoo.fr Thu Mar 14 11:34:40 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Thu, 14 Mar 2002 17:34:40 +0100 Subject: Why I think range is a wart. References: Message-ID: Thanks Christopher for your clear and intelligent response. I could only add that it is always possible to use a dictionary with an ordered range of integers as keys (or even as values). In some cases, it should probably make sense. Ironically, I could ask "why not add indices in the dictionary type, it is sometimes usefull" ? Let's keep things simple and understandable : - lists are ordered sets, - dictionnaries are "keyed" sets. And if somebody needs something richer, just combine or inherit from those types (btw many many thanks to the BDFL and his team for Python 2.2, for the little that I know it, I really appreciate it). B. "Christopher A. Craig" wrote in message news:mailman.1016042063.7531.python-list at python.org... Gon?alo Rodrigues writes: > For starters, range (and xrange) is a perfectly sensible, reasonable and > useful built-in. But the biggest use I make of it is in iterating through > a list, e.g. as in > > for index in range(len(mylist)): > > > and in the body I need to make use of the indexes. I am not > sufficiently qualified to say if this is Pythonic or not, but I find > myself doing this quite often. I don't understand how range is a reasonable and useful built-in if this use is not. If you have a list [2, 3, 5, 7, 11] and you want to iterate through it you don't need range: for item in list: If, on the other hand, you want to iterate though the indicies of said list rather than the items themselves you need to come up with some way to generate a zero based list of integers up to one less than the size of the list (i.e. a list of indicies). When you create this list you aren't doubling information that the list already has. A list does not contain a list of indicies into itself. The list knows its elements, in order, and how many elements it has. From this you can generate a list of indicies, but there are no 'keys' stored in a list object like there are in a dictionary. To go from the information that is stored in the list (an ordered list of elements, and the size of said list) to the information you need to iterate through indicies (an ordered sequence of indicies valid for the given list) you need to take the length of the list (N), and create a new list of N integers from 0 to N-1. 'range(len(mylist))' says precisely that. I don't see how this is the least bit kludgey. .keys() and .items() methods on lists seem odd to me. That is inforamtion that the list does not contain. Sure it can easily be generated given information the list does contain, but why can't the programmer generate it himself from the same information? -- Christopher A. Craig Is Peal Better Than Python? No, no. Quicker, easier, more seductive. From kennedy.bill.nospam at freeuk.com Thu Mar 7 02:59:21 2002 From: kennedy.bill.nospam at freeuk.com (William Kennedy) Date: Thu, 07 Mar 2002 07:59:21 GMT Subject: NotePad Lite Message-ID: Does anyone use the NotePad series for writing Python code, if so have they built a python library that I can have. --- William Kennedy remove the .nospam from my email address From gh_pythonlist at gmx.de Fri Mar 8 10:38:01 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 8 Mar 2002 16:38:01 +0100 Subject: Where is quote (again)? In-Reply-To: <1f5252d4.0203080721.3bfc5c14@posting.google.com> References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: <20020308153801.GD2591@lilith.hqd-internal> Le 08/03/02 ? 07:21, N Becker ?crivit: > Back in 1999, I asked "where is quote?". I was looking for > a way to quote a function (delay evaluation). > > I wonder if there is anything new. It looks to me that the > best answer is to use lambda. > > example: > > def f(): > return lambda: os.chmod(""/root/.rhosts", 0644) > > def g(): > f() Just out of interest: what's that good for? Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 10.4 ?C Wind: 3.1 m/s From tejarex at yahoo.com Sun Mar 31 19:41:08 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Mon, 01 Apr 2002 00:41:08 GMT Subject: PEP 285: Adding a bool type References: <3CA751EF.10F25F2D@ndh.net> Message-ID: "Stefan Schwarzer" wrote in message news:3CA751EF.10F25F2D at ndh.net... > There are, as pointed out, too much cases where bool/int interactions > lead to surprises because the behaviour of the bool type does not live > up to its abstract concept that it should have. This is confusing; ... This is precisely why I now think that the proposed formalization of Python truth value system should not be called 'bool'. Too many people expect it to be like it "should' be, rather that how it was designed. Python truth values, like, for instance, Python lists, were designed on a pragmatic basis without necessarily being constrained by other similar models. Terry J. Reedy From angie4325 at hotmail.com Tue Mar 5 20:53:26 2002 From: angie4325 at hotmail.com (angie4325 at hotmail.com) Date: Tue, 5 Mar 2002 17:53:26 -0800 (PST) Subject: how you been? Message-ID: <200203060153.RAA14181@deteconline.com> Below is the result of your feedback form. It was submitted by (angie4325 at hotmail.com) on Tuesday, March 5, 2002 at 17:53:26 --------------------------------------------------------------------------- : Hey, I am a 19/f with a webcam my name is angie! If you're interested in meeting myself or other people of all races, ages, of the same or opposite sex and want to watch them on their webcams for free, then you need to try this! It's called it's a dating program designed for people who are sick of the same old bar scene & want to meet new people! It's simple, all you do is signup & start looking! The best part is...it's ALL 100% free for you! ~Enjoy! FREE WEBCAM DATING! IF you would like to be removed from this reply with the message "remove" thanks. --------------------------------------------------------------------------- From gimbo at ftech.net Thu Mar 14 08:57:37 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Thu, 14 Mar 2002 13:57:37 +0000 Subject: SF vs. Lynx (was Re: zlib vulnerabilities and python) In-Reply-To: References: Message-ID: <20020314135737.GC1527@andy.tynant.ftech.net> On Thu, Mar 14, 2002 at 08:47:31AM -0500, Aahz wrote: > OTOH, I still can't submit my stupid bug report AFAICT. Is there anyone > who uses Lynx to access SF? No, but have you tried "links"? It's a command-line browser like lynx, but somewhat more featureful. Apologies if this is old news. http://links.sf.net/ (sf.net? oh, the irony...) -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From mickey at tm.informatik.uni-frankfurt.de Sat Mar 2 20:37:26 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 3 Mar 2002 03:37:26 +0200 Subject: Possible to fake object type? References: <3c80e76b@nntp.server.uni-frankfurt.de> <3c80fb6d@nntp.server.uni-frankfurt.de> <3c812217@nntp.server.uni-frankfurt.de> Message-ID: <3c818c66@nntp.server.uni-frankfurt.de> Chris Liechti wrote: >> This is basically the same as I have now. But the thing is: >> __getattr__ only gets called when the attribute _doesn't_ exist, > > you're right - i thought this has changed in py 2.2 but i never used > it that way. > > maybe you could replace your classes __dict__ with an empty one so > that __getattr__ get called? Aaah... this is it! Well, not exactly, but it gave me the idea to override "by-hand" the (few) methods, which the baseclass implements but which should rather be reflected to the "contained" class. My code now looks like class Dockable( gtk.HandleBox ): "Repraesentiert eine andockbare Werkzeugleiste" _meth = ["set_style"] def __init__( self, Class ): gtk.HandleBox.__init__( self ) self.__dict__["_child"] = Class() self.add( self._child ) for meth in self._meth: self.__dict__[meth] = getattr( self._child, meth ) def __getattr__( self, attr ): return getattr( self._child, attr ) It might not be a "totally political correct"[*] solution, but it works :) Thanks your help. Yours, Mickey. [*] which brings the question, when and how justified can a "bad design" be, if it saves you a whole lot of code, especially for many ugly special cases, which can't be a sign of good design, either? Opinions? From tanzer at swing.co.at Sat Mar 9 04:34:01 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Sat, 09 Mar 2002 10:34:01 +0100 Subject: PEP 276 final version In-Reply-To: Your message of "Fri, 08 Mar 2002 12:50:47 PST." Message-ID: James_Althoff at i2.com wrote: > In light of the "Parade of PEPS" message, I also have asked the PEP > administrator to move PEP 276 to the withdrawn/rejected group. > > Many thanks to all who participated in the PEP 276 discussions. I didn't want to add to the noise, but now I want to say thank you for the way you're admitting defeat. IMHO, features like you proposed are better served by Python modules than by syntax changes (technically, your proposal isn't a syntax change but I think the motivation was just syntactical). Opposed to a syntactical feature, a generator exported by a Python module is: - explicit (better than implicit ) - self documenting - one less special case - less likely to participate in unexpected interaction of features - an object in its own right (can be passed around, introspected, ...) -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From bokr at oz.net Sat Mar 9 00:55:38 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 05:55:38 GMT Subject: instantiating a class References: <3c899c2d@news.cc.umr.edu> Message-ID: On Fri, 8 Mar 2002 23:23:08 -0600, "Carl" wrote: >I'm an intermediate-level python programmer and use classes all the time, >but a weird problem is frustrating me. > >In my main program: > > >import lj_connect > >blah blah code > >talkserver = lj_connect.lj_connect(userinfo) > > what happens if you go to the directory where lj_connect.py is, run python, and do the above (minus blah blah ..) interactively? if the import succeeds, try dir(lj_connect) to see whether the spelling of the class name might have gotten glitched, or whatever. >the start of lj_connect.py is this: > >class lj_connect: > def __init__(self,basic_data): > self.uinfo = basic_data > > >I'm getting an AttributeError saying module lj_connect has no attribute >lj_connect. Originally the lj_connect code was in the same file as the main >program until I moved it for readability's sake. Can anyone see a problem? >Thank so much! Looks like it ought to work. Did you accidentally include class lj_connect in a """comment""" ? The dir(lj_connect) will tell. Regards, Bengt Richter > >Carl > > From claird at starbase.neosoft.com Tue Mar 12 09:54:22 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 12 Mar 2002 08:54:22 -0600 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> Message-ID: In article <3c8e0911_1 at news.bluewin.ch>, Samuele Pedroni wrote: > >Tim Churches wrote in message >mailman.1015926440.9915.python-list at python.org... >> So asks an article on Mark in the IT section of today's Sydney Morning >> Herald - see >> http://www.it.mycareer.com.au/news/2002/03/12/FFXMFP3LOYC.html >> > >It's probably just the journalist's fault but I find the article frivolous >and vague. > >What he is concretely working about? What he contretely want to work about? >etc... There are many possible integration philosophies and technologies? >and both aspects tech/philosophy are far from irrelevant. >(The frozen Python.NET as a full fledged Python or limited >and altered, a new attempt in that direction, bridging ...) > >Is he working in stealth-mode or it is just MS-kind PR ? > >What kind of Python technologies will the book treat? > >Just some academic questions. regards. > > > > > > My background is academic. I spend a lot of time nowadays journalistically. I can assure you that this article is *not* frivolous or vague--at least not in comparison with most of what appears in the popular and trade presses. My best to Mark, in any case. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From bh at intevation.de Fri Mar 8 07:07:03 2002 From: bh at intevation.de (Bernhard Herzog) Date: 08 Mar 2002 13:07:03 +0100 Subject: Integers class...? References: <3C882BF0.B7B6A239@cosc.canterbury.ac.nz> Message-ID: <6qd6yf461k.fsf@abnoba.intevation.de> Greg Ewing writes: > The only thing you don't get from that is an > easy way to iterate backwards. The best I can > think of is > > for x in reverse(ints[0:11]): Slices support a step parameter, so for x in int[9:-1:-1]: should work, I think. Whether this is really so much more convenient than range or xrange is a different matter. The fact that this new feature could be defined to create an iterator could be an advantage, tough. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From anthony_barker at hotmail.com Fri Mar 1 11:12:21 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 1 Mar 2002 08:12:21 -0800 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> Message-ID: <899f842.0203010812.6151d817@posting.google.com> "DeepBleu" wrote in message > Deitel and Deitel book on Python? I personally would not touch it. Give me > a book written by Lutz, Holden or Hammond any time. But not from the > establishment of Deitel. I bet you they do not even know how to program in > Python. All their books are churned out by what resembles an > industry-complex with standard issue. > Long ago I discovered a mistake in their old C++ How to Program. I sent > them an e-mail. The answer still brings vivd memories of when you feel like > throwing up. Arrogant bunch of oppurtunists who are not worth the price of > the paper their books are printed on. > You want books on Python: Buy Beazley, Lundh, Holden, Hammond, Greyson > etc.... > Leave Deitel alone! > DeepBleu I agree with you to a point. They don't seem passionate about programming, and the books are definitely cookie cutter. That said, more books on the python landscape is a good thing. And as the previous poster said, programming books are a personal thing. Personally I found a lot of the best material is online. Beazley's presentations are excellent, as is his dead tree book. Eckel's, "The thinking in Python", is very good. For beginners the "How to Think Like a Computer Scientist" I found better that most dead tree books (http://www.ibiblio.org/obp/thinkCSpy/). I would love to see books on Algorithms with Python (makes a perfect fit), and more advanced topics such as threads and extending python. From newsfroups at jerf.org Tue Mar 5 14:31:54 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Tue, 05 Mar 2002 19:31:54 GMT Subject: Order of constructor/destructor invocation References: <3C8466F9.2080903@jerf.org> <_f7h8.5541$aP6.6480@rwcrnsc54> Message-ID: <3C851D41.3000902@jerf.org> Reginald B. Charney wrote: > In this idiom, I am not trying to traverse a tree. I am trying to execute > what I declare. Also, this idiom allows for very shallow dependencies. There > is no inheritance here. In this example, I am trying to write: > > h = HTML(); b = BODY(); p = PHP() > > Note that there is no interdependencies. But there ARE interdepencies. If you didn't care about the order, you wouldn't be upset about 'destructors' being called in the wrong order. Thus, dependencies. You are trying to offload the order depencies onto the destructor rules, but the destructor rules aren't hearing of it. Additionally, the style you show is fundamentally too weak to work with HTML. h = HTML() b = BODY() l = LIST() le = LISTELEMENT() p = PARAGRAPH() Is the paragraph a child of the list element, or not? This is merely one of the hundreds of similar situations you'll encounter in HTML. You can't generate HTML this way. h = HTML() he = HEADER() t = TITLE() b = BODY() Now what? Will body be a child of title? And again, HTML stands in for ANY tree structure. You ***cannot*** flatten a tree structure without losing data. You have developed a style of coding that is *extremely* dependent, dangerously so, on very, very particular details of a single, increasingly outdated* language. Your style has numerous disadvantages, and no significant advantages I can see. I echo the recommendations of another poster to use a real HTML library, or to do something like what I proposed, or, if nothing else, to simply declare HTMLStart and HTMLEnd functions. I don't know of any interpreted language that guarentees, as part of the language specification, destructor order. For that matter, many non-interpreted languages don't specify it either. In fact, even IF C/C++ specifies the destructor order, which I don't care to look up right now, I would not be surprised that not all compilers will destruct in that order at the end of a function. Perhaps you'd like functional? HTML(BODY(PHP())) No, it's not as simple as what you show, but that's life. It can be adjusted to work better then that. *outdated C: C/C++ has a well known set of advantages and disadvantages, which I have no beef with. The point here is that nobody's trying to make a better C nowadays. Unless you write your own, you may very well NEVER find a language with destructors that are as user-controllable as C. Most of us are happy to give up that responsibility, and concentrate on writing code. From m.faassen at vet.uu.nl Thu Mar 14 18:12:36 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 14 Mar 2002 23:12:36 GMT Subject: Why I think range is a wart. References: Message-ID: John Roth wrote: > It happens to me too, mostly when I'm using a sliding window > type algorithm, that is, I need to look at two adjacent members > of the list. You can't do this easily by iterating through the list; > unrolling the first entry and the last entry are a pain. > Is there a way of handling this nicely? Somehow I doubt it. I occasionally use this: last_element = list[0] for element in list[1:]: # some_operation on element and last_element here last_element = element Do you mean that by unrolling the first and last entries? I mean, there's not much unrolling going on here. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From sholden at holdenweb.com Fri Mar 29 08:37:53 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 08:37:53 -0500 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: "Benjamin Schollnick" wrote ... > In article , > Steve Lamb wrote: > > > case: Don't like it. We already have means to do what a case does and do it > > more elegantly. It would add a needless redundant portion to the language. > > > We do??? > > We have the IF .... ELIF statement structure, which can be used to > simulate a case statement, but it is not as clear nor as neat as > the case statement. > [case statement suggestions ] > > And it can be optimized to: > > CASE X of: > 0,6 : DO_THIS() > 2 : DO_THIS (2) > 4 : DO_THIS (x+2) > ELSE: > DO_NOT_DO_THIS() > OK, how would the above handle the case where X == (0,6)? Clearly we could explicitly add parentheses to handle tuple-valued case variables, but would we then have to also lable the singleton case values as tuples? case X of: (0, 6, (0,6)): this() (2,): that() (4,): the_other() Doesn't look quite so clean now, though, does it? > if Z == "ZEBRA": > DO_THIS (ZEBRA) > > The key issue is that I believe the IF / ELIF / ELSE statement can be > used with multiple variables during the IF ELIF..... At least I remember > using it that way.... > I'm not sure what this statement means. With an "if" construct you can compare as few or as many variables as you like to form a single Boolean result. And clearly if/elif/elif/else can handle any number of cases anyway. Ultimately the only way to implement a case statement in its full generality is to use the lower-level if/elif/elif/else construct, so what we are discussing here is syntactic sugar. > The CASE is cleaner, and can only be used to compare a SINGLE variable > with multiple values. And I believe it's easier to maintain.....(And > can be optimized easier). > I don't. By the way, there's NO NEED TO SHOUT! ;-) regards Steve From a.martin at perfectwww.de Wed Mar 13 12:20:03 2002 From: a.martin at perfectwww.de (Andreas Martin) Date: 13 Mar 2002 09:20:03 -0800 Subject: Ho to use a regular expression group reference as hash key References: Message-ID: Ahh.. the % substitution operator is perfect. First I didn't understand what to do with an %s format string. Thank you "Raymond Hettinger" wrote in message news:... > Maybe the % substitution operator will help. > > >>> person={"entry1":"value1","entry2":"value2"} > >>> target = 'A sample sentence with %(entry1)s and %(entry2)s' > >>> print target % person > A sample sentence with value1 and value2 From cliechti at gmx.net Fri Mar 29 18:19:36 2002 From: cliechti at gmx.net (Chris Liechti) Date: 30 Mar 2002 00:19:36 +0100 Subject: Help with POST request. References: Message-ID: Gustavo Cordova wrote in news:mailman.1017440584.2947.python-list at python.org: ... > Well, I'm having some trouble accepting POST requests. ... > ==========================================================import > BaseHTTPServer > > SIMPLE_WEB_FORM = """ ... a little web page in HTML ...""" > > class TestHTTPRequestHandler (BaseHTTPServer.BaseHTTPRequestHandler): > def test_response(self): > # Always so positive. > self.send_response(200) > self.send_header("Content-type", "text/html") > self.end_headers() > > def do_GET(self): > self.test_response() > self.wfile.write(SIMPLE_WEB_FORM) > > def do_POST(self): > self.test_response() > print "-" * 60 #find out length of input data length = int(self.headers.getheader('content-length')) #read data print self.rfile.read(length) > print "-" * 60 > self.wfile.write(SIMPLE_WEB_FORM) > > BaseHTTPServer.test(TestHTTPRequestHandler, BaseHTTPServer.HTTPServer) > > ========================================================== > OK, the problem is I can't ever see what's being sent via POST, > it hangs when reading from the rfile object. > > I'd appreciate any and all comments. i've replaced the read() above with a solution that works for me. chris -- Chris From marduk at python.net Mon Mar 18 18:04:07 2002 From: marduk at python.net (marduk) Date: 18 Mar 2002 17:04:07 -0600 Subject: Declare list of large size In-Reply-To: References: Message-ID: <1016492648.2016.4.camel@berkowitz> On Mon, 2002-03-18 at 16:44, Aaron Ginn wrote: > > Perhaps I've just glossed over this in the documentation, but what is > the simplest way to declare a list of large size? Is there something > analogous to the following in C: > > int list[100]; > list = [0]*100 --m Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From netlangau at yahoo.com.au Sun Mar 10 20:18:11 2002 From: netlangau at yahoo.com.au (Patrick) Date: Mon, 11 Mar 2002 12:18:11 +1100 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: "Aahz Maruch" wrote in message news:a6g7ra$lm6$1 at panix2.panix.com... > > But are there any tasks for which C++ (or C++/Python) is really better > than C/Python? One example is an extremely complex and long-running simulation in which the time-critical components are a very substantial chunk of the project. In those (rare) situations you need ruthless efficiency with slightly better than rudimentary abstraction capabilities. C++ fits the bill, but only if every processor cycle and every byte counts. The vast majority of programmers will never go anywhere near a project like that. Even "real programmers" very seldom do. And you can virtually guarantee that if somebody is idiot enough to claim that knowing C++ is either necessary or sufficient for being a real programmer, they will never work on a project that actually needs C++. Unless somebody has already spent years learning C++, I think they're much better off using either (a) one vastly more powerful yet still reasonably efficient language like Common Lisp, or (b) two lean and vicious languages like C and Python - both small and simple, both perfectly suited to their respective domains, and both complementary. Either way you end up with very good performance and far less mental friction. If the OP is still around, I'd recommend learning C and Python at this stage. In spite of what your friends tell you, C++ is *not* a powerful language in the sense that it has one of the worst power/complexity ratios of any language in use today. Don't mistake effiency for power. If two people of equal ability started programming today, one learning C and Python, the other learning C++, I'd wager that the C/Python guy will be running conceptual rings around the C++ guy 12 months from now. Power in a language is all about being able to express your most complex thoughts with as few arbitrary difficulties as possible. Some languages help. Some hinder. From irmen at NOSPAMREMOVETHISxs4all.nl Sun Mar 24 08:40:48 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Sun, 24 Mar 2002 14:40:48 +0100 Subject: [ANN] Pyro 2.5 available References: Message-ID: For the people out there that are interested in Pyro; > You can get the latest Pyro version (2.5) at http://pyro.sourceforge.net > > What's new: > New URIs to make object lookup even simpler I forgot to mention: for the new PYRONAME:// and PYROLOC:// URIs to work, I had to make some changes to the Pyro Daemon. The Daemon itself is now also a Pyro object. This means you can access the Daemon remotely. I'm not sure if this is a good approach. On one hand, it is quite flexible, because we can now get interesting information from the Daemon, such as all registered objects. On the other hand, I see a potential security and stability risk. You don't want anybody to access the Daemon... right? What do you think? I'm very interested in your opinion about this. Thank you Irmen de Jong PS What's all that fuss about the new URI formats? Well, let me show you: #! /usr/bin/env python import Pyro.core Pyro.core.initClient() object=Pyro.core.getProxyForURI("PYRONAME://:Test.MyObject") # lookup through Name Server print object.method() object=Pyro.core.getProxyForURI("PYROLOC://localhost:MyObject") # direct lookup print object.method() # that's all :-) From dsavitsk at e-coli.net Thu Mar 21 18:31:51 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 21 Mar 2002 23:31:51 GMT Subject: quick win32 pipe and objects question References: Message-ID: the answer is to pickle first. "dsavitsk" wrote in message news:X0sm8.575$d7.169869 at newssrv26.news.prodigy.com... > when writing and reading from a pipe, is it okay to do something like ... > > >>> t = (0, 1, 2, 3) > >>> r = win32pipe.CallNamedPipe(pipename, t, 512, 0) > > of should i pickle t first? > > -d > > From jhg at galdon.com Thu Mar 14 16:57:33 2002 From: jhg at galdon.com (Juan Huertas) Date: Thu, 14 Mar 2002 22:57:33 +0100 Subject: zlib and performance Message-ID: I have a file, with records generated using cPickle and zlib, for example: record1=['juan',0,123.456,'Madrid',23,'Granada','Spain'] usualy in the real case the length of the list is 30 or 40. My file has 60,000 records aprox. For archive i use, a btrieve file: f[id]=compress(dumps(record1)) f..sync() When i need to read the whole file, i use: r={} for k in f.keys(): r[k]=loads(decompress(f[k])) and in Windows 2000 (256 Mb ram) P-III 1000 Ghz Python 2.1.2 this takes 4 sec aprox: 1 sec for retrieving f[k] 2 sec for decompress 1 sec for loads If i need, read the whole file a continuation, i proceed: r={} # This takes 3 seconds aprox !!! (Why?) for k in f.keys(): r[k]=loads(decompress(f[k])) 1 sec for retrieving f[k] 28 sec for decompress !!! (Why?) 1 sec for loads Whats is the problem?. zlib does not work fine? Please aid. In Windows XP this does not occurs!!! From cliechti at gmx.net Tue Mar 12 17:02:14 2002 From: cliechti at gmx.net (Chris Liechti) Date: 12 Mar 2002 23:02:14 +0100 Subject: serial port communication References: <3c8e6884.10907140@news.planetis.com> Message-ID: grante at visi.com (Grant Edwards) wrote in news:ncuj8.20190$N7.4739028 @ruti.visi.com: > There are a couple serial port libraries around that can make > life easier. Mine is strictly for Posix (Unix) systems: > > ftp://ftp.visi.com/users/grante/python/PosixSerial.py > > There are some others that are cross-platform, and Googling for > "serial" in comp.lang.python should find them. one of them is http://pyserial.sf.net which is multiplatform and the posix part is based on Grant's code. chris -- Chris From nas at python.ca Thu Mar 7 13:44:08 2002 From: nas at python.ca (Neil Schemenauer) Date: Thu, 7 Mar 2002 10:44:08 -0800 Subject: Python daemon instead of CGI programs In-Reply-To: ; from akuchlin@ute.mems-exchange.org on Thu, Mar 07, 2002 at 05:21:20PM +0000 References: <88bc63c6.0203061444.30ad9c44@posting.google.com> <7x7kope1n9.fsf@ruckus.brouhaha.com> Message-ID: <20020307104408.C3043@glacier.arctrix.com> A.M. Kuchling wrote: > Unfortunately we haven't wrapped up mod_scgi for release yet. It's getting close. I'd like to polish the SCGI specification a little more and write a lightweight CGI to SCGI adaptor (for servers other than Apache). It would be cool to have a threading SCGI server Python module in addition to the pre-forking one we already. I'm not the guy to write one though so that won't hold up the release. Neil From martin at v.loewis.de Tue Mar 19 04:04:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Mar 2002 10:04:23 +0100 Subject: Chewing international (unicode) filenames on windows? References: <3C96F705.50908@skippinet.com.au> Message-ID: Mark Hammond writes: > > p.s.2 what is the status on win9x? Give it up or ;-) > > I *think* it still works when accessing a Unicode aware file system > (ie, network) Doesn't even a local FAT32 file system expose file names in CP_ACP? So "mbcs" should work everywhere. With PEP 277, you can get Unicode file names if you pass a Unicode directory to listdir. Regards, Martin From chris.gonnerman at newcenturycomputers.net Thu Mar 28 23:08:31 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 28 Mar 2002 22:08:31 -0600 Subject: IDiscMaster interface References: <3CA366AB.934E9719@ccvcorp.com> Message-ID: <008d01c1d6d7$6c472880$0101010a@local> ----- Original Message ----- From: "Jeff Shannon" > > Chris Gonnerman wrote: > > > I have been investigating the IDiscMaster interface implemented > > in Windows XP... > > Note that there are (effectively) two types of COM interfaces -- > "custom" and "automation" (I'm not sure I've got the terms exactly > right, but...) Pythoncom currently only handles automation interfaces > (which were inteded to be used from scripting languages), not custom > interfaces (which were effectively intended to be used from C++). As > I understand it, in order to handle a custom interface (which I am > guessing the IDiscMaster interface is), you'd need to delve deep into > the internals of pythoncom. Of course, I'd *love* to be proved wrong > about this... ;) > Ug. I was afraid that it would be something like that. Add this to the list of things which are evil in Windows. Any chance anyone else might be planning to "wrap" this interface? From nospam at [127.0.0.1] Fri Mar 15 15:11:06 2002 From: nospam at [127.0.0.1] (Chris) Date: Fri, 15 Mar 2002 20:11:06 +0000 Subject: This may seem a slightly strange problem ... Message-ID: I want to learn programming - just for fun - and to learn more about computing - and the problem is I don't know what to write! I mean I can't seem to think of an interesting project. Has anyone else experienced this? It feels really silly! I did think of one thing that I'd be interested in but it's probably above my level (which is the lowest level!) and probably isn't possible in Python. That was to write a program to display all the possible 24-bit colours in a systematic way. But, aside from that, any advice on thinking up programs to write? -- Chris From fabi.kreutz at gmx.de Mon Mar 4 10:23:20 2002 From: fabi.kreutz at gmx.de (fabi.kreutz at gmx.de) Date: 4 Mar 2002 15:23:20 GMT Subject: SAX-Parser entity References: Message-ID: Martin v. Loewis and some other people wrote: > It is indeed very easy: There is an error in your document. It has no > encoding declaration in the xml header. The parser rightfully rejects > it. Yeah, now that you say it ... I just finished my work-around, but this way is of course the better (and only correct) way. I probably was too convinced that it must be minidom's fault to think about that. Thank's again. Fabian From tdelaney at avaya.com Mon Mar 18 01:20:29 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 18 Mar 2002 17:20:29 +1100 Subject: Creating a module that uses itself Message-ID: > From: Asheesh Laroia [mailto:pan-news at asheeshenterprises.com] > > I'm writing a PageMaker-to-specialized-HTML module (henceforth > "pm2html"). In the module, I define the classes Article, > Headline, and > Photo, among others. > > In the Article class, I want to have a Headline object. Is this > possible? Right now, ActivePython's PythonWin spits a syntax > error at me > because the Headline class is not defined. But I can't > > import pm2html > > (which is where the Headline object lives) because *that's > the file I'm > working in*! > > So, how do I create a module that uses objects it creates? Post the code. Try not to include anything that isn't necessary (but don't strip out what is - make sure that what you post fails in the same way). Tim Delaney From nhodgson at bigpond.net.au Tue Mar 12 17:33:53 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 12 Mar 2002 22:33:53 GMT Subject: RFC PEP candidate: q''quoted ? References: Message-ID: Jason Orendorff: > Neil Hodgson wrote: > > In my experience writing a lexer for Perl (for use in syntax styling > > editors), 'here documents' and arbitrary quote sequences add much > > complexity to a lexer. [...] > > (skeptical look) Are you really claiming to have written a lexer > for Perl? Is that even possible? No. I started writing a lexer for Perl, but it is incomplete and is likely to remain incomplete. The subset of Perl handled is sufficient for syntax styling but is not sufficient for a language interpreter. The code is available as part of Scintilla and is used in various IDEs. At one stage it was used in Komodo, but ActiveState may have changed to using the Perl interpreter's lexer. I wrote the first versions and then other contributors extended the lexer into some of the more difficult pieces of Perl syntax. The implementation of lexing and parsing in the Perl interpreter is a bit messy, using parse level information to guide lexical analysis. Neil From jeffbi at jetsoft.com Tue Mar 19 18:23:48 2002 From: jeffbi at jetsoft.com (Jeff Bienstadt) Date: Tue, 19 Mar 2002 15:23:48 -0800 Subject: IntSpan? Message-ID: <3c97c886@news.nwlink.com> Does there exist for Python something akin to the Set::IntSpan module for Perl? I'm looking for something that inteligently handles and manipulates spans of integers, such as: 2-356,456,458-500 Thus far, web searches have been unsuccessful... Thanks, ---jkb From martin at v.loewis.de Wed Mar 27 15:00:22 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Mar 2002 21:00:22 +0100 Subject: interactive python shell References: Message-ID: ian reinhart geiser writes: > I have an python application and I would like to provide a > "console" in the application where users can have an interactive > session with python that has all of the applications enviroment. > This is for debugging the system in real time. > Is there an easy way to do this? What's wrong with using standard input and output for that? If you want to emulate a Python interactive session, you can use code.InteractiveConsole. HTH, Martin From tim-dated-1016743233.4ed988 at catseye.net Thu Mar 14 15:40:32 2002 From: tim-dated-1016743233.4ed988 at catseye.net (Tim Legant) Date: 14 Mar 2002 14:40:32 -0600 Subject: Why I think range is a wart. In-Reply-To: References: <7UYj8.31929$l93.6269941@newsb.telia.net> Message-ID: <86lmcu7uin.fsf@skitty.catseye.net> Peter Dobcsanyi writes: > Fredrik Lundh wrote: > > > > note that > > > > index = 0 > > for item in mylist: > > > > index += 1 > > > > is faster than > > > > for index in range(len(mylist)): > > item = mylist[index] > > > > > > Here is some timing with variations posted so far. > > i in range(len(ls)): 2.01 > x in ls; i+=1 : 2.59 > lambda x:zip(range(len(x)), x): 3.86 > Iter class: 10.7 [...] > def bar(ls): > i = 0 > for x in ls: > if ls[i] == '998': > return i > i += 1 No. Your bar() function is broken and the test results invalid. Try this instead: def bar(ls): i = 0 for x in ls: if x == '998': return i i += 1 You already have ls[i] as x, which was the whole point of /F's post. Tim From gh_pythonlist at gmx.de Wed Mar 13 13:56:10 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 13 Mar 2002 19:56:10 +0100 Subject: Newbie: Undefined reference when initializing Python In-Reply-To: References: Message-ID: <20020313185610.GC1227@lilith.hqd-internal> Le 13/03/02 ? 18:18, Michael Hudson ?crivit: > "henrikb666" writes: > > [...] > > I already include at the top of the TServer.cc file, so > > that's not it. Could it have something to do with my Makefile? > > You need to link to Python; there should be a "-lpython" in there > somewhere (and probably a "-L/some/path/or/other/" too). Also take a look at this URL, before you tear your hairs out trying to satisfy all the library dependencies: http://www.faqts.com/knowledge_base/view.phtml/aid/11864 Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 14.2 ?C Wind: 1.2 m/s From vlindberg at verio.net Tue Mar 26 17:12:09 2002 From: vlindberg at verio.net (VanL) Date: Tue, 26 Mar 2002 15:12:09 -0700 Subject: Symbolic imports and manipulation of the namespace? Message-ID: <3CA0F239.7020205@verio.net> Hello, I was recently solving a problem which required that the config file (just a python file) lie outside of the pythonpath. Is it possible to do symbolic importation of a module? For example, I had: # cfgpath is passed in on the command line cfgpath = os.path.basename(cfgpath) sys.path.insert (0, cfgpath) import sc_cfg #Hardcoded config module name! How do you do this: # cfgpath is passed in on the command line cfgpath, cfgfile = os.path.split(cfgpath) sys.path.insert (0, cfgpath) import cfgfile #Hardcoded config module name! So that any file name (ending with .py, of course, but that's another matter) could be the configfile? I tried the above, but I got an ImportError (no module named cfgfile) Thanks, Van From bokr at oz.net Tue Mar 19 22:32:20 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Mar 2002 03:32:20 GMT Subject: Q: Sound production with python? References: Message-ID: On 20 Mar 2002 01:42:45 GMT, "A.Newby" wrote: >Being a beginner fiddle player, as well as a beginner python programmer, I >want to write a little prog that trains the sense of pitch. > >How envisage it working is thus... > >It plays a simple 4 note melody, then repeats the melody with one of the >notes (selected randomly) slightly off pitch ... say by 20% or 10% or 5%. >The user then has to detect which note was off. > >What modules and commands should I use to generate this sounds? What's the >best way to go about it? > I wonder if there is a midi module you could use to play midi violin notes and use the pitch bend thing to vary them. If so, be sure you have the 'everything-off' (or whatever it's called) code correctly defined and easy to output ;-) Regards, Bengt Richter From truce at inwind.it Tue Mar 26 03:28:34 2002 From: truce at inwind.it (truce) Date: Tue, 26 Mar 2002 09:28:34 +0100 Subject: [ZPublisher] how to install ? Message-ID: <20020326.092833.352118606.2249@inwind.it> Hi! I'm using mod_python and from the docs I've read about ZPublisher. I would like to use the great ability to point to a function inside a module from URL ... http://server/site/module/function how can I do this? is this the only way to do this ? I don't want to use all Zope, and if possible some solution that use my version of python 2.2 ... thax a lot davide. From phr-n2002a at nightsong.com Sun Mar 3 23:55:20 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 03 Mar 2002 20:55:20 -0800 Subject: Rotor in Jython? References: Message-ID: <7xit8daq4n.fsf@ruckus.brouhaha.com> writes: > But the sorry history of rotors has nothing to do with rotor strength and > everything to do with short/obvious keys, the obvious starting text of the > messages (e.g. "No news to report"), and the limitations of mechanical > implementations. You can *always* make a rotor stronger by increasing the > length of the key - and at no additional computational cost. That's erroneous--if you count the rotor and plugboard permutations, the WW2 Enigma machines had a very large key space (maybe larger than 56-bit DES) but they were cryptanalyzed with fairly crude electromechanical devices (the "Bombe" was basically 6 Enigmas wired together). From ryanmorillo at hotmail.com Mon Mar 25 21:40:01 2002 From: ryanmorillo at hotmail.com (Ryan) Date: 25 Mar 2002 18:40:01 -0800 Subject: personel CDDB Message-ID: <4a7fde99.0203251840.2aafdf58@posting.google.com> I'm thinking about writting a personel CD database that links into RDB so you can put in a cd and have python link to crdb and make a personel database to keep track of your cd's (and maybe rip mp3s from it and store them in the database to) I'm wondering if many people would have an interest in this so I will know whether to just write it so it works, or write it the right way, (ie. pure python and a gui using anydb). If it's just for me it won't be nearly as robust and will use a lot of win32 extensions (for speed). If there is enough interest I may even post to source-forge. Thx Ryan From gimbo at ftech.net Tue Mar 19 04:32:41 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Tue, 19 Mar 2002 09:32:41 +0000 Subject: Correct to use instance = module.__dict__[class_name]() ? In-Reply-To: References: Message-ID: <20020319093241.GE19877@andy.tynant.ftech.net> On Mon, Mar 18, 2002 at 07:48:42PM +0100, Just van Rossum wrote: > This would be better: > > def bar(module_name, class_name): > module = __import__(module_name, globals(), locals(), []) > handler = getattr(module, class_name)() > return handler Ah, yes. That feels nicer. :-) Excellent - thanks! -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From narnett at mccmedia.com Sun Mar 24 19:29:46 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Sun, 24 Mar 2002 16:29:46 -0800 Subject: hang in urllib.read()? Message-ID: The (presumably) infinite loop that I thought was in sgmllib, about which I posted earlier, actually seems to be when I call read() on an urllib.urlopen object. It's terribly non-reproducible, though -- I'm retrieving lots of pages and sometimes it'll go for dozens and dozens, no problem. Other time it hangs after just a few. And it won't do it on the same page twice, as far as I can see. I've been unable to find anything like this searching... sound familiar to anyone, or any suggestions for nailing it down, short of gruesome stepping through with a debugger, hoping I can catch one...? This is on Win2000 with Python 2.2. Haven't tried on other platforms yet. Nick -- narnett at mccmedia.com (408) 904-7198 From geoff at gerrietts.net Fri Mar 8 02:08:18 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 7 Mar 2002 23:08:18 -0800 Subject: Learning from imperfect lectures In-Reply-To: <3C8821FE.B81C4A5D@engcorp.com> References: <3C8821FE.B81C4A5D@engcorp.com> Message-ID: <20020308070818.GA1112@isis.gerrietts.net> Quoting Peter Hansen (peter at engcorp.com): > Roman Suzi wrote: > > > > I do not remember who told me this, but it seems that students > > better learn from poorly constructed lectures than perfect ones. > > Because, they need to be _active_ in constructing their own system > > rather than _passively_ "eat" readymaid knowledge frames. > > Wow. Deep... I like this (to me) completely new idea. This idea was new to me, too, in form but not in concept. Pedagogical coursework -- like the stuff they teach to new grad students who are going to be teaching assistants, or the stuff they teach to people in education programs -- frequently talks about how important it is to engage the student, and how involving them and making them think about the material is the teacher's primary task, with presenting the material actually being secondary. The actual practice of an "imperfect presentation", though, is something I'd not considered before -- the idea of leaving blanks for the student to fill in is both appealing and a little alarming. > Anyone know where it came from? References to a study or something? If you look for it, it will be there, but I can't provide you with specific materials. Try checking into research in educational techniques; that's where you're most likely to find something like that. Failing that, developmental psych is likely where it came from, but it's more likely to be a needle in a haystack, there. > Someone I know worked for months (on and off) on a presentation that > could have been done (imperfectly) in a week. When it was presented, > the reception seemed to me rather luke-warm, in spite of apparently > strong interest in the audience ahead of it (and after). The > presentation struck me at the time as being _very_ "polished", but > perhaps with too little unsaid for someone to question, or think > about. I suspect this is the reason why it didn't seem to work. Interesting anecdotal evidence. I can think of several cases where I've felt somewhat the same way about presentations that I've given. It's often taught me and my audience both more if my presentation is struggling to hold together at the seams. -- Geoff Gerrietts "I am always doing that which I can not do, in order that I may learn how to do it." http://www.gerrietts.net --Pablo Picasso From krissepu at vip.fi Mon Mar 25 02:40:06 2002 From: krissepu at vip.fi (pekka niiranen) Date: Mon, 25 Mar 2002 07:40:06 GMT Subject: unicode and locale of machine ? Message-ID: <3C9ED480.8000403@vip.fi> My plan is to store text data in single format and display it according to machine's locale. Is it possible to read the current keyboard layout or language settings in windows/unix and use that automatically to convert text from unicode to printable in another machine ? Or have I completely misunderstood unicode ? -pekka- From martin at v.loewis.de Fri Mar 1 02:29:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 08:29:43 +0100 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: "Stephen J. Turnbull" writes: > IMO, the Python source code parser should never see any text data[1] > that is not UTF-8 encoded. If you want to submit Python programs to > the parser that are not UTF-8 encoded, then it is your responsibility > as the programmer to make sure they get translated into UTF-8 (eg, by > the preprocessing hook) before the interpreter proper ever sees them. That would cause surprises to users. They have a source program that says # -*- coding: koi8-r -*- print "some cyrillic text" This currently works fine on their system; the text comes out on the terminal just right. Now, Python would convert this text silently to UTF-8 behind their backs, and the terminal would show just garbage. In XEmacs, this is no problem: the "terminal" mostly is the *Messages* buffer, and that would know that all text is UTF-8. For Unicode strings, we indeed plan to make the transformation you suggest (not to UTF-8, though): If you have a script that reads # -*- coding: koi8-r -*- print u"some cyrillic text" then the string literal will be converted to the internal Unicode type. How to print it is then another issue; you'll have to figure out the encoding of the terminal - that is feasible in most cases. It is not feasible to do the same for arbitrary byte strings: You (the Python interpreter) could not know whether the string is supposedly UTF-8 encoded, and that conversion to the terminal's encoding is needed, or whether the string is an arbitrary byte sequence, which is intended to appear on the terminal as-is. "All byte strings are UTF-8" is not going to work, since Python is used to operate on binary data as well, and the bytes that make up a GIF file just aren't UTF-8. > [1] Ie, Python language or character text. It might be convenient to > have an octet-string primitive data type, in which you could put > EUC-encoded Japanese or Java byte codes. The traditional "string" type is, in fact, a byte string type. Many people use it still for character strings, since the Unicode type was the later addition. Changing the string type to be a Unicode type was not feasible since that would have broken many applications, in particular C modules which expect that the internal representation of the string type is char[]. > [2] But I recommend against this. Don't offer support for such; it's > a time and effort sink, for little return. There will be a simple form of auto-recognition: an UTF-8 signature (i.e. a UTF-8 encoded BOM) at the beginning of a source file will be treated as a clear indication that the file is UTF-8. Regards, Martin From tim.one at comcast.net Sat Mar 30 17:44:12 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 17:44:12 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: <200203301338.g2UDc0m01524@pcp742651pcs.reston01.va.comcast.net> Message-ID: [Guido, on why operator.truth() should change to return True/False] > Tim must be missing something. The obvious way to turn a bool b into > an int is int(b). It's also an incorrect way for me, because I meant "true/false expression" in the way Python has always meant it, e.g. operator.truth([]) == 0, but int([]) raises an exception. The alternative int(bool(b)) is not obvious (else you would have thought of it first ), and becomes needed only if operator.truth() is changed. > Having to import the obscure 'operator' module for this purpose is > backwards. Under the PEP it's extremely easy to get a bool result (bool(b)), so I favor presuming that anyone bothering to use operator.truth() will do so because bool() doesn't do what they want; and if they're using truth() in 2.2, are doing so because they specifically want a 0/1 result. > (IMO there's almost *never* a reason to import that module anyway.) That's not a reason to change what it does -- people who do import it generally know exactly what they're doing, or have no idea . From stephen at xemacs.org Wed Mar 6 21:19:10 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 07 Mar 2002 11:19:10 +0900 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3c864a78$1_3@news.newsgroups.com> Message-ID: <873czdnmqp.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Brad" == Brad Clements writes: Brad> You can find a respectable (IMHO) chapter on extending and Brad> embedding in "Professional Linux Programming", Wrox Press. Brad> Strange place to bury it, but if you're in a bookstore some Brad> time check it out. I'd like to know your opinion. I thought it was clear, although I haven't tried to apply it yet. (I'm a co-author) -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From bokr at oz.net Sun Mar 10 15:29:58 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 20:29:58 GMT Subject: should i learn it first ? References: Message-ID: On Sun, 10 Mar 2002 17:13:17 GMT, "G. Sumner Hayes" wrote: >In article , Bengt Richter wrote: >>> >> I'd say if you don't know C, C++, or Python, then start with Python. >> Then C++, then C. In that order, you won't have to unlearn patterns >> of design you absorb solving problems with C. > >Ugh, I can see learning Python first but definitely learn C before >C++. In that order, you won't have to unlearn patterns of design >you absorb solving problems with C++. > >Seriously, the point of using a low-level language like C or C++ is to get >next to the hardware, and it should be learned from that level first >IMO. Otherwise, stay with a more productive language like Python. > I think "low level" is a mis-characterization of C++, even though it obviously has as much low level capability as C. If you are just going to use the low level stuff (unless you are talking about assembler within C++), you might as well use C. ISTM C++ was designed to let you *build* "levels" with layers of abstraction through objects and generics. IOW, one group can work at low level to produce elements that others can use at high level. E.g., instatiating an mp3-playing object and calling the play method is pretty trivial and high level, yet the same C++ language can be used to write the guts of almost everything involved. If you really want to get intimate with the[1] hardware, even C is mostly isolating you from true carnal knowledge. Get an assembler[2], and choose every instruction and every data location and access thereto. Disassemble and understand the MBR. Get Linux or BSD and mess around (on a system you can afford to wipe out ;-) [1] Of course 'the' will vary with your platform ;-) [2] OTOH, you'd be surprised what level chunks you can build with macros in a good macro assembler. >> If you start with C, you will get used to a procedural way of looking >> at problems, and when you get to C++ you will be tempted to see it >> as just C with extra features. You'll have to dislodge yourself from C >> habits of thinking in order to "think objects" in C++. Coming from > >Conversely, if you learn in the other order you'll find yourself thinking >of it as a limited version of C++ instead of a different language with >its own idiom. The point of C is that it's procedural, small, and close >to the metal. Viewing without the corrupting lens of C++ is extremely >valuable, IMO. > I don't know what you mean by "corrupting lens of C++," other than a rhetorical counter point ;-) >FWIW, I know more good programmers who learned C and then C++ than >vice-versa. Some of us learned to program before either existed, and couldn't have the choice of which to learn first without ignoring C for many years ;-) But even if you just want to learn C, you can largely use C++ as if it were C. Regards, Bengt Richter From peter at engcorp.com Sun Mar 10 15:12:52 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 15:12:52 -0500 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: <3C8BBE44.BDA092C9@engcorp.com> phil hunt wrote: > > On Sat, 09 Mar 2002 22:57:42 -0500, Peter Hansen wrote: > > > >I agree with much of what you say, especially the "consider skipping > >C++ and just learn C part", but _what_ pragmatic point of view is it > >that has one learning Perl, Java, or C++ when one uses Python already? > >Not dissing those languages, but when would you really need them? > > I can think of several tasks for which C++ is better than Python, > e.g. writing operating systems, network stacks, windowing systems, > run-time interpreters, crypto algorithms, etc. Point taken, although I would try to use C far more often in those cases than some others might. I admit I had "application programming" stuck in mind as I wrote the question, not system programming... -Peter From dale at riverhall.NOTHANKS.co.uk Thu Mar 14 06:38:52 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 14 Mar 2002 11:38:52 +0000 Subject: redirecting stdin with Python scripts under win2k (solution) References: Message-ID: <9t119uo75apvom6ghje49fk21b5o325n99@4ax.com> I'm sure you're very pleased with that but I don't see the point. If I want to run a Python program, I just type the name of it at a command prompt. A few prerequisites need to be in place but some of these happen during install: 1. The directory containing the script needs to be in your PATH environment var or be the current directory. 2. PATHEXT environment var needs to contain ".PY;.PYC;.PYW" 3. The Python exes need to be associated with the Python file types. Once you get all the above right, you just type: C:\> wibble args and it runs: "C:\Python21\python.exe" "wibble.py" args This only works with Win NT/2K/XP. As for 95/98/ME, well it's easier not to bother, really. Disguising your Python programs as batch files is going to knacker any attempt your editor may make to help with syntax highlighting and suchlike. Also, FYI, I think all the command extensions you mention were introduced with NT 4. -- Dale Strickland-Clark Riverhall Systems Ltd From gcordova at hebmex.com Mon Mar 25 17:25:44 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Mon, 25 Mar 2002 16:25:44 -0600 Subject: How to get a key from dictionary? Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689CF@SRM201002> > > Hi, > Is there a possibility to get, from a dictionary, a key > according to a value ? > For example I have a dictionary > > dict={'aa':1,'bb':2} > > and > dict['aa'] > is 1 > > But how can I for value 1 find out key? (That is here 'aa') > > Thank you for help > Ladislav > You're welcome, here's an example: >>> Dict = { "gustavo":32, "pedro":31, "campa":25 } >>> K = Dict.keys() >>> V = Dict.values() >>> K ['campa', 'pedro', 'gustavo'] >>> V [25, 31, 32] >>> V.index(31) 1 >>> K[V.index(31)] 'pedro' >>> Dict.keys()[Dict.values().index(32)] 'gustavo' >>> From jgardn at alumni.washington.edu Sat Mar 16 03:02:52 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Sat, 16 Mar 2002 17:02:52 +0900 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: Fernando P?rez wrote: > Jonathan Gardner wrote: >> Anyone have any suggestions on where I should go? Anyone can help me out >> here? >> > > This was my rough solution. It may be a reasonable starting point for you. > It looks pretty good. However, it requires the users to install another package just to install the main package. I'll take a look at it, but isn't there a way to write some kind of installation script in something native to windows? Jonathan From lars.gustaebel at gmx.de Thu Mar 14 19:24:30 2002 From: lars.gustaebel at gmx.de (Lars Gustäbel) Date: Fri, 15 Mar 2002 01:24:30 +0100 Subject: tarfile 0.2.5 Message-ID: tarfile 0.2.5 tarfile is a pure python module that allows read and write access to tar and tar.gz archives. Its interface is compatible to the zipfile standard module. This will make it easy to integrate it in existing projects that already use zipfile, for example. some other features: - platform independent - handles all common file types: files, directories, symlinks and fifos - manages GNUtar extensions like longnames and longlinks - stores all meta-information about files, like permission, modification time, username, user id etc. It is available at: http://www.gustaebel.de/lars/tarfile/ I hope, it will be useful. Suggestions, comments and patches are welcome. Lars Gustaebel (lars at gustaebel.de) From quinn at pfennig.ugcs.caltech.edu Sat Mar 9 00:38:20 2002 From: quinn at pfennig.ugcs.caltech.edu (Quinn Dunkan) Date: 9 Mar 2002 05:38:20 GMT Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: On Mon, 4 Mar 2002 12:26:48 -0800, James_Althoff at i2.com wrote: >Carel, > >Thanks for the explanation, below. Very interesting. > >Yes, I agree with your basic analysis that producing an iterator for an >integer makes a lot more sense if one accepts integers as first-class >objects. The fact that Python treats integers as well as everything else >as first-class objects is one of the big reasons why I like Python so much. I have no trouble accepting integers as objects just like any other type, and I still don't like iter(5). Objects don't need to be all-singing all-dancing. Just because you can provide a magic method to overload a type to give a nifty "convenient" meaning to some built in syntax doesn't mean it's a good idea. >From my view, int.__iter__ is inappropriate overloading, just as int.__contains__ would be, or file.__add__ would be. I've never had range(n) be a memory or a performance problem. The only time it's notationally inconvenient is when I want a haskell-like inclusive range that can go up or down, which is why I wrote hrange(). And sometimes (rarely), the most convenient kind of changing index is: i = start while i < upper_bound: ... i += increment I have no problem with that either. From lac at strakt.com Fri Mar 22 13:46:03 2002 From: lac at strakt.com (Laura Creighton) Date: Fri, 22 Mar 2002 19:46:03 +0100 Subject: New SIG on logic/CLP programming in Python In-Reply-To: Message from nico@aries.logilab.fr (Nicolas Chauvat) of "Fri, 22 Mar 2002 17:44:20 GMT." References: Message-ID: <200203221846.g2MIk3rq005323@ratthing-b246.strakt.com> I am most interested in this. (But then you knew you would say that, didn't you.) I want to see if we can get Michel Sanner involved as well. Laura Creighton From martin at v.loewis.de Fri Mar 15 19:09:58 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Mar 2002 01:09:58 +0100 Subject: locale module broken? References: <3C928042.BA50A5B3@snakefarm.org> Message-ID: Carsten Gaebler writes: > while playing around with Greg Lindstrom's "Pretty integers" (see his > posting), my Python 2.2 got stuck here: > > >>> import locale > >>> locale.setlocale(locale.LC_ALL, "fr_FR") > 'fr_FR' > >>> locale.format("%.1f", 12345.5, 1) > > It runs forever. This is on RedHat 6.2 and Debian Potato. Any hints? I can't reproduce this, with Python 2.3a0 on a SuSE 7.2 system: it prints '12345,5'. If you care somewhat about this problem, submit a bug report to SF. If you care a lot, please investigate. Regards, Martin From siegfried.gonzi at kfunigraz.ac.at Sun Mar 24 17:56:39 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Sun, 24 Mar 2002 22:56:39 -0000 Subject: reading in ints from binary files References: Message-ID: "Bill" schrieb im Newsbeitrag news:a7ns1d$mi1$1 at nntp1.jpl.nasa.gov... > Quick Newb question: > > How do I read in integers from binary files? readlines() reads returns the > data in as a string. I can manipulate the string to get the desired result. > However, is there an easier way of doing this? I currently do something > like: > > f=open('file', 'rb') > s = f.readline() > l = list(s[0:-1]) > l.reverse() > a = array.array('h', ''.join(l)) I had a similar problem: reading a binary array of dimension 360x180. The satellite-datas have been stored in floating-point format. I am relatively new to Python, but the following function just works (and it is quite fast, at least I am contented with): def readBinArray(file,rows,cols,trans='nein',what='f'): f = open(file,'rb') # ergArray = array(what) n = cols*rows ergArray.fromfile(f,n) f.close() ergArray.byteswap() ergArray = reshape(ergArray,(rows,cols)) if trans == 'ja': return transpose(ergArray) return ergArray It is based on the Numeric-library (but this is not a condition; I just only passed the array on to a DISLIN-plotting library, hence also the transposing). Important here is "fromfile(f,n)" and "array(what)". You should look after what you have to use in array() in order to create an array dedicated to integers (e.g. 'f' means floating-point in Python notation). If your file is a Unix-file and you read it on Windows, maybe you should also apply byteswap(). So, the above shows Python's strength . It seems the Python developers had the better common-sense when it comes to "Python and the real world" (as opposed to Clean and in the binary-specific case even Common Lisp*). S. Gonzi *Surely, Common Lisp programmers believe that they are God, and God dictates what you may and what not. All the Gods decided we just only use ASCI-files. There is only one caveat: my NASA-binary-satellite-data-files do not care on ASCI-files. Please, no suggestions like: "But you can do it in Lisp with a little bit investment on work". Okay, agreed, but then the Lisp fanatics should stop accusing Python or Perl,...infinitely (until Cantor says: Lisp fanatic stop, you are reaching God's realm). From mats at laplaza.org Fri Mar 1 19:22:58 2002 From: mats at laplaza.org (Mats Wichmann) Date: Sat, 02 Mar 2002 00:22:58 GMT Subject: (OT?) Web-based document review system? Message-ID: <3c801a5b.68374897@news.laplaza.org> Note: this is not a Python question per se. I'm looking for a piece of software to aid in reviewing a document through the web - click on a paragraph tag, have the comment added (highlighted in some way). The wiki style doesn't seem to quite do it, as the core document is not protected. I haven't found much in web searches, and nothing where the software seems to be free. I'd of course love it if this were done through Python since I'm on a bit of an advocacy kick...but in the end it doesn't matter much. Anybody know if anything like this is happening in any of the web services projects? Mats Wichmann From martin at v.loewis.de Sat Mar 23 18:14:00 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Mar 2002 00:14:00 +0100 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: philh at comuno.freeserve.co.uk (phil hunt) writes: > >On Fri, Mar 22, 2002 at 02:59:15PM -0500, Barry A. Warsaw wrote: > >> > >> To maintain www.python.org, we use a web page templating system called > >> `ht2html', which transforms .ht template files into .html files. > > Is the source for this available? It's in the CVS. Regards, Martin From boud at valdyas.org Thu Mar 7 10:25:43 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Thu, 07 Mar 2002 14:25:43 -0100 Subject: Black Adder and PyQt References: <3c848d1a$0$90054$e4fe514c@dreader1.news.xs4all.nl> Message-ID: <3c876b3b$0$24833$e4fe514c@dreader3.news.xs4all.nl> Ron Stephens wrote: > I have just ordered both Black Adder, Personal edition plus one year > of updates, as well as your new book, GUI Programming with Qt: Python > edition. > Balm to the heart of an authors whose last computer has just gone up in smoke... -- Boudewijn Rempt | http://www.valdyas.org From gerhard at bigfoot.de Sun Mar 10 12:29:36 2002 From: gerhard at bigfoot.de (Gerhard =?ISO-8859-1?Q?H=E4ring?=) Date: Sun, 10 Mar 2002 09:29:36 -0800 Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> Message-ID: <3C8B9800.8040302@bigfoot.de> Grant Edwards wrote: > If I did, couldn't I make all of > "my" apps look in the same place for "my" DLLs? I really hate > the idea of my app putting things in "system" directories. Sure you can. Just append to the PATH a directory where all your DLLs go. This is of course best done with the installer. Here's a description of how Windows searches for DLLs: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore/html/_core_The_Search_Path_Used_by_Windows_to_Locate_a_DLL.asp Gerhard From huaiyu at gauss.almadan.ibm.com Wed Mar 6 18:27:42 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 6 Mar 2002 23:27:42 +0000 (UTC) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: On Tue, 05 Mar 2002 19:50:10 -0500, Tim Peters wrote: > >> Since both 1e-200**2 and 1e200**2 produce the same errno all the time, >> but Python still raises OverflowError for 1e200**2 when linked with >> -lieee, there must be a separate mechanism at work. > > ... What differs is when >platform pow(x, y) does not set errno. In that case, Python synthesizes >errno=ERANGE if the pow() result equals +- platform HUGE_VAL. Thanks! Thanks! Thanks! That's exactly what I was looking for. The OverflowError was produced by the line commented out below: errno = 0; PyFPE_START_PROTECT("pow", return NULL) ix = pow(iv, iw); PyFPE_END_PROTECT(ix) /*Py_SET_ERANGE_IF_OVERFLOW(ix); */ if (errno != 0) { /* XXX could it be another type of error? */ PyErr_SetFromErrno(PyExc_OverflowError); return NULL; } With this little change, I got the following answer consistantly: >>> 1e200**2 inf >>> (1e200*1j)**2 (-inf+nanj) instead of the inexplicable: >>> 1e200**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') >>> (1e200*1j)**2 (-inf+nanj) > >> What is that and how can I override it? > >Sorry, you can't override it. I just did. So I guess I must have been communicating terribly. But anyway, all is fine and the sun is shining now. :-) Why do I want this? I believe it is impossible for computation to carry its own numerical analysis without prohibitive cost (think interval computation in the 1970s). If the user knows his numerical analysis, you don't want to short circuit him, and if he does not, it's hopeless anyway. Overflow error should only be raised when the return value is out of bound AND not represented by well defined out of bound values such as inf and nan. I'm not going to write any lengthy rationale for this, as my itch has been scratched. The following example illustrate my point (Consider: How do you know that y=x**2 is not used in exp(-y)? And what should happen if this is inside a matrix where you don't want try/except for each element? Answer: you can't. Numerical analysis in general can only be performed globally.) >>> from math import exp >>> def f(x): return exp(-x**2) ... >>> f(1) 0.36787944117144233 >>> f(5) 1.3887943864964021e-11 >>> f(1e100) 0.0 >>> f(1e200) 0.0 versus >>> from math import exp >>> def f(x): return exp(-x**2) ... >>> f(1) 0.36787944117144233 >>> f(5) 1.3887943864964021e-11 >>> f(1e100) 0.0 >>> f(1e200) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in f OverflowError: (34, 'Numerical result out of range') Hauiyu From martin at v.loewis.de Sun Mar 10 15:52:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 10 Mar 2002 21:52:45 +0100 Subject: How to disable assert statements inside a module? References: Message-ID: Pearu Peterson writes: > Is there a way to disable all assert statements inside a module, > and without calling python with -O switch? You can set __debug__ to 0 on the module level; this will disable assert statements inside this module. Regards, Martin From logiplexsoftware at earthlink.net Thu Mar 28 18:42:10 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 28 Mar 2002 15:42:10 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) In-Reply-To: <3CA3AA98.2F94398B@activestate.com> References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA3AA98.2F94398B@activestate.com> Message-ID: <20020328154210.037caf5e.logiplexsoftware@earthlink.net> On Thu, 28 Mar 2002 15:43:20 -0800 David Ascher wrote: > May I suggest that you instead do: > > >>> class MyClass: > ... def do_this(self): > ... "this function would do this" > ... def do_that(self): > ... "while this function would do that" > ... > >>> > > and use the docstrings as a placeholder for the actions of the function > -- typically something that's foremost in your mind when you're > pseudocoding, and it counts as a statement as far as the parser's > concerned (hence is syntactically valid), and at the same time, you've > already got docstrings ready for you when you start to implement. Phil is trying to avoid having to backspace 4 times to delete a pass statement. Why the hell would he want to type in an entire docstring??? ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From shalehperry at attbi.com Wed Mar 6 16:17:34 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 06 Mar 2002 13:17:34 -0800 (PST) Subject: Dictionaries in Lists In-Reply-To: Message-ID: On 06-Mar-2002 Avi Homes wrote: > I was attempting to make a list of dictionaries, which to me feels like the > C equivlant of an array of structs, kind of. anyway, after making a > dictionary and putting some values into it, and trying to append it to a > list, python is not liking this. Am I approaching the idea the wrong way? i > would like to keep the data organized as dictionaries.. the code looked > something like > > Info{'IName':"Voodoo2",'IDescription':"blahblah} > Listing=[] > Listing.append(Info) > Seems to work here. What fails for you? >>> d = {'Foo':1, 'Bar':8} >>> d {'Foo': 1, 'Bar': 8} >>> l = [] >>> l.append(d) >>> l [{'Foo': 1, 'Bar': 8}] >>> l[0] {'Foo': 1, 'Bar': 8} >>> l[0]['Foo'] 1 >>> y = {'Foo':3, 'Bar':12} >>> l.append(y) >>> l [{'Foo': 1, 'Bar': 8}, {'Foo': 3, 'Bar': 12}] >>> l[0] {'Foo': 1, 'Bar': 8} >>> l[1] {'Foo': 3, 'Bar': 12} From philh at comuno.freeserve.co.uk Tue Mar 12 08:56:17 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Tue, 12 Mar 2002 13:56:17 +0000 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> <3C8C02B3.674898B0@engcorp.com> <3C8C0460.993A4F81@engcorp.com> <3C8D9956.5920AA52@engcorp.com> Message-ID: On Mon, 11 Mar 2002 22:25:46 -0800, David Eppstein wrote: >In article <3C8D9956.5920AA52 at engcorp.com>, > Peter Hansen wrote: > >> Resulting in a grand total Crackpot Index of about 3471, surely >> an all-time record. > >I guess you haven't seen some of the more persistent math and physics >crackpots. This guy came, didn't get a lot of support, and went >quickly, without destroying the newsgroup for months or years. Much >less of a waste of bits... I wonder what it is about maths and physics that attracts crackpots. Python people are (mostly) more sensible. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From fdrake at acm.org Sat Mar 30 11:07:36 2002 From: fdrake at acm.org (Fred L. Drake, Jr.) Date: Sat, 30 Mar 2002 11:07:36 -0500 Subject: [Python-Dev] RE: PEP 285: Adding a bool type In-Reply-To: <200203301342.g2UDgTE01572@pcp742651pcs.reston01.va.comcast.net> References: <200203301342.g2UDgTE01572@pcp742651pcs.reston01.va.comcast.net> Message-ID: <15525.58056.566073.884317@grendel.zope.com> Guido van Rossum writes: > You've been staring at standards too much, haven't you? The > difference between MUST and SHOULD isn't as clear-cut as most > standards people use them. Most standards define MUST and SHOULD very specifically, and then use them according to those definitions. There's an IETF RFC specifically for use in writing RFCs, allowing those terms to be defined by reference. A number of W3C specs seems to be using this definition-by-reference as well, with the same RFC providing the actual definitions. I think we'd do well to accept a specific definition of these terms and use them consistently, simply to make our documentation (including docstrings) easier to understand. -Fred -- Fred L. Drake, Jr. PythonLabs at Zope Corporation From mhammond at skippinet.com.au Tue Mar 12 17:17:16 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 12 Mar 2002 22:17:16 GMT Subject: Has Mark Hammond attained pariah status yet? References: Message-ID: <3C8E7E90.6000608@skippinet.com.au> Michael Chermside wrote: > Um... look folks. We can all point at the article and laugh, but some > people appear to be confused about what is and what isn't intended to be > taken with a . So let me state a few facts quite clearly, with no > sarcasm (or humor) intended. Let me state first of all that I took the original post in the manner which it was intended. From my POV, any publicity is good publicity. To my mind, having a fairly large headline "Charmed by the Python" in the 2 most respected newspapers in Australia (Sydney and Melbourne broadsheets) is a nice coup. I certainly saw the humour in both the newspaper article, and the newsgroup posts, so worry not. The article was not 100% accurate. One 30 minute phone call, and this article appears. The book I am working on now is *not* Python for .NET, but just .NET. Python doesn't get much of a mention :( And-what-is-wrong-with-being-a-pariah-anyway ly, Mark. From bokr at oz.net Wed Mar 27 22:31:45 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Mar 2002 03:31:45 GMT Subject: instrumenting Python code References: <15521.50103.968819.131319@12-248-41-177.client.attbi.com> Message-ID: On Wed, 27 Mar 2002 19:46:32 -0600, Skip Montanaro wrote: > > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import hotshot > >>> hotshot.Stats > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'Stats' > >My apologies. I was typing from memory. Should have been > > import hotshot > profiler = hotshot.Profile("/home/skip/tmp/csv2csv.prof") > profiler.run("main()") > profiler.close() > import hotshot.stats > stats = hotshot.stats.load("/home/skip/tmp/csv2csv.prof") > stats.print_stats() > Thanks. That seems to work. Sorry to be lazy about it ;-/ Regards, Bengt Richter From altis at semi-retired.com Fri Mar 22 15:38:53 2002 From: altis at semi-retired.com (Kevin Altis) Date: Fri, 22 Mar 2002 12:38:53 -0800 Subject: ANN: PythonCard 0.6.4 Message-ID: Apologies for the belated announcement. I was on the road the last two weeks and emailed to c.l.py.announce, but forgot to post to c.l.py. ka --- This release includes walkthroughs to get you started with PythonCard, an improved layout editor (resourceEditor sample), and new samples that use SOAP and XML-RPC (Blogger API). All the information you need about PythonCard can be found on the project web page at: http://pythoncard.sourceforge.net/ You can download the latest release at: http://sourceforge.net/project/showfiles.php?group_id=19015 For a list of the samples that have been built with PythonCard and some screenshots of them in action go to: http://pythoncard.sourceforge.net/samples.html A description of each sample is included in the readme.txt file in each sample directory. The kind people at SourceForge host the project: http://sourceforge.net/projects/pythoncard/ If you want to get involved the main contact point is the Mailing list: http://lists.sourceforge.net/lists/listinfo/pythoncard-users PythonCard requires Python 2.1.x or later and wxPython 2.3.2.1 or later and runs on every platform those are available for. wxPython can be downloaded at http://www.wxpython.org/ ka --- Kevin Altis altis at semi-retired.com From tony at lsl.co.uk Wed Mar 6 04:28:03 2002 From: tony at lsl.co.uk (Tony J Ibbs (Tibs)) Date: Wed, 6 Mar 2002 09:28:03 -0000 Subject: Python song? (Re: Python isn't necessarily slow) In-Reply-To: <86n0xmg2q4.fsf@skitty.catseye.net> Message-ID: <009001c1c4f1$377484b0$545aa8c0@lslp862.int.lsl.co.uk> Definitely off topic, but... Tim Legant wrote: > Oh, are you from across the pond? It was either Bronski Beat or the > Communards who did an interesting cover of Ain't Necessarily So in the > early '80s - I think both groups were Brits.... It's in more of a > Broadway musical style than country, though. I'm not sure which side of the pond Tim is from, so I'm not sure that helped... Anyway, the song "It ain't necessarily slow" is from George Gershwin's Porgy and Bess (see, for instance http://www.operaheb.co.il/operas/arias/porgy5.html). Jimmy Somerville (who is from Glasgow, which is in Scotland, and was at the time in Bronski Beat - later on he was indeed in the Communards) does indeed cover this - it's on the album The Age of Consent, and also on his singles album. I have no reason to think that Jimmy Somerville programs in Python, though... Tibs -- Tony J Ibbs (Tibs) http://www.tibsnjoan.co.uk/ Give a pedant an inch and they'll take 25.4mm (once they've established you're talking a post-1959 inch, of course) My views! Mine! Mine! (Unless Laser-Scan ask nicely to borrow them.) From jkraska at san.rr.com Tue Mar 12 02:34:08 2002 From: jkraska at san.rr.com (Courageous) Date: Tue, 12 Mar 2002 07:34:08 GMT Subject: should i learn it first ? References: <7CWi8.104549$aFN.34864@news1.bloor.is> <3C8D8B52.FAB4E102@engcorp.com> Message-ID: >> >seems a lot people recommend C over C++,... C is quite a bit less complicated than C++, although it's painful not having an easy way to do inheritance or virtual functions. Templates are nice in theory, although C++ template syntax is simply atrocious. C// From r.salz at verizon.net Mon Mar 18 17:27:02 2002 From: r.salz at verizon.net (Rich Salz) Date: Mon, 18 Mar 2002 22:27:02 GMT Subject: Need maintainer for wizard.py Message-ID: <3C9669B9.70105@verizon.net> Is anyone interested in taking over wizard.py, a module built on top of TKinter that makes it easy to write MS-style "wizards"? For details see http://www.zolera.com/opensrc/wizard/index.html (although that describes 1.4, not 1.5 which has some minor API cleanups). Please send me mail if so. /r$ From gh_pythonlist at gmx.de Wed Mar 13 21:42:59 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 14 Mar 2002 03:42:59 +0100 Subject: Performance problem with filtering Message-ID: <20020314024259.GA24728@lilith.hqd-internal> I have two lists of files (approx. 50000 entries). Now I want to have all the entries of list b, that are not in list a. However, the primitive: results = [] for entry in b: if entry not in a: results.append(entry) is terribly slow. I mean *really* slow. Any recommendations on how to optimize this? Wouldn't it be nice if I could simply do b.removeall(a)? Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 7.5 ?C Wind: 0.9 m/s From bokr at oz.net Sun Mar 24 03:40:21 2002 From: bokr at oz.net (Bengt Richter) Date: 24 Mar 2002 08:40:21 GMT Subject: list comprehension question References: Message-ID: On Sat, 23 Mar 2002 23:11:58 -0700, "Andrew Dalke" wrote: >Tripp Scott asked: >>can i generate this list: >> >> [1, 1.1, 2, 2.1, 3, 3.1] >> >>with a list comprehension in a form of this: >> >> [SOMETHING for x in 1,2,3] >> >>and without using side effects like this? > >There is no way with list comprehensions which is more >elegant than the standard solution, which is > >result = [] >for i in 1, 2, 3: > result.extend([i, i + 0.1]) > >>> a = [x+y for x in 1,2,3 for y in 0,0.1] >>> a [1, 1.1000000000000001, 2, 2.1000000000000001, 3, 3.1000000000000001] And to see the elements in normal individual print precision: >>> map(str,a) ['1', '1.1', '2', '2.1', '3', '3.1'] I guess that not quite what the OP asked for, i.e., it's [SOMETHING for x in 1,2,3 SOMETHING_ELSE] but no way say no way ;-) Regards, Bengt Richter PS. Anyone else getting weird mail quoting a post as bounced mail, saying (in part) -- > >Diagnostic-Code: X-Postfix; mail for taisha.hamete.org loops back to myself > >Received: from fuseki.hamete.org (fuseki.hamete.org [192.168.19.1]) > > by localhost.hamete.org (Postfix) with ESMTP id 0F56EBD93 > > for ; Sun, 24 Mar 2002 00:07:42 +0100 (CET) > >Received: from fuseki.hamete.org (localhost.localdomain [127.0.0.1]) > > by fuseki.hamete.org (Postfix) with ESMTP id AC6591E98 > > for ; Sat, 23 Mar 2002 23:58:24 +0100 (CET) -- I emailed the whois-indicated owner and tech support, and got an automated reply from the latter. From anthony at ekit-inc.com Mon Mar 11 19:43:25 2002 From: anthony at ekit-inc.com (Anthony Baxter) Date: Tue, 12 Mar 2002 11:43:25 +1100 Subject: PEP Parade In-Reply-To: Message from Tim Peters of "Fri, 08 Mar 2002 16:38:37 CDT." Message-ID: <200203120043.g2C0hP931608@burswood.off.ekorp.com> >>> Tim Peters wrote > I expect PythonLabs will continue wrapping up bugfix releases in the 2.1.x > series for as long as someone volunteers to produce them. At the moment, > 2.1.2 is the end of that line, as 2.1.2 was the last 2.1.x release to > attract a volunteer. I've yet to see a bug that makes 2.1.3 seem a likely or useful upgrade. There were a number of _critical_ bugs in 2.1.1 that made 2.1.2 useful. -- Anthony Baxter It's never to late to have a happy childhood. From jeff at ccvcorp.com Tue Mar 26 18:29:08 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 15:29:08 -0800 Subject: Symbolic imports and manipulation of the namespace? References: Message-ID: <3CA10444.718AB646@ccvcorp.com> VanL wrote: > Hello, > > I was recently solving a problem which required that the config file > (just a python file) lie outside of the pythonpath. Is it possible to > do symbolic importation of a module? You might want to look at the __import__() function. Jeff Shannon Technician/Programmer Credit International From djc at object-craft.com.au Fri Mar 1 23:16:30 2002 From: djc at object-craft.com.au (Dave Cole) Date: 02 Mar 2002 15:16:30 +1100 Subject: ASV module, CVS modules References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: >>>>> "John" == John Machin writes: John> Wow. You have two problems. Bill Gates has one. And one of John> either you or Dave Cole will get busted real soon now if you John> keep smoking that stuff :-) I haven't smoked since I tried it as a young kid and threw up... John> You and/or Dave in peril of the law: Last time I saw Dave's John> module it didn't presume to read files at all, it expected you John> to read lines and pass them to it one at a time. So either Dave John> has had a very recent rush of blood or something worse to the John> head and released unbeknownst to me a file-handling version of John> his module, or you are gravely mistaken when you assert "I get a John> similar message from CSV module". No such luck on the rush of blood to the head thing. I think you were correct in your assessment of the problem. Bill and his stoopid backslashes are to blame. - Dave -- http://www.object-craft.com.au From evebill8 at hotmail.com Fri Mar 15 12:46:01 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Fri, 15 Mar 2002 17:46:01 GMT Subject: socket References: Message-ID: Nothing evil here. I have 2 reasons why I would do this program. Firs, it is my TCP/IP concept class's project. Basically, I want to try what the book tells in to code, but I notice it does not work the way it says in so many commercial SMTP servers. Second, I have been unemployed for about 4 months. My friend's company needs a program to verify the users who registered to their service. They found out many registered users were using fake addresses. I just want to try this program to see if I will get a job there. That's all! I really do appreciate if you would provide any info for me to complete this project. Thanks in advance! Billy Ng "Grant Edwards" wrote in message news:CVnk8.25667$N7.5385001 at ruti.visi.com... > In article , Billy Ng wrote: > > > I am trying to write a python program to verify the email > > address. > > What you're trying to do is pointless. Whether it's evil or > not, I don't know, but one is suspicious. > > Most servers either refuse the verify command or always return > affirmative. Many modern servers will accept RCPT for invalid > addresses also. > > -- > Grant Edwards grante Yow! Did we bring enough > at BEEF JERKY? > visi.com From peter at engcorp.com Mon Mar 25 19:59:41 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 19:59:41 -0500 Subject: How to get a key from dictionary? References: Message-ID: <3C9FC7FD.A660C190@engcorp.com> A wrote: > > Hi, > Is there a possibility to get, from a dictionary, a key according to a > value ? > For example > I have a dictionary > > dict={'aa':1,'bb':2} > > and > dict['aa'] > is 1 > > But how can I for value 1 find out key? (That is here 'aa') If you've seen the other responses, you've learned about the issues. One possible solution I haven't seen suggested is that you simply populate two dictionaries, one for each direction. This of course works only if you have unique values as well as unique keys. If you wrap the two dictonaries inside a class that handles the hard work for you, you can make it appear that you have a regular dictionary but which lets you retrieve in both directions. -Peter From Michael_Toldo at hotmail.com Mon Mar 11 09:59:17 2002 From: Michael_Toldo at hotmail.com (Michael Toldo) Date: 11 Mar 2002 06:59:17 -0800 Subject: Need Help in Plone Message-ID: I installed the newest version of Plone. But now I have to adapt it to a cms. The different objects and the different templates make me crazy. Can anybody tell me, where to get a usefull documentation. Mick From cliechti at gmx.net Wed Mar 27 18:31:23 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Mar 2002 00:31:23 +0100 Subject: Dealing with python version References: Message-ID: Andrei Kulakov wrote in news:slrnaa2gf7.qed.ak at ak.silmarill.org: > Correct me if I'm wrong, but it seems like if python1.6 or 2.0 are > already installed and you install a newer version, python command > still points to the old interpreter. on my debian linux box the path to /usr/local/bin is in an other position in PATH for user root that for normal users. this means "python" points to 1.5.2 as root but to the current manually installed python 2.2 for users. chris -- Chris From max at malva.com.ua Thu Mar 7 07:41:12 2002 From: max at malva.com.ua (Max Ischenko) Date: Thu, 7 Mar 2002 14:41:12 +0200 Subject: C/C++ to Python translater References: <5e8bd451.0203011049.5d12d3a2@posting.google.com> Message-ID: <85n76a.0fb.ln@cvs> kevin parks wrote: > Is there a translator to automatically port (rewrite) code snippets > from C or C++ to Python? I have some old C code that i have been > porting by hand (well by head really) and i was wondering if there > were any translation utilities that i could try. I imagine that this > would be a monster AI undertaking, Btu with Python's powerful built-in > types i am guessing c --> Python is easier than the opposite. SWIG from www.swig.com From rnd at onego.ru Sat Mar 9 08:28:18 2002 From: rnd at onego.ru (Roman Suzi) Date: Sat, 9 Mar 2002 16:28:18 +0300 (MSK) Subject: Learning from imperfect lectures In-Reply-To: <20020308070818.GA1112@isis.gerrietts.net> Message-ID: On Thu, 7 Mar 2002, Geoff Gerrietts wrote: >Quoting Peter Hansen (peter at engcorp.com): >> Roman Suzi wrote: >> > >> > I do not remember who told me this, but it seems that students >> > better learn from poorly constructed lectures than perfect ones. >> > Because, they need to be _active_ in constructing their own system >> > rather than _passively_ "eat" readymaid knowledge frames. >> >> Wow. Deep... I like this (to me) completely new idea. > >This idea was new to me, too, in form but not in concept. Pedagogical >coursework -- like the stuff they teach to new grad students who are >going to be teaching assistants, or the stuff they teach to people in >education programs -- frequently talks about how important it is to >engage the student, and how involving them and making them think about >the material is the teacher's primary task, with presenting the >material actually being secondary. I could continue on this and say that teachers who got only highest mark at pedagogical college are often... bad teachers. And ones who had hard time learning are (not as a rule, but noticebly) better. Because they are nearer to the schoolchildren they teach. We call it "3-mark effect" (I do not know how to translate it right) : in Russia we have marks 2, 3, 4, 5, five being highest mark. OK, world-class professors are better teachers than former 3-mark student, but these are rare in usual schools. That is why I am poor teacher: I know the subject, but am a pathological 5-marker ;-) And I left teaching some time ago. >The actual practice of an "imperfect presentation", though, is >something I'd not considered before -- the idea of leaving blanks for >the student to fill in is both appealing and a little alarming. I remember how I was shocked with printed lectures of some western university: they were _perfect_. They were easy to grasp but I had a feeling that they beautify the picture (dumb it down). In our universities we usually write lectures (conspects) manually. So, their presentation is less than perfect. >> Anyone know where it came from? References to a study or something? > >> strong interest in the audience ahead of it (and after). The >> presentation struck me at the time as being _very_ "polished", but >> perhaps with too little unsaid for someone to question, or think >> about. I suspect this is the reason why it didn't seem to work. > >Interesting anecdotal evidence. I can think of several cases where >I've felt somewhat the same way about presentations that I've given. >It's often taught me and my audience both more if my presentation is >struggling to hold together at the seams. Some lecturers even allow errors to check attention of the audience. And it works too. In the estimation theory there are models where it is impossible to make estimation of some values if inputs aren't noisy! The same is true in genetics where mutations and selection make species stronger. This means trial-and-error way is not unfounded. Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Saturday, March 09, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "And now for something ruder..." _/ From bkc at Murkworks.com Thu Mar 7 13:42:17 2002 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 7 Mar 2002 13:42:17 -0500 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3c864a78$1_3@news.newsgroups.com> <873czdnmqp.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <3c87b5aa_10@news.newsgroups.com> "Stephen J. Turnbull" wrote in message news:873czdnmqp.fsf at tleepslib.sk.tsukuba.ac.jp... > >>>>> "Brad" == Brad Clements writes: > > I thought it was clear, although I haven't tried to apply it yet. > > (I'm a co-author) Heh, greetings, funny meeting you here! It's hard to tell which chapter you wrote.. or which picture is yours... -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! Check out our new Unlimited Server. No Download or Time Limits! -----== Over 80,000 Newsgroups - 19 Different Servers! ==----- From krissepu at vip.fi Fri Mar 8 03:27:08 2002 From: krissepu at vip.fi (pekka niiranen) Date: Fri, 08 Mar 2002 08:27:08 GMT Subject: PARTIAL SOLUTION: Compiling Python 2.2 with GCC in HPUX 10.20 does not work Message-ID: <3C8875FE.9030700@vip.fi> First of all, thank you guys for your help. I managed to compile Python 2.2 in HP-UX 10.20 with the following hacks: 1) I downloaded and installed from http://hpux.connect.org.uk/ the following dynamically linked precompiled software depots: binutils 2.11.2 gcc 3.0.1 make 3.79.1 These all installed automatically into /opt -directory, since I used "swinstall -s" -command: swinstall -s make-3.79.1-sd-10.20.depot make 2) I also downloaded from http://hpux.connect.org.uk/ HP's sources for ncurses-5.2 HP-UX Source Code (gzipped) [HTTP] [FTP] (Size: 1.74 MB, Archived: 12 Jan 2001, View contents) and unzipped+tared it to a temporary directory. 3) I removed HP's default compiler's location /usr/css/bin from my /etc/PATH -file and changed the link in /usr/bin to point to installed gmake: /usr/bin/make@ -> /opt/make/bin/gmake I also added /opt/make/bin and /opt/gcc/bin to my PATH. 4) I configured ncurses with the following script: #! /usr/bin/sh unset LANG TERM=vt100 gmake distclean CC=gcc ./configure --with-gcc --with-shared --without-cxx --prefix=/usr/local --without-ada --without-debug 5) I edited the resulting Makefile in subdirectory ncurses-5.2/ncurses by adding the -fpic variable to line 96: CFLAGS_SHARED = $(CCFLAGS) -fPIC -fpic 6) I compiled and installed ncurses with commands: make make install My /usr/local/lib/ -directory: libcurses.sl@ -> libncurses.sl 104294 Mar 8 08:41 libform.a 102955 Mar 8 08:41 libform.sl* 52572 Mar 8 08:41 libmenu.a 49377 Mar 8 08:41 libmenu.sl* 531110 Mar 8 08:41 libncurses.a 595297 Mar 8 08:41 libncurses.sl* 20948 Mar 8 08:41 libpanel.a 20538 Mar 8 08:41 libpanel.sl* terminfo@ -> ../share/terminfo My /usr/local/include/ -directory: 60691 Mar 8 08:41 curses.h 2825 Mar 8 08:41 eti.h 16091 Mar 8 08:41 form.h 10951 Mar 8 08:41 menu.h ncurses.h@ -> curses.h 3434 Mar 8 08:41 panel.h 3168 Mar 8 08:41 termcap.h 36954 Mar 8 08:41 term.h 2957 Mar 8 08:41 unctrl.h 7) Python-2.2 source I edited by adding line "int h_errno;" to Modules/socketmodule.c at line 161 just above the '#ifndef RISCOS' block: int h_errno; #ifndef RISCOS #include #else #include #define NO_DUP int h_errno; /* not used */ #endif #else 8) I configured python with script: #! /usr/bin/sh unset LANG gmake distclean CC=gcc ./configure --with-gcc --with-threads=no --without-cxx --prefix=/opt/python gmake 9) When running "gmake test", I still get error: test test_fpformat failed -- Traceback (most recent call last): File "./Lib/test/test_fpformat.py", line 51, in test_reasonable_values self.checkFix(realVal, d) File "./Lib/test/test_fpformat.py", line 28, in checkFix self.assertEquals(result, expected) File "/osasto/home/niirape/python_softa/Python-2.2/Lib/unittest.py", line 286, in failUnlessEqual raise self.failureException, \ AssertionError: '-0' != '0' And summary looks like: 1 test failed: test_fpformat 33 tests skipped: test_al test_asynchat test_bsddb test_cd test_cl test_curses test_dl test_fork1 test_gdbm test_gl test_gzip test_imgfile test_largefile test_linuxaudiodev test_locale test_minidom test_nis test_ntpath test_openpty test_pyexpat test_sax test_socket_ssl test_socketserver test_sunaudiodev test_thread test_threaded_import test_threadedtempfile test_threading test_unicode_file test_winreg test_winsound test_zipfile test_zlib Ask someone to teach regrtest.py about which tests are expected to get skipped on hp-ux10. make: *** [test] Error 1 10) After gmake install python starts OK. Maybe it is OK now ;). -pekka- From idot at vt.edu Tue Mar 12 23:13:23 2002 From: idot at vt.edu (Carl Banks) Date: 12 Mar 2002 20:13:23 -0800 Subject: Is there a good reason why we cannot (as of 2.1.1) deepcopy complex objects? References: Message-ID: idot at vt.edu (Carl Banks) wrote in message news:... > Strangely, I've found no mention of this anywhere: the docs, the > Python FAQ, or the Google archives. And to clarify, I mean complex number objects.... -- CARL BANKS From joejava at dragoncat.net Sat Mar 30 01:19:28 2002 From: joejava at dragoncat.net (Joel Ricker) Date: Sat, 30 Mar 2002 01:19:28 -0500 Subject: Data type ideas Message-ID: <004701c1d7b2$dbbf9180$a2a1d6d1@x9k7y2> HI all, got a new problem :) I have a tab delimited file of people plus a list of groups they belong to like so: Person 1 Group A Group B Person 2 Group B Person 3 Group A Group C So basically a person can be part of one of more groups. I'm looking to process this list so that I can take each group and examine the list of people in it. Basically turn the list into: Group A Person 1 Person 3 Group B Person 1 Person 2 Group C Person 3 The drawback I have to all this is, the file I'm working is pretty big: about 40 megs. A majority of the file is going to be extraneous data that I have weeded out with regular expressions but it is still a large data file. My first (naive) approach was to just create a Dict type using the name of the group as a the key and for the value a list of people. I learned that due to the overhead, that was going to take alot of memory and processing time. It would look something like this: {"Group A" : ["Person 1", "Person 3"], "Group B" : ["Person 1", "Person 2"], "Group C" : ["Person 3"]} My next idea was what about references? Maybe create a list of people and a Dict as above with a list of references to the list of people. But as I learned you can't do references to simple data objects (like a subscript of a list). I could be wrong but thats what I gathered. I tried using a list of integers for the value of the Group Dict, "pointing" to the list of People: {"Group A" : [0, 2], "Group B" : [0, 1], "Group C" : [2] } ["Person 1", "Person 2", "Person 3"] This helped a little but obviously not much since it isn't much of a change from what I've had before. So what next? Any ideas that I can use? Thanks Joel -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri Mar 1 02:34:26 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 08:34:26 +0100 Subject: PEP 263 comments References: Message-ID: "Jason Orendorff" writes: > > Java does accept iso-latin-1 files as input. In fact on my machine (Mac > > OSX) it doesn't even accept utf-8 files with the utf-8 signature. And > > strings containing utf-8 are interpreted as just 8-bit characters, meaning > > every byte is a character. > > Oh! Yes, it works this way on Windows, too. javac assumes source > files are latin-1, and System.out.println() encodes output in latin-1. That is not completely true. javac has the -encoding command line which allows you to specify the source encoding; this defaults to the platform default encoding (which probably was latin-1 resp. windows-1252 on your systems). > I'm referring to this paragraph in Martin's original post: > > The only problem with this approach is that encodings where " or ' > could be the second byte of a multi-byte character cannot be > supported as a source encoding. Python supports no such encoding > in the standard library at the moment, anyway, so this should not > be a problem. > > \x22 is a double-quote mark. Martin is a little off on the last > bit, though; UTF-16 can produce \x22 bytes. Right. Source encodings (atleast under the initial implementation) need to be an ASCII superset (in the sense that source code that uses only ASCII characters is ASCII-encoded); I see no way to allow UTF-16 as a source encoding. Regards, Martin From oleksik at awa.mat.agh.edu.pl Tue Mar 19 05:58:46 2002 From: oleksik at awa.mat.agh.edu.pl (Pawel Oleksik) Date: Tue, 19 Mar 2002 10:58:46 +0000 (UTC) Subject: [wxPython 2.3.1] what's going on? Message-ID: Hi Snakes Tamers! Playing with wxPython modules I've found something -- perhaps bug. Importing from wxPython.wx changes the calculation rules. Here is an example (strictly based on the random.py self-verification): (Linux, glibc-2.2.5, wxGTK-2.3.1, wxPython-2.3.1) Python 2.1.1 (#1, Aug 26 2001, 02:52:19) [GCC 2.95.3 20010315 (release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import math >>> 4*math.exp(-0.5)/math.sqrt(2.0) 1.7155277699214135 >>> from wxPython.wx import * >>> 4*math.exp(-0.5)/math.sqrt(2.0) 2,8284271247461898 Has anybody met this problem, or it's just my 'private reslult' :) best regards p.o. From dale at riverhall.NOTHANKS.co.uk Fri Mar 22 20:54:59 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 23 Mar 2002 01:54:59 +0000 Subject: The IDE is important too [was Develop-test-debug cycle] Message-ID: Tim Peters wrote: > >Yes, and we're not going to fix it . > I don't think you should dismiss it so flipantly and readily - unless you see Python as a toy language for small scripts and noddy programs. The large systems that we are writing take a while to crank up. To have to shut them down, fix the bug (if it was obvious) or add some debugging code (if it wasn't), then crank them up again, is a significant time overhead. It seems to me that the development environment has been seriously neglected in the rush to add sexy new features to the language. Microsoft, Borland and the like realised a long time ago that a nice IDE makes a huge difference to programmer productivity - even if the language is crap. Consider this: without the IDE, would anyone have given VB a second glance? I don't want all the frils of VB - PythonWin is almost there but - and I'm guessing here - it is limited by the language runtime environment. It would be an enormous help if the runtime environment had debugger hooks that could preserve program state in the event of an untrapped error, then allow any of: 1. statements to be executed interactively in the current context; 2. execution point adjusted forwards or backwards (with obvious restrictions) 3. continue execution; 4. program reset to initial entry conditions - including terminating any threads. You can already do 1. at breakpoints in PythonWin so some of the hooks are there. If you could fix all these four requirements, I reckon you could more than quadruple my productivity on large projects. -- Dale Strickland-Clark Riverhall Systems Ltd From samschul at pacbell.net Sat Mar 30 21:05:04 2002 From: samschul at pacbell.net (Samuel Schulenburg) Date: 30 Mar 2002 18:05:04 -0800 Subject: ANN: SCSIPyTOOLS a library of Python tools to test SCSI and IDE disk drives Message-ID: I have posted the combined ASPI and SCSIPASSTHROUGH libraries for Python at the following URL: http://starship.python.net/crew/samschul/ This release supports Python version 2.2 only. Future releases will follow the updates to the Python Library's. the main features of this open source release are: 1) Any machine the supports ASPI will execute the ASPIPy libraries. 2) All Windows maxhines WindowsNT -> WindowsXP that support the SCSIPASSTHROUGH interface will execute the SCSIPy libraries. 3) Both libraries are available at any time or together under python for example issueing the following Python commands will interface to either library: ISSUE COMAMND TO START SCSI >>> import scsi as Scsi scsi.py Copyright 2002 by Samuel W. Schulenburg 13555 Colony Ave. San Martin Calif. USA samschul at pacbell.net SCSI Python library loaded verson: scsi.py 0.9 03/20/03 Type help for command line help functions, or use IDLE help menu File SCSI0.log allready exists: Do you want to append or delete A/D d SCSIPython Version 0.9 03/19/2002 Windows high performance clock detected File SCSI1.log allready exists: Do you want to append or delete A/D d SCSIPython Version 0.9 03/19/2002 Windows high performance clock detected File SCSI2.log allready exists: Do you want to append or delete A/D d SCSIPython Version 0.9 03/19/2002 Windows high performance clock detected ----Device Characteristics--- Claimed = 1 DeviceID = 0 DeviceInquery = Maxtor 94098U8 FA50 DeviceName = \\.\Physicaldrive0 DriverName = atapi TID = 0 LUN = 0 MaxLBA = 80041247 SectorSize = 512 ------------------------------ ----Device Characteristics--- Claimed = 1 DeviceID = 1 DeviceInquery = Maxtor 53073U6 DAC1 DeviceName = \\.\Physicaldrive1 DriverName = atapi TID = 1 LUN = 0 MaxLBA = 60030431 SectorSize = 512 ------------------------------ ----Device Characteristics--- Claimed = 1 DeviceID = 2 DeviceInquery = SEAGATE ST118273N 6244 DeviceName = \\.\Physicaldrive2 DriverName = aic78xx TID = 0 LUN = 0 MaxLBA = 35566479 SectorSize = 512 ------------------------------ The default DeviceID will be 2 Error Loging has been enabled: CDB 12 00 00 00 FF 00 SCSIPython Version 0.9 03/19/2002 SEAGATE ST118273N 6244LP633950 NOW ISSUE COMMAND TO START ASPI >>import aspi as Aspi aspi.py Copyright 1999 by Samuel W. Schulenburg 13555 Colony Ave. San Martin Calif. USA samschul at pacbell.net ASPI Python library loaded verson: aspi.py 2.0 07/03/00 Type help for command line help functions, or use IDLE help menu Host adapter driver = ATAPI Drives are attached Host adapter # 0 SCSI ID # 7 Host adapter driver = ATAPI Drives are not attached Host adapter # 1 SCSI ID # 7 Host adapter driver = AIC78XX Drives are attached Host adapter # 2 SCSI ID # 7 Select which host adapter do you want to use, Enter host adapter number 2 0 SEAGATE ST118273N 6244LP633950 1 Drive not present 2 Drive not present 3 Drive not present 4 Drive not present 5 Drive not present 6 Drive not present 8 Drive not present 9 Drive not present 10 Drive not present 11 Drive not present 12 Drive not present 13 Drive not present 14 Drive not present File SCSI0.log allready exists: Do you want to append or delete A/D d ASPIPython Version 2.3 01/20/2002 Windows high performance clock detected CDB 12 00 00 00 FF 00 ASPIPython Version 2.3 01/20/2002 SEAGATE ST118273N 6244LP633950 >>Scsi.io6r(0x12,0x00,0,0,0xff,0) CDB 12 00 00 00 FF 00 (0, 65392, 144) >>s.displaybuff(1) Read Buffer Data = for drive #02 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F -------------------------------------------------- 0000:|00 00 02 02 8B 00 00 1E 53 45 41 47 41 54 45 20 ........SEAGATE. 0010:|53 54 31 31 38 32 37 33 4E 20 20 20 20 20 20 20 ST118273N....... 0020:|36 32 34 34 4C 50 36 33 33 39 35 30 00 00 00 00 6244LP633950.... 0030:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0040:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0050:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0060:|00 43 6F 70 79 72 69 67 68 74 20 28 63 29 20 31 .Copyright.(c).1 0070:|39 39 38 20 53 65 61 67 61 74 65 20 41 6C 6C 20 998.Seagate.All. 0080:|72 69 67 68 74 73 20 72 65 73 65 72 76 65 64 20 rights.reserved. 0090:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00A0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00B0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00C0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00D0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00E0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00F0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ >>Aspi.io6(0x12,0x00,0,0,0xff,0) CDB 12 00 00 00 FF 00 (0, 0, 65536) >>Aspi.displaybuff(1) Read Buffer Data = for drive #00 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F -------------------------------------------------- 0000:|00 00 02 02 8B 00 00 1E 53 45 41 47 41 54 45 20 ........SEAGATE. 0010:|53 54 31 31 38 32 37 33 4E 20 20 20 20 20 20 20 ST118273N....... 0020:|36 32 34 34 4C 50 36 33 33 39 35 30 00 00 00 00 6244LP633950.... 0030:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0040:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0050:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 0060:|00 43 6F 70 79 72 69 67 68 74 20 28 63 29 20 31 .Copyright.(c).1 0070:|39 39 38 20 53 65 61 67 61 74 65 20 41 6C 6C 20 998.Seagate.All. 0080:|72 69 67 68 74 73 20 72 65 73 65 72 76 65 64 20 rights.reserved. 0090:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00A0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00B0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00C0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00D0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00E0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00F0:|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ >> Enjoy: Samuel Schulenburg From huckle at edsamail.com.ph Sat Mar 16 21:00:57 2002 From: huckle at edsamail.com.ph (huck) Date: Sun, 17 Mar 2002 10:00:57 +0800 Subject: why python for the academe? Message-ID: hello all, i've been lurking for a while and am amused at how many people in the list here use python for scientific computing. why not matlab (or octave or scilab or whatever)? wondering, huck __________________________________ www.edsamail.com From fperez528 at yahoo.com Fri Mar 1 02:36:28 2002 From: fperez528 at yahoo.com (Fernando Pérez) Date: Fri, 1 Mar 2002 00:36:28 -0700 Subject: Numeric Python Installation woes References: <2dg03lvk1q.fsf@james.hut.fi> Message-ID: > > Maybe you should re-install it (python 22) and get rid of the two old installations. Careful. The OP hasn't specified but from the symptoms I suspect he's a victim of RedHat's completely ass-backwards python setup as of 7.2. He'll majorly blow his system if he removes 1.5. His best bet is to manually build 2.2, shove it into /usr/local/, and make sure that gets found by his user's /usr/bin/env before 1.5. But NOT by root and other system-level users (like those of certain daemons), those need to see 1.5. He'll just have to play a few path games. And complain to redhat for the mess they've made. Every other week there's someone here totally (and justly) confused by their setup. I have yet to hear a convincing argument from them justifying what they did. They could perfectly have made it so that _their_ scripts find 1.5 first if they need it, while allowing the user system default to be 2.x. But no, instead they chose to make it difficult for users who aren't too savvy with internals to safely switch to 2.x (if you simply change the global python link to point to 2.x, you break lots of stuff). Cheers, f. From kzaragoza at attbi.com Tue Mar 26 23:25:44 2002 From: kzaragoza at attbi.com (Kris J. Zaragoza) Date: Wed, 27 Mar 2002 04:25:44 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: In article <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82 at lp.airnews.net>, Dean Goodmanson wrote: > Kris Zaragoza and others explain how to make your own use of MS SQL > Server with Python. > http://groups.google.com/groups?th=efccf3faf8d7eb11 Wow. I never thought I'd see my name in lights! (Those tiny little pixels on my screen are lights, right?) I feel special. :) Even though my post is a bit old, let me just add that it still holds true, even with SQL Server 2000. Just one warning, though: If you are having performance problems talking to SQL Server, use the profiler. Take special care when using ADO; I've seen it do some really horrendous stuff for what should be a simple stored procedure call. > -- The Python-URL! Team-- > > Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and > sponsor the "Python-URL!" project. Let me just take a moment to thank everyone involved in Python-URL! This is, IMHO, a wonderful resource for this community. I have found it extremely useful in keeping up with things when extremely busy (as I seem to have been all this year so far!) Thanks again! -Kris -- Kris J. Zaragoza | On the face of it, Microsoft complaining about kzaragoza at attbi.com | the source license used by Linux is like the | event horizon calling the kettle black. | -- Adam Barr, article on kuro5hin.org From loewis at informatik.hu-berlin.de Sun Mar 10 13:50:32 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 10 Mar 2002 19:50:32 +0100 Subject: Binary Register entries Question References: Message-ID: matthias_j at lycos.com (Matthias Janes) writes: > I exported a Win NT register to a reg file like this. > > [HKEY_CURRENT_USER\Software\TEST] > "Password"=hex:b3,e8,85,f6,4d,9c,29,04 > > Now I'm not sure how to write binary Hex data with python. [...] > values = ...... I do not know how to use this for binary hex data You need to use a byte string: values = '\xb3\xe8\x85\xf6\x4d\x9c\x29\x04' If you want to create the string dynamically, use the chr builtin. Regards, Martin From dale at riverhall.NOTHANKS.co.uk Sun Mar 24 06:17:34 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sun, 24 Mar 2002 11:17:34 +0000 Subject: forgetting state References: <98b6685d.0203231539.1459d00d@posting.google.com> Message-ID: emersonwood at yahoo.com (Emerson Wood) wrote: >Hi, how would I make a python interpreter >shell forget everything that I've done >and run a script or accepts commands as >if it were first run? > >The reason I ask is that I'm running >on Windows, and using the IDLE which >keeps a Python shell up all the time. >It would be natural to use that shell >to test my program, but I'm finding >problems running it twice. > >-Emerson This is a known, zero priority problem. See my recent posts on the develop-test-debug cycle. -- Dale Strickland-Clark Riverhall Systems Ltd From nospam at mega-nerd.com Sat Mar 9 18:13:50 2002 From: nospam at mega-nerd.com (Erik de Castro Lopo) Date: Sat, 09 Mar 2002 23:13:50 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> Message-ID: <3C8A972E.8517ABEF@mega-nerd.com> brobbins333 at shaw.ca wrote: > > the round() function will sometimes return a predictable result, as > in: > > round(45.67891, 2) > >>> 45.68 > > but sometimes it will return something like: > > round(56.78923, 2) > >>> 56.789999999999999 > > 2.1 and 2.2 both behave this way on two different (Windows) computers. > What's going on here? You are running into problems with the floating point representation of numbers. You may want to look up how floating point numbers are stored in computers. Search google. What you will fins is that some numbers like 2, 0.25 etc can be represented exactly in floating point format while others like 2/3 cannot. Thats just the way it is. Erik -- +-----------------------------------------------------------+ Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) +-----------------------------------------------------------+ BSD: A psychoactive drug, popular in the 80s, probably developed at UC Berkeley or thereabouts. Similar in many ways to the prescription-only medication called "System V", but infinitely more useful. (Or, at least, more fun.) The full chemical name is "Berkeley Standard Distribution". From sandskyfly at hotmail.com Sun Mar 10 09:00:12 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 10 Mar 2002 06:00:12 -0800 Subject: python and haskell for fun References: Message-ID: "Patrick" wrote: > This subset of PASKELL will be clean, beautiful and functional. I'm sorry I wasn't clear. I meant 'beget a pretty monster' of an application, not a language. The last thing I would want to do is waste time discussing a new hybrid 'PASKELL' language... Now I haven't attempted to actually combine the dynamic duo yet in a test app, but the idea is nonetheless intriguing: on the lines of using the Glasgow Haskell Compiler to turn certain charming algorithms in haskell into executables or COM servers, and then use python to glue the parts together with other parts using pipes, COM or whatever. Now, I love python (my everyday programming language), and will not give it up for the world: the way I see it, python introduces me to other parts of the CS universe that I would surely not have engaged if it wasn't for the language and its community -- jython and java being a great example. Even so, one must admit that haskell is a great window into the world of functional programming and no doubt holds its own in terms of elegance. A case in point is ye olde quicksort: -- haskell quicksort (from the Prelude?) qsort [] = [] qsort (x:xs) = qsort [y | y <- xs, y < x ] ++ [x] ++ qsort [y | y <- xs, y >= x] # Nathan Gray's Python cookbook version # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66473 def qsort(L): if len(L) <= 1: return L return qsort( [ lt for lt in L[1:] if lt < L[0] ] ) \ + [ L[0] ] \ + qsort( [ ge for ge in L[1:] if ge >= L[0] ]) Now if that ain't purrty I don't know what is... So why can't I have my python and haskell too (-; Sandy From tdelaney at avaya.com Thu Mar 14 17:49:15 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 15 Mar 2002 09:49:15 +1100 Subject: Has Mark Hammond attained pariah status yet? Message-ID: > From: Brad Clements [mailto:bkc at Murkworks.com] > > "Mark Hammond" wrote in message > news:3C907711.4030004 at skippinet.com.au... > > > But if I combine this with the fact that new .NET beta > releases often > > breaks the Python compiler but I have only received 2 > complaints in a > > year, I concluded that interest is not yet high :) > > > > Mark. > > > > And .NET is expensive to actually deploy, and we're all cheap. After all, why else would we use a *free* language with no restrictions ... ;) While I'm here, I'd like to thank Mark for all the work he has put into the Python community and for his valiant attempt to date to corrupt .NET into something possibly worth using (for customers, not me ;) Tim Delaney From mxp at dynalabs.de Fri Mar 8 15:40:50 2002 From: mxp at dynalabs.de (Michael Piotrowski) Date: Fri, 08 Mar 2002 21:40:50 +0100 Subject: PARTIAL SOLUTION: Compiling Python 2.2 with GCC in HPUX 10.20 does not work References: <3C8875FE.9030700@vip.fi> Message-ID: pekka niiranen writes: > 9) When running "gmake test", I still get error: > > test test_fpformat failed -- Traceback (most recent call last): > File "./Lib/test/test_fpformat.py", line 51, in test_reasonable_values > self.checkFix(realVal, d) > File "./Lib/test/test_fpformat.py", line 28, in checkFix > self.assertEquals(result, expected) > File > "/osasto/home/niirape/python_softa/Python-2.2/Lib/unittest.py", > line 286, in failUnlessEqual > raise self.failureException, \ > AssertionError: '-0' != '0' I've had a look at test_fpformat: The test expects that "%.*f" % (0, -0.003) produces -0 (negative zero), but on HP-UX 10.20, this yields 0. It seems that, according to IEEE, -0 would be correct, and this is indeed what you get on HP-UX 11. This is basically a, ahem, property of the 10.20 libc; I don't think there's anything reasonable one could do about it. Also, apart from the test, I'd think that this has any impact on Python. If you need the "correct" behavior, the best idea might be to upgrade to 11. You might also want to have a look at According to this posting, Solaris 7 and AIX 4.3 seem to behave in the same way as HP-UX 10.20, so test_fpformat should fail on these platforms, too. -- Michael Piotrowski, M.A. From paoloinvernizzi at dmsware.com Wed Mar 27 04:08:15 2002 From: paoloinvernizzi at dmsware.com (Paolo Invernizzi) Date: Wed, 27 Mar 2002 10:08:15 +0100 Subject: Build python under VS.NET Message-ID: Hi all, I'm trying, for the first time, to build the current python cvs under VS.NET, in debug mode. The problem is... D:\cvs\python\dist\src\PCbuild>python_d Adding parser accelerators ... Done. Python 2.3a0 (#29, Mar 18 2002, 12:06:07) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sre Traceback (most recent call last): File "", line 1, in ? File "D:\cvs\python\dist\src\lib\sre.py", line 97, in ? import sre_compile File "D:\cvs\python\dist\src\lib\sre_compile.py", line 13, in ? import _sre,sys ImportError: dynamic module does not define init function (init_sre) [9591 refs] And so on with any subproject... like socket, sre, etc,etc... Any hint? Thanks in advance Paolo Invernizzi DMSWare.com From timr at probo.com Sat Mar 30 00:31:56 2002 From: timr at probo.com (Tim Roberts) Date: Fri, 29 Mar 2002 21:31:56 -0800 Subject: Unicode with win32com and makepy Message-ID: <71jaau4q7m8ljplv7r9vrog529dibnf4s9@4ax.com> Some time ago, I posted about a problem I was having accessing text fields from an Access database using ADO via win32com. I was getting an error about characters with ordinals beyond 255. Several suggestions were offered, but none helped. I dug in to this a bit more. The problem can be traced into the Python files generated by makepy. I did a makepy on ADO 2.5. About a third of the way through that generated file, we find class Field(DispatchBaseClass): which contains this: # str(ob) and int(ob) will use __call__ def __str__(self, *args): try: return str(apply( self.__call__, args)) except pythoncom.com_error: return repr(self) If I try to fetch the contents of an Access field with an extended character (e with an umlaut, in my case), the error happens in the "return str(apply(..." line. This is somewhat sensible, since it is being asked to convert a character outside ASCII. Several folks suggested I call unicode() to fetch the string value of the field. This does not work; the Field class does not contain a __unicode__ method, so Python calls __str__ instead, which fails. My temporary workaround is to edit the generated Python (!) by adding a __unicode__ method: def __unicode__(self, *args): try: return unicode(apply( self.__call__, args)) except pythoncom.com_error: return repr(self) Now, I can wrap unicode() around my field fetch, and it does fetch the correct string. Here's the question: what do we do in the long term? Should makepy generate a __unicode__ member every time it generates a __str__ member? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From just at xs4all.nl Mon Mar 25 07:07:11 2002 From: just at xs4all.nl (Just van Rossum) Date: Mon, 25 Mar 2002 13:07:11 +0100 Subject: 2.2 open References: <1UtsCLAcngn8EwWc@jessikat.fsnet.co.uk> Message-ID: In article , Robin Becker wrote: > yes, but presumably abs is not the same as type(abs(1.2)) so this only > applies to certain factories rather than all functions. But of course: type objects are callable, but not every callable is a type object... > So the question now is, how do I tell if __import__ is the built in one > even if the import system is not fully initialized. In any case not by comparing its type with type(open)... If you really can't import types.py at that point, comparing it with eg. type(abs) doesn't seem too bad. Just From jcosby at mindspring.com Sun Mar 31 09:46:58 2002 From: jcosby at mindspring.com (Jon Cosby) Date: Sun, 31 Mar 2002 06:46:58 -0800 Subject: List problem References: Message-ID: This is strange. I've added some lines to see where this is failing. You can see below the interpreter is not detecting matches, but they are there, and it is showing them. There is something in word[0] == firstword[i] that's not right or the interpreter isn't understanding. What could possibly be wrong with this? ################################################################ for word in words: for i in range(lword): if word[0] == firstword[i]: print "true" # Are there any matches found? cols[i].append(word) print len(words) print cols C:\Python21>python projects\wordsquare.py Enter first word (enclosed in quotes): "hello" 4220 [[], [], [], [], []] ########################################################################## l = [] for word in words: for i in range(lword): l.append(word[0] + ":" + firstword[i]) if word[0] == firstword[i]: cols[i].append(word) print len(words) print cols print l C:\Python21>python projects\wordsquare.py Enter first word (enclosed in quotes): "add" 502 [[], [], []] ['A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'B:a', 'B:d', 'B:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'C:a', 'C:d', 'C:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', 'D:a', 'D:d', 'D:d', ...] "Jon Cosby" wrote in message news:a82mlc$ja1$1 at slb6.atl.mindspring.net... > Can anyone se why this is coming up empty in the "cols" list? I've tried > something similar in the interpreter, and everything here looks right. For > some reason, it isn't finding any matches here. > > ######################################################################## > # WordSquare > # Build word squares from initial word > # > > > # Word dictionary > dict = "c:\data\dict.txt" > > firstword = input("Enter first word (enclosed in quotes): ") > lword = len(firstword) > words = [] > cols = [] > rows = [] > > > f = open(dict, "r") > for line in f.readlines(): > if len(line[:-1]) == lword: > words.append(line[:-1]) > f.close() > > > for i in range(lword): > cols.append([]) > rows.append([]) > rows[0].append(firstword) > > # Generate an array of words with matching first letters > for i in range(lword): > for word in words: > if word[0] == firstword[i]: # Matches not found > cols[i].append(word) > > print len(words) > print cols > > ###################################################################### > > C:\Python21>python projects\wordsquare.py > Enter first word (enclosed in quotes): "hello" > 4220 > [[], [], [], [], []] > > C:\Python21> > > > > Jon Cosby > > > From huaiyu at gauss.almadan.ibm.com Fri Mar 1 14:41:54 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 1 Mar 2002 19:41:54 +0000 (UTC) Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: I've been following this discussion with quite some interest, but I do not have the background to delimit the scope of various concepts. Is there a gentle introduction to a unicode-newbie? On 01 Mar 2002 15:39:42 +0900, Stephen J. Turnbull wrote: > >IMO, the Python source code parser should never see any text data[1] >that is not UTF-8 encoded. Presumably this discussion only concerns unicode strings - I don't think want to lose the ability to read in arbitrary binary data as a raw string. But then you mention >[1] Ie, Python language or character text. It might be convenient to >have an octet-string primitive data type, in which you could put >EUC-encoded Japanese or Java byte codes. What's the difference between this and a raw string (a byte sequence) that you can translate into any other encoding? Huaiyu From claird at starbase.neosoft.com Fri Mar 15 12:46:24 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 15 Mar 2002 11:46:24 -0600 Subject: Converting relative URLs to absolute References: <23891c90.0203130331.6f030f5b@posting.google.com> <23891c90.0203150820.6362868@posting.google.com> Message-ID: <1BA0B611A94DFC68.31BB361E767CE89A.765E82A2856C9826@lp.airnews.net> In article <23891c90.0203150820.6362868 at posting.google.com>, Paul Boddie wrote: >James A Roush wrote in message news:... >> > >[Handling relative and "rooted" links in Web pages] > >> This precisely what I'm looking for. As someone else pointed out in another >> post, urllib should have this but, sadly, does not. > >The module I mentioned [1] doesn't attempt to handle more >sophisticated URL types, such as... > > http://user at somesite/somepath > >Indeed, a more generic URL parser really needs to be put into the >standard library whilst retaining the simplicity that one tends to see >in other "path" manipulation APIs (eg. os.path) - the world doesn't >need another overcomplicated Java-like API to do the simplest of >things. I wonder if mxURL might at least provide inspiration. > >Paul > >[1] http://www.boddie.org.uk/downloads/urlutils.py >From what I've seen, cURL, or more properly libcurl , has cornered the market in being an efficiently coded library which properly interprets the most recent URL standards. Is Python best served by support of pycurl? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From jimd at vega.starshine.org Tue Mar 26 00:55:26 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 26 Mar 2002 05:55:26 GMT Subject: personel CDDB References: <4a7fde99.0203251840.2aafdf58@posting.google.com> Message-ID: In article <4a7fde99.0203251840.2aafdf58 at posting.google.com>, Ryan wrote: > I'm thinking about writting a personel CD database that links into RDB > so you can put in a cd and have python link to crdb and make a > personel database to keep track of your cd's (and maybe rip mp3s from > it and store them in the database to) I'm wondering if many people > would have an interest in this so I will know whether to just write it > so it works, or write it the right way, (ie. pure python and a gui > using anydb). If it's just for me it won't be nearly as robust and > will use a lot of win32 extensions (for speed). If there is enough > interest I may even post to source-forge. > Thx > Ryan I would think that at tool to query online CDDB and post to a local PostgreSQL or MySQL (or any dbm) database would be useful. I'm not so sure about the idea of posting BLOBs (binary large objects) into the db, but that would be almost trivial as an option (in supported DBMSes). From david at goodgirldesigns.com Mon Mar 25 06:03:43 2002 From: david at goodgirldesigns.com (dc) Date: 25 Mar 2002 03:03:43 -0800 Subject: zope/python devloper needed! Message-ID: <7085ec43.0203250303.2eea14f2@posting.google.com> We are looking for a zope/python developer to create a custom application using zope/mysql and having it synchronize with Raiser's Edge DB. please only submit inquiries up until 3/29/02. No phone calls or recruiters. Thank you. From duncan at NOSPAMrcp.co.uk Wed Mar 20 03:58:39 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 20 Mar 2002 08:58:39 +0000 (UTC) Subject: NameError assigning to class created in a function References: Message-ID: [posted and mailed] Andrew Bennetts wrote in news:mailman.1016603731.25922.python-list at python.org: > So, it seems that you can't assign to a variable in a class if it has the > same name as the variable you are assigning from. Except that it works > outside a function: > It seems to be a problem with nested scopes. If a variable is assigned to anywhere in the class statement, then the local value is used after the assignment, but the global value is used before. If a variable is not assigned to then the nested scope rules apply. def f(y): class Private: x = y y = 42 return Private f(33) Comment out the assignment to y, and this works (Private.x gets 33 from y in nested scope), with the assignment to y in place this raises NameError. So far this is pretty much what I would have expected: you can use the value of y from the nested scope only if y is not a local variable in the class scope (although I would have expected an UnboundLocalError rather than a NameError). But, if you assign a global variable y=77 then Private.x gets 77 which definitely seems wrong. I knew before that nested scopes didn't seem to work quite the way I expected with classes, but this definitely looks like a bug. Either classes should not do nested scopes at all, or they should do them consistently with functions. -- 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 skip at pobox.com Mon Mar 25 20:16:28 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 25 Mar 2002 19:16:28 -0600 Subject: Streaming XML-RPC? In-Reply-To: <3C9FAF96.5DE9A0@bgb-consulting.com> References: <3C9F51EE.5000203@jerf.org> <3C9FAF96.5DE9A0@bgb-consulting.com> Message-ID: <15519.52204.972477.680449@12-248-41-177.client.attbi.com> Don> Are there any decent (finished/tested) Jabber libraries for Python? Don't know what its status is, but there is jabberpy: http://jabberpy.sourceforge.net/ -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From tim.one at comcast.net Mon Mar 25 13:15:00 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 25 Mar 2002 13:15:00 -0500 Subject: Random... In-Reply-To: Message-ID: [FREDRIK HULDTGREN] > I want to generate random numbers, very large random numbers. If I use > randrange() I get an out of bounds error since it only supports numbers > up to (2**31)-1. However, I can use uniform(), but then I get the number > returned in 7.9655120654553743e+018 or something simaler, and I would > rather have it in a "L" format(796551206545537430183218312890381031L). > How do I do this? You don't: you're looking for a miracle. A uniform() has no more than 53 significant bits (the limit of a Python float on most boxes), and the underlying Wichmann-Hill generator can't make more than about 45 of those even arguably "random". You can't magically increase the amount of available randomness via multiplying by a large integer. So you need a different approach. Here's one: http://www.faqts.com/knowledge_base/view.phtml/aid/4406/fid/546 From cfelling at iae.nl Sat Mar 30 18:12:03 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 31 Mar 2002 00:12:03 +0100 Subject: PEP 285: Adding a bool type References: Message-ID: Guido van Rossum wrote: ... > I'm particularly interested in hearing your opinion about the > following three issues: As you seem more interested in votes this time around then in arguments:) I'll try to restrict my self to yes and no anwsers. > 1) Should this PEP be accepted at all. yes (I always missed it) > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) str(True) == "True" (more readable at the interpreter prompt) > 3) Should the constants be called 'True' and 'False' definitely 'True' and 'False' > Minor additional issues: > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 no. The first time I came across "days + isleap(year)" I found it higly puzzling (I was raised with strict typing), but now that I'm used to it I wouldn't want to loose it. > 5) Should operator.truth(x) return an int or a bool. Tim Peters assuming its result can be used in integer expressions, it should return a canonical truth value, so bool (preferably called 'truth') -- groetjes, carel From olc at ninti.com Fri Mar 29 19:21:50 2002 From: olc at ninti.com (Michael Hall) Date: Sat, 30 Mar 2002 09:51:50 +0930 (CST) Subject: Function problem Message-ID: G'day: Can someone tell me why this function stops printing after looping through the
    "> The idea, which I am still not sold on, goes a bit like this: The first bit of template attaches an attribute name and value to an attribute id. This attribute association would be stored in the execution context so you could define values in your Python code if you wished. Albatross tags would then retrieve values from the association by using the same id attribute. This would allow Albatross templates to be much more flexible. Consider the tag. At the moment you have to staticly decide the name of the iterator. This means that you cannot reuse a bunch of template code which paginated a sequence in a macro since you would be using the same iterator for multiple sequences. With the above you could do this (not really a good example): blah blah spam eggs The functionality would require an extensive reworking of the tags code. There are some advantages to the approach but I am still a bit concerned that it is too obscure. Andrew has since mentioned changing the way that the we name the Albatross processed attributes to make them more functional and consistent. Something like: I am starting to think that this would be an excellent idea. Ian> Of course there's the ZPT approach, which isn't bad, but then you Ian> might as well use ZPT. But I guess there's no reason you can't Ian> use something like ZPT just for changing attributes, like: Ian> I have a few concerns about ZPT. You are forced to embed programming logic which is used to dynamically alter the presentation of the interface directly inside the presentation elements. I have a feeling that this makes the whole template unduly fragile and resistant to change. The idea that an HTML developer who does not understand ZPT will be able to ignore the ZPT attributes and just change the interface in isolation is a fantasy. The ZPT attributes define an executable program - their correct placement is critical to the functioning of the template. Note that the same is true of Albatross tags, but you can change the HTML in isolation to the Albatross tags. Ian> And then skip all the looping and such that ZPT does with Ian> attributes. You'd still have the worry about generating CSS and Ian> Javascript, though. Dave mentioned performance... doing a full Ian> XML parse is performance-intensive, but you could fake it for Ian> this particular case -- you don't need to find the
    tag Ian> or anything, you could probably do it just with regexes. Ian> I still think it's so much easier to use [], and make the system Ian> orthogonal to XML or any other medium you might want to generate. Ian> I think it actually gives you better tool support as well. The [] characters do not make things much more pretty IMO. You sill end up with things like this:
    Something which would dynamically assign attributes to tags would look much nicer. The whole goal of Albatross is to place as little logic as is possible in the templating system. All real programming should be in Python. Having said that, I recognise that the templating system is far from perfect. If it was an easy problem, we would all be using the same templating system which was a standard Python module. - Dave -- http://www.object-craft.com.au From martin at v.loewis.de Wed Mar 27 15:03:14 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Mar 2002 21:03:14 +0100 Subject: Text to HTML algorithm. References: Message-ID: Gustavo Cordova writes: > Does anybody have an implementation, or know of one, > to format plain text into HTML? Sure. If it does not contain markup, print "
    %s
    " % plaintext will fulfill this requirement. > I need to preserve a minimum of structure, such as > wrapping

    ...

    around paragraphs separated by > at least one empty line and detecting unnumbered > lists (at least). If you think you need a pre-existing library, you may want to try HTMLGen. It knows much about HTML, but little about plain text. Regards, Martin From bkelley at wi.mit.edu Thu Mar 28 15:13:17 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Thu, 28 Mar 2002 15:13:17 -0500 Subject: vwait in Python? References: <1017315455.8141.1.camel@lewis> Message-ID: <3CA3795D.1020200@wi.mit.edu> You might want to try a different pattern. A simple observer pattern might do what you want. Essentially if you can break up your control logic into functions so that after variable Y's value has been changed you want to call function X you might find that most of your problems become easier. Here is an example of a new IntVar widget that uses an observer pattern to control program flow. Note that this sets a variable that broadcasts to all relevant "listeners" that's its value has been changed. The variable's value is set by the widget but could be set by anything else as well. For example, if you have some other process that changes the observable it could notify the widget to update to the new value as well. This is left as an exercise to the reader :) from Tkinter import * import Dialog class Observable: def __init__(self, data): self.data = None self.callbacks = [] def addCallback(self, func): """(function)-> add listeners""" self.callbacks.append(func) def set(self, data): """(data)->set the variable to be equal to data and call all listeners""" self.data = data for callback in self.callbacks: callback(data) class ObservableIntVar(Frame): def __init__(self, master, **kw): apply(Frame.__init__, (self, master), kw) self._var = IntVar() b = Checkbutton(master, variable=self._var, command=self._setVar) b.pack() self._observable = Observable(self._var.get()) def _setVar(self): self._observable.set(self._var.get()) Dialog.Dialog(self, title="Hello", text="I'm set to %s"%self._var.get(), bitmap=Dialog.DIALOG_ICON, default=0, strings=('OK',)) def add(self, callback): """(callback)->add a callback function that should be notified when the value of the IntVar changes""" self._observable.addCallback(callback) if __name__ == "__main__": tk = Tk() ob = ObservableIntVar(tk) ob.pack() def callback(data): print "callback called with data =", data ob.add(callback) mainloop() From phr-n2002a at nightsong.com Fri Mar 8 08:53:11 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 08 Mar 2002 05:53:11 -0800 Subject: [ANN] istring 1.0.1 released; announce list created References: <3C88BEBD.20901@stroeder.com> Message-ID: <7xpu2fxj20.fsf@ruckus.brouhaha.com> Michael Str?der writes: > I have to admit that I'm scared of having to deal with yet another > special char $ which would need quoting. Since the istring approach > does not add any more value to Python the developers in favor of this > should use the istring module. But it should not be added to standard > Python. Of course it adds more value to Python. If you've programmed in Perl and then switched to Python, you're probably delighted like me to be free of a lot of Perl ugliness, but interpolation is something that I sorely miss. It's better to do it as a language extension than as a library, because that way the compiler can parse the interpolated strings and emit bytecode for them directly, rather than having to do some messy runtime parsing. If it has to be done as a library, it should at least be a C extension rather than pure Python (I don't know which the istring module is). IMO, Python's "format_string % varlist" hack is excessively cute and can be done without. I'd rather have interpolation in the language and a printf-like function in the library. From just at xs4all.nl Sat Mar 16 02:32:37 2002 From: just at xs4all.nl (Just van Rossum) Date: Sat, 16 Mar 2002 08:32:37 +0100 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: In article , Graham Ashton wrote: > On Fri, 15 Mar 2002 18:49:09 +0000, Skip Montanaro wrote: > > >>>>>> "Joe" == Joe Grossberg writes: > > > > Joe> Is there any effective difference between the two? > > > > Nope. > > I read somewhere (don't ask me where) that != is preferred. But it's not generally accepted. I for one prefer <>, if only because I learned Pascal before C... Too bad you can't google on <> or !=, but it has been discussed many times in the past. Just From tim at worthy.demon.co.uk Fri Mar 15 14:09:56 2002 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Fri, 15 Mar 2002 19:09:56 GMT Subject: Access to shared directories References: Message-ID: In message "Fabrizio" wrote: > I just want to read a .txt file that I have in a shared directory on > another PC which is part of a WindowsNT/98 LAN. > > What path should I use in order to read that file from my PC ? \\pcname\sharename\file.txt -- ___ |im ---- ARM Powered ---- From pearu at cens.ioc.ee Fri Mar 29 17:13:48 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sat, 30 Mar 2002 00:13:48 +0200 Subject: Anyone need a program written? In-Reply-To: References: Message-ID: On Fri, 29 Mar 2002 rasmussn at lanl.gov wrote: > How about a Python substitute for make. SCons seems to address this field already http://www.scons.org/ BTW, there are lots of Python based projects going on, you may also consider joining to some of these projects. Pearu From paul1brian at yahoo.com Mon Mar 4 05:42:17 2002 From: paul1brian at yahoo.com (Paul Brian) Date: Mon, 4 Mar 2002 10:42:17 -0000 Subject: Gentle reminder for Python UK Conference, April 4 & 5. Message-ID: <1015238517.16564.0.nnrp-01.c1c3e191@news.demon.co.uk> Dear all, This is a gentle reminder for those Python enthusiasts in the UK that the 2nd Python UK Conference will take place on April the 4th and 5th near Stratford upon Avon. The two day conference is packed full of talks on cutting edge applications of Python, with time to meet, socialise and even discuss code, life and love with fellow Pythonistas. You even get access to the full ACCU conference, attended by luminaries such as Bjarne Stroustrup. If that does not convince you, try advice from Mrs Doyle (Father Ted and the Inland Revenue) : "Ah, go on, go on, go on, go on, go on, go on, go on, go on" You can register online at www.accuconference.co.uk , and further details are available there too. Please note that Python attendees should pay the daily rate for the conference (?130 /day for ACCU members, ?155 else) for the one or two days they choose to attend. Yours Paul Brian From martin at v.loewis.de Fri Mar 1 15:55:41 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 21:55:41 +0100 Subject: importing C libraries, Solaris2.6, gcc2.95 :( References: <17214de2.0203010819.240c00d3@posting.google.com> Message-ID: rsalz at zolera.com (Rich Salz) writes: > I have a Solaris 2.6 machine, gcc 2.95.3 installed in /usr/local; > /usr/local/bin is in my $PATH ; /usr/ccs/bin is not in my $PATH. I > have python 2.1.1 sources; I did "./configure" with no flags. > Attempting to import any library that includes a C shared library > fails with the same backtrace: I think I've seen this before, but I can't find it, and I don't think it was resolved the last time. It sounds like a compiler/linker bug to me: The argument to SetItemString which is out of bounds *literally* comes from the methods array. Please try inspecting methods in the the gdb stack trace (up;up;up;up;p methods[0] - or some such). If this is still an invalid string, try finding out whether the compiler correctly passed address of _tkinter.c:moduleMethods. If that is the case, most likely the static or dynamic linker has messed up with relocations. What linker are you using? You may want to apply the latest patch cluster. Regards, Martin From philh at comuno.freeserve.co.uk Mon Mar 11 07:48:52 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 11 Mar 2002 12:48:52 +0000 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: On Mon, 11 Mar 2002 12:18:11 +1100, Patrick wrote: > >If two people of equal ability started programming today, one learning C and >Python, the other learning C++, I'd wager that the C/Python guy will be >running conceptual rings around the C++ guy 12 months from now. Power in a >language is all about being able to express your most complex thoughts with >as few arbitrary difficulties as possible. Some languages help. Some hinder. This is all true. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From usenet at thinkspot.net Sun Mar 17 12:36:10 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 09:36:10 -0800 Subject: Where to download bugfix for email Module? References: Message-ID: On Sun, 17 Mar 2002 14:43:02 +0300, Oleg Broytmann wrote in comp.lang.python in article : > On Sun, Mar 17, 2002 at 12:35:43AM -0800, Sheila King wrote: > > However, I can't figure out where this latest code is or how to download > > it. > > CVSROOT=":pserver:anonymous at cvs.mimelib.sourceforge.net:/cvsroot/mimelib" > export CVSROOT > > cvs login > cvs checkout mimelib > > New code is in mimelib/email directory. If you still will have troubles, > I can tar and send my copy to you. Thanks, Oleg. I've downloaded WinCVS and am going to try to learn this CVS thing and get the code that way. However, I have two concerns, and this is not just directed at Oleg, but anyone who has some experience on this matter: (1) stability. Can I expect this latest code to be stable? Somehow I would think that would be questionable with late releases? (2) distribution. If I want to distribute code that I'm developing, and I use the latest CVS releases to develop my code, such that my code relies on these CVS releases, how do I distribute code to others who are running the standard 2.2 install? Also, I noticed last night, when looking over the mimelib/email CVS files (browsing), that there are a LOT more libraries/files and that the dependencies have changed. For example, the import statements in email.Message.py are completely different between the latest CVS version and the standard 2.2 version. If I grab these files and put them on my computer, should I just rename/backup the old version and then drop these new ones in place? Should I try to somehow (through clever renaming) make both available to my Python2.2 installation? I'm just so uncertain as to how to proceed. (Think "CVS newbie" here...) But I need to get around this 'int has no attribute lower' error. :( -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From brueckd at tbye.com Fri Mar 1 12:21:04 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 1 Mar 2002 09:21:04 -0800 (PST) Subject: Swapping out sys.stdout globally In-Reply-To: <20020301093135467-0500@braeburn.na.sas.com> Message-ID: On 1 Mar 2002, Kevin Smith wrote: > I am working on a command-line utility written in Python which daemonizes > itself. In the process of daemonizing, sys.stdout and sys.stderr are > redirected to now file-like objects as follows: > > sys.stdout = NewFile() > sys.stderr = NewFile() > > However, I have some logging routines in a separate package that already > have their own references to sys.stdout and sys.stderr which are > unaffected by this. Is there a way to chonge where sys.stdout and > sys.stderr print their output to and have this change affect all existing > references? Nope - there's nothing magical about sys.stdout/err - they're just variables that reference objects. By rebinding them they lose knowledge of what they referenced previously, just as with any other variable. You need to rebind stdout/err as soon as your program starts, before any other modules load. Then as the others load they'll refer to your replacement objects. -Dave From lac at strakt.com Tue Mar 26 09:51:56 2002 From: lac at strakt.com (Laura Creighton) Date: Tue, 26 Mar 2002 15:51:56 +0100 Subject: list comprehension question In-Reply-To: Message from Peter Hansen of "Mon, 25 Mar 2002 20:02:37 EST." <3C9FC8AD.CD82FEA0@engcorp.com> References: <20020325113323.A26319@glacier.arctrix.com> <3C9FC8AD.CD82FEA0@engcorp.com> Message-ID: <200203261452.g2QEpurq012407@ratthing-b246.strakt.com> >Peter Hansen: > > Neil > > > > PS. tell the bot I'm sorry I doubted the correctness of his code > > If it's a bot, you don't have to apologize. Bots feel no emotion. > > And you're safe, too -- remember the First Law. > > -objectifying-tim-ly yr's, > Peter Tisk tisk. Only half of the apologising you do for the other person. The other half you do for yourself. Laura Creighton From sandskyfly at hotmail.com Sun Mar 10 04:36:22 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 10 Mar 2002 01:36:22 -0800 Subject: python and haskell for fun Message-ID: Hi folks, I've just picked up Simon Peyton Jones' book on haskell: "The craft of functional programming", and I've just discovered that there's a nice aesthetic to haskell that somehow reminds me of python: beautiful syntax, significant whitespace, a wonderful obsession with simplicity, clarity and readability... Now, just for fun, I'm thinking how it would be splendid to use these two languages together, and make them beget a pretty monster so to speak. Does anyone have any tips, experiences, or whatever along these lines? regards, Sandy From duncan at NOSPAMrcp.co.uk Wed Mar 27 07:17:57 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 27 Mar 2002 12:17:57 +0000 (UTC) Subject: Python UK - April 4th and 5th References: Message-ID: "Tony J Ibbs (Tibs)" wrote in news:mailman.1017226183.22623.python-list at python.org: > .. [1] and I get to stay with friends, which is an additional > bonus - Duncan, do I have to promise not to talk Python > at home? Judy says that if her eyes glaze over you are talking too much Python (or perhaps I am). -- 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 gtalvola at attbi.com Sun Mar 31 20:00:40 2002 From: gtalvola at attbi.com (Geoffrey Talvola) Date: Sun, 31 Mar 2002 20:00:40 -0500 Subject: Webware for Python 0.7 Message-ID: <20020401005602.IGOR1214.rwcrmhc54.attbi.com@there> Webware for Python 0.7 is now available! Webware for Python is a suite of software components for developing object-oriented, web-based applications. The suite uses well known design patterns and includes popular features such as: * A fast, easy-to-use application server * Servlets * Python Server Pages (PSP) * Object-relational mapper * Task scheduler * User manager with authentication * CGI wrapper Key goals of the project include: * Python-oriented. * Object-oriented. * An expansive suite of components and features to cover common needs of web developers. * Modular architecture where components can be used together or independently. * Excellent documentation and numerous examples. * Open source development and community (Python-style license). For more information or to download Webware 0.7 see http://webware.sourceforge.net ------------------------------------------------ Changes since version 0.6.1: Python 2.0 or higher is now required. Components of Webware no longer have independent version numbers. There is just an overall Webware version number. Each component still has an independent status of alpha, beta, etc. New option "gobblewhitespace" in Python Server Pages lets you write if/else and try/except statements in a more natural manner. New option "formatter" in Python Server Pages lets you specify an alternate formatter function to use instead of str(). New feature in MiddleKit: model inheritance. See the user's guide for details. Improvements to the CSV functionality in MiscUtils. WebKit features: - PickleRPC as a more Pythonic alternative to XML-RPC - SessionPrefix setting that can be used with mod_rewrite for easy load balancing with session affinity - improved exception reporting hooks - EmailErrorReportAsAttachment setting can be used to send HTML error pages as attachments - minor bug fixes Major speed improvements in MiddleKit. -- - Geoff Talvola gtalvola at attbi.com From neal at metaslash.com Wed Mar 20 15:06:47 2002 From: neal at metaslash.com (Neal Norwitz) Date: Wed, 20 Mar 2002 15:06:47 -0500 Subject: ANN: PyChecker v0.8.10 released Message-ID: <3C98EBD7.90E34BF7@metaslash.com> A new version of PyChecker is available for your hacking pleasure. PyChecker is a tool for finding bugs in Python source code. It finds problems that are typically caught by a compiler for less dynamic languages, like C and C++. It is similar to lint. Comments, criticisms, new ideas, and other feedback is welcome. NOTE: This is the last release I plan to support Python 1.5.2. Changes from 0.8.9 to 0.8.10: * Add --unpack option to warn when unpacking a non-sequence * Add --unpacklen option to warn when unpacking sequence of wrong size * Add --changetypes option to warn when setting a variable to different types * Add --stringiter option to warn when iterating over a string * Add --input option to warn when using input() * Fix crash with checking properties or deriving from objects (2.2 only) * Fix crash with nested scopes and lambdas * Fix spurious warnings for constant conditionals when using ('%s' % value) * Fix spurious warnings for unused identifiers caused by from XXX import * * Add more information when module cannot be imported * Fix spurious warnings for implicit returns when using while 1: * Fix spurious warnings for implicit returns when using try/finally: * Fix spurious warning with globals that start w/__ * Fix spurious warnings for modifying default arguments when calling {}.get(), {}.has_key(), [].index(), [].count(), etc. * Fix spurious warnings in Python 1.5.2 when using from/import PyChecker is available on Source Forge: Web page: http://pychecker.sourceforge.net/ Project page: http://sourceforge.net/projects/pychecker/ Mailling List: pychecker-list at lists.sourceforge.net Neal -- pychecker-list at lists.sourceforge.net From thoa0025 at mail.usyd.edu.au Thu Mar 28 17:02:14 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Thu, 28 Mar 2002 22:02:14 GMT Subject: mutliple search and replace References: Message-ID: hey Gustavo, actually i wished to do the replacement in one sweep and occuring in any order.. to avoid problems.. is it easy? cheers "Gustavo Cordova" wrote in message news:mailman.1017263863.2060.python-list at python.org... > > > > Greetings, > > > > Suppose i have a map (or two lists). is it possible to make a > > sweep through > > a string to find all occurances of key's in the map then > > replace them all in > > one sweep? > > > > cheers > > trung > > > > Sure, only that there's not a builtin function that does that, > but it sounds easy enough to make it: > > def ReplaceLots(String, RDict): > "Replace all occurrences of all keys in RDict inside String" > for k in RDict: > String = String.replace(k, RDict[k]) > return String > > Simple, eh? Yeah, that's Python for ya. :-) > > -gustavo > From gmcm at hypernet.com Fri Mar 22 09:08:24 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 22 Mar 2002 14:08:24 GMT Subject: Why do Windows sockets break after exactly 4 minutes? References: Message-ID: Geoffrey Talvola wrote: > I've noticed that Windows sockets seem to close all by themselves if > there is no activity for 4 minutes. Does anyone know why? Is it > possible to control this behavior? Just a link to some documentation > of this behavior would be greatly appreciated. > > I don't think the same thing happens on Linux, or maybe it does but the > timeout is longer than 4 minutes there. > > I've attached a set of 2 test scripts that provoke the behavior. Start > up server.py first, then client.py, then wait 4 minutes. Does it help to note that if you change: > time.sleep(250) to time.sleep(15), then the socket closes after 15 seconds? Your client does a shutdown(1) after sending some data. The shutdown(1) causes the server to fall out of the receive loop. It then sleeps for however long specified, sends some data and closes the socket. In other words, the behavior is exactly what you asked for, and Windows' socket implementation has nothing to do with it. -- Gordon http://www.mcmillan-inc.com/ From huaiyu at gauss.almadan.ibm.com Fri Mar 22 15:12:23 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 22 Mar 2002 20:12:23 +0000 (UTC) Subject: Puzzling difference between module and package.module Message-ID: A mystery for everyone's curiosity! (It might even be a Python bug.) I hope someone can recognize what would cause import dir2.file1 # in dir1 import file1 # in dir1/dir2 to behave quite differently in the following directory structure: dir1 dir2 __init__.py (empty file) file1.py Here's a test program that uses the Gnuplot package: ------------------- test_plot.py ------------ x = [range(5), range(1,6)] from Gnuplot import Gnuplot g = Gnuplot() g.plot(x) from time import sleep sleep(.1) print 'after sleep' --------------------------------------------- It is OK to run 'import test_plot' in dir2. But running 'import dir2.test_plot' in dir1 generates an error: after sleep tmpfile /tmp/@2065.0 None Exception exceptions.AttributeError: "'NoneType' object has no attribute 'system'" in > ignored When trying in an interpreter, the error comes up while exiting the interpreter. The relevant sections are (I've added some diagnostic statements) -------------------- Gnuplot/PlotItems.py -------------------- import os, string, tempfile class TempFile(AnyFile): def __del__(self): try: os.unlink(self.filename) except: print 'tmpfile', self.filename, `os`, self os.system('ls -l %s' % self.filename) raise SystemExit --------------------------------------------------------------- So it appears that Gnuplot.PlotItems.os somehow becomes None. How does that happen? I can understand that if the module attribute simply dissappears, that would be caused by a mismatched order of clean up. But how is it changed to None? It appears that this bug first appeared in Python 2.2: $ echo import testdir.test_plot | python2.0 after sleep $ echo import testdir.test_plot | python2.1 after sleep $ echo import testdir.test_plot | python2.2 after sleep Exception exceptions.AttributeError: "'NoneType' object has no attribute 'unlink'" in > ignored $ echo import testdir.test_plot | python2.3 after sleep tmpfile /tmp/@2252.0 None Exception exceptions.AttributeError: "'NoneType' object has no attribute 'system'" in > ignored The versions used are: Python 2.0 (#1, Mar 1 2001, 02:42:21) [GCC 2.95.2 19991024 (release)] on linux2 Python 2.1 (#1, Oct 2 2001, 15:35:43) [GCC 2.95.2 19991024 (release)] on linux2 Python 2.2 (#4, Mar 6 2002, 14:33:41) [GCC 2.95.2 19991024 (release)] on linux2 Python 2.3a0 (#5, Mar 20 2002, 12:38:28) [GCC 2.95.3 20010315 (SuSE)] on linux2 Should I file a bug report? Huaiyu From usenet at thinkspot.net Sun Mar 10 23:03:33 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 10 Mar 2002 20:03:33 -0800 Subject: New Member References: Message-ID: On Mon, 11 Mar 2002 02:22:58 -0000, "j45729" wrote in comp.lang.python in article : > Hi i'd like to introduce myself. My name is Jon. I think Python is > one of the coolest scripting languages! I'm a new student and i'm > enjoying learning Python. I hope to use Python in many applications > for the web and for problem solving and anything else. I think it > will be fun! I'm so glad i have all of you here for my support! > what a great plus in learning this language is having so many who are > interested in the same language. Welcome Jon, It is always nice to hear another, enthusiastic response to Python. Welcome to the community! -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From bergeston at yahoo.fr Thu Mar 14 14:02:43 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Thu, 14 Mar 2002 20:02:43 +0100 Subject: Conditional Import References: Message-ID: "Aahz" wrote in message news:a6qr70$cg8$1 at panix1.panix.com... > In article , > Gustavo Cordova wrote: > > > > from exceptions import ImportError > > try: > > from codeop import CommandCompiler > > except ImportError: > > from MockCommandCompiler import CommandCompiler > > Exceptions are automatically imported; no need for the first line. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > The best way to get information on Usenet is not to ask a question, but > to post the wrong information. --Aahz ... and you just proved it :-) (I mean that "the best way to get information on Usenet ....") From logiplexsoftware at earthlink.net Thu Mar 28 19:17:31 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 28 Mar 2002 16:17:31 -0800 Subject: Exceptions and modules / namespaces question In-Reply-To: References: <1136f745.0203281521.76a1a62c@posting.google.com> Message-ID: <20020328161731.664c9cfe.logiplexsoftware@earthlink.net> On Thu, 28 Mar 2002 15:57:15 -0800 Emile van Sebille wrote: > Preston Landers > > The problem, in a nutshell, is that I can't seem to catch an exception > > in the same module it was defined in if the function that raised the > > exception is in a different module, because of naming issues. > > > > It seems to me that you have a __main__ vs module1 issue. When module2 > imports module1, it gets a new copy, not __main__. > > > -------module2.py: > > > > import module1 > > > > def raise_foo_exception(): > > raise module1.FooException("HELLO") > > > > -------module1.py: > > > > import exceptions, sys > > > > class FooException(exceptions.Exception): > > pass > > > > def main(): > > > > try: > > import module2 > > if you import module1 here > > > > module2.raise_foo_exception() > > except FooException, e: > > then except module1.FooException > > it may work. Better perhaps to define your exceptions in a separate > module and import it into both. I failed to notice that his main() function was also in module1 (replying without reading is a specialty of mine ;) Maybe this will make the namespace issue clearer except module2.module1.FooException, e: works, but it would obviously be cleaner if both the main program and module2 imported module1. /Then/ he could simply use module1.FooException. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From michael at dynamine.net Fri Mar 29 18:31:23 2002 From: michael at dynamine.net (Michael S. Fischer) Date: Fri, 29 Mar 2002 15:31:23 -0800 Subject: IOError on file close In-Reply-To: References: Message-ID: <20020329233122.GB10345@attrition.dynamine.net> On Fri, Mar 29, 2002 at 03:14:28PM -0800, Sean 'Shaleh' Perry wrote: > > That indeed appears to be the case, but it looks like a bug in the > > kernel to me. > > why? /proc/scsi/scsi is clearly marked 444 on my machine, not 644. It's ENOSYS, not EPERM. I'm running this script as root. Specifically, the code is here in the Linux kernel (2.4.17), in drivers/scsi/scsi.c: for (scd = HBA_ptr->host_queue; scd; scd = scd->next) { if ((scd->channel == channel && scd->id == id && scd->lun == lun)) { break; } } err = -ENOSYS; if (scd) goto out; /* We do not yet support unplugging */ -- Michael S. Fischer / michael at dynamine.net / +1 650-533-4684 Lead Hacketeer, Dynamine Consulting, Silicon Valley, CA From bokr at oz.net Sun Mar 10 20:06:48 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Mar 2002 01:06:48 GMT Subject: range Failure? References: <3C8B84B6.DB3F8E9A@sympatico.ca> <3C8BFB9C.1EF90FAB@engcorp.com> Message-ID: On Sun, 10 Mar 2002 19:34:36 -0500, Peter Hansen wrote: >Bengt Richter wrote: >> >> On Sun, 10 Mar 2002 11:07:18 -0500, "Colin J. Williams" wrote: >> [...] >> >It might say: >> > >> > range([start= 0,] stop[, step= 1]) >> >> Still, the two optional []'s are not valid in all combinations, >> (which is what you fix with your improved text ;-) >> so maybe it should say something like: >> >> range([start= 0,] stop) # where step defaults to 1, or >> range(start, stop [, step= 1]) > >Why not be very explicit, rather than fancy and confusing? >The above is an improvement over the original, but perhaps >this is better? > > range(stop) # start is 0, step is 1 > range(start, stop [, step=1]) > Yes, that is better. >Answering my own question: the first of the three is pretty bad. >The second one suffers from implying that Python can have optional >positional arguments which come before non-optional ones. The >third suffers from implying (perhaps?) that Python can have >overloaded methods. > >Since range() doesn't take keyword arguments, even my second >one above could be considered a little bit confusing, if you >think that implies you can say range(1, 6, step=2) which you >cannot. > I guess it's a matter of defining the grammar of usage documentation. Regards, Bengt Richter From cja at dds.nl Thu Mar 14 16:19:26 2002 From: cja at dds.nl (Chris Abraham) Date: Thu, 14 Mar 2002 16:19:26 -0500 Subject: Python/Zope App for Email Activist Alert (WALD) tool? Message-ID: Hi: I am building a web-based application that intends to accept membership (free) and each member will be alerted as to an event (generally Senate, House, White House, corporation) via an email message that can then me responded to via clicking back to a web site where you edit a form letter and then submit this protest to be delivered to its intended politician. Like Working Asset's Alert Network? Is there an open souce web application like this? Zope sounds perfect for this! Whether attached to the ZODB or to MySQL. Cheers & Thanks! Chris From Van at Lindbergs.org Sun Mar 24 11:19:23 2002 From: Van at Lindbergs.org (VanL) Date: Sun, 24 Mar 2002 09:19:23 -0700 Subject: Embedding help Message-ID: <3C9DFC8B.5070700@Lindbergs.org> Hello, I'm trying to embed python in a C program. I already have the libraries, header files, linker options, etc worked out -- I can compile and run a program that embeds a python module both with the python/C api and with Mark Lutz's ppembed API. I can also move values between python and C. The problem is that I'm not sure how to maintain state in the python class I'm using. Ideally, I would only like to expose four functions to C: (called once) setup(int type) This would initialize python and a python class with the passed-in value (Used internally by the python class). This python class would also import other modules (both builtin and custom; the custom ones would be pure python) (called repeatedly) update(int x, int y, int z) This would update state within the python class instance (called repeatedly) getPt() This would fetch some variables from the python class instance, put them into a struct, and return the struct (called once) cleanup() Self explanatory. My problem is the following: How do I keep the class instance around so that I can maintain state? The getPt function would return variables that in part are functions of previous inputs, not just the current input. Please help! It would be greatly appreciated. Thanks, Van From ykingma at accessforall.nl Mon Mar 4 14:27:19 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Mon, 04 Mar 2002 20:27:19 +0100 Subject: Can Python do this? References: Message-ID: <3C83CA8D.C12A4F76@accessforall.nl> Robert Oschler wrote: > > Hello, Python newbie here. > > Let's say I'd like to build a method name into a string variable (e.g. > "FuncCall" + "1" to attempt to call "FuncCall1"). Can I then call that > method by somehow having the interpreter evaluate the string variable into a > call to the desired method? (I know this is usually done in a language like > Prolog or Lisp but I'm hoping Python can do it too.) Although you'd probably better use a dictionary of functions, you might try: result = eval("FuncCall" + "1" + "()") or: function = globals()["FuncCall" + "1"] result = function() or: import sys function = getattr(sys.modules[__name__], "FuncCall" + "1") result = function() In case you need a variable number of arguments, have a look at apply: theArgs = (1,2,3) result = apply(function, theArgs) Have fun. Python can be quite Lispy. Ype From rjones at ekit-inc.com Wed Mar 20 21:11:00 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 21 Mar 2002 13:11:00 +1100 Subject: ANN: Logging Module v0.4 released In-Reply-To: <2e37dc1.0203201754.50a15e80@posting.google.com> References: <2e37dc1.0203201754.50a15e80@posting.google.com> Message-ID: <200203210211.CAA14633@crown.off.ekorp.com> On Thu, 21 Mar 2002 12:54, Vinay Sajip wrote: > A new version of the proposed Python standard logging module (as per > PEP 282) has been released. You can get all the information from Having looked at the excellent work being done here, I wonder what's happening at the other end of the pipeline. That is, what's listening for the events that the logger is generating? Has anyone got any plans to write a logging sink for the other end? The sink would perform the following duties: - accept events from the logging module via all the logging module's handlers - present a display of the events to a user, either graphically or textually (the most basic of these would resemble the UNIX tail -f) - redistribution of events to other targets - filter incoming events, possibly aggregating, possibly dropping - have state which would be affected by the filters and may cause new events to be generated (ie. escalation) Anyone think this is a good idea? Richard From mwh at python.net Thu Mar 7 07:26:39 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Mar 2002 12:26:39 GMT Subject: PEP 276 -- What else could iter(5) mean? References: <6qpu2gzktu.fsf@abnoba.intevation.de> Message-ID: Just van Rossum writes: > I don't want any of these, but then again, I don't want "for i in 4" > either. I think it's an awful idea. Well, so long as your brother thinks the same, those of us in the "anti" camp don't have to worry, right? At least, that's what I've been hoping. Cheers, M. -- MARVIN: Oh dear, I think you'll find reality's on the blink again. -- The Hitch-Hikers Guide to the Galaxy, Episode 12 From phd at phd.pp.ru Mon Mar 18 11:47:26 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 18 Mar 2002 19:47:26 +0300 Subject: Still same bug even with email ver. 1.2 In-Reply-To: <7876a8ea.0203180837.4aaa1542@posting.google.com>; from woodsplitter@rocketmail.com on Mon, Mar 18, 2002 at 08:37:06AM -0800 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> Message-ID: <20020318194726.C7655@phd.pp.ru> On Mon, Mar 18, 2002 at 08:37:06AM -0800, David Rushby wrote: > Unfortunately, contrary to Oleg's assertion in c.l.py and Barry's in > his message added to the SF bug report, the CVS version of has *not* > been fixed. It was fixed for me :) That is, I had the problem, reported it, got back suggestion to use CVS version, checked it out - and hurray! - the bug was fixed... at least my program started to work. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jennyw at colorfulexpressions.com Sat Mar 16 14:44:07 2002 From: jennyw at colorfulexpressions.com (jennyw) Date: 16 Mar 2002 11:44:07 -0800 Subject: Sample Python programs to look at? Message-ID: <327f0ccd.0203161144.14299a4c@posting.google.com> Hi there! I was just wondering if someone could suggest sample Python programs to look at. Something complicated enough for me to get a feel for what programming something non-trivial would be like, but not so complex that it's overwhelming. In particular, I'm interested in database access (e.g. MySQL) and IMAP access, so if there's a smallish app. w/ source out there that someone could point me to, that'd be great! Thanks! Jen From jimd at vega.starshine.org Mon Mar 18 02:47:23 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 18 Mar 2002 07:47:23 GMT Subject: open() error ---- what am I missing? References: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com> Message-ID: In article , Eric Torstenson wrote: > OK I figured it out. It was a misleading error message. For those with > similar troubles I have listed an explanation (and I was being stupid...I > sort of figured as much) > It was a bad path name after all. It is a nested structure, where at one > point I left off one extra "\" (I'm using windows). I had looked at that > path a dozen times, somehow missing that single "\" down toward the > middle.... > "Oleg Broytmann" wrote in message > news:mailman.1015263607.7574.python-list at python.org... >> On Mon, Mar 04, 2002 at 11:31:46AM -0600, Eric Torstenson wrote: >>> self.fLog=open(filename, mode='w') >>> IOError: invalid argument: w >> Do you have the os module imported? Especially in the form >> "from os import *" or "from os import open"? >> Oleg. In other words it was another case of: r"use raw strings for filename literals under Win Python!" From fredrik at pythonware.com Wed Mar 13 03:04:53 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Mar 2002 08:04:53 GMT Subject: python -c cmd bug? References: Message-ID: "erik_w" wrote: > When I do > >python -c "import sys;print sys.argv" > ['-c'] > > (Python 2.1.2 on NT4) > > Is this the right behaviour? I would expect that the -c was an option > to the python interpreter, not to my script. http://www.python.org/doc/current/lib/module-sys.html "argv" "The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv has zero length." From aahz at pythoncraft.com Sat Mar 30 20:22:46 2002 From: aahz at pythoncraft.com (Aahz) Date: 30 Mar 2002 20:22:46 -0500 Subject: Subclass sadness (was Re: [Python-Dev] PEP 285: Adding a bool type) References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: In article , phil hunt wrote: >On 30 Mar 2002 11:04:13 -0500, Andrew Koenig wrote: >> >>I wonder if this is the circle-ellipse problem over again? > >What is the circle-ellipse problem? I'm not sure, but I'm going to guess for my own edification: Instead of circle/ellipse, it's slightly easier to talk about square/rectangle. In terms of standard geometry, a square is a subset of rectangles, such that height and width are identical. But in OO terms, it's a bit more complicated to inherit square from rectangle, because square has only side-length attribute where rectangle has two (height and width). So to create a class square that inherits from rectangle, you either have to write special code that ties height and width together or you have to delete at least one of the attributes (in which case any code expecting to work with rectangle fails). This kind of thing is what makes the Deitel book on Python really bad, because it doesn't give a clean picture of proper OOP (they make circle a subclass of point, and cylinder a subclass of circle, which is even a worse botch than trying to deal with circle/ellipse). In general, I think the evidence has shown that subclassing is an exercise fraught with danger and should be de-emphasized as a primary technique in OOP. I'm very glad that Python uses implicit protocols through magic methods for much of its OO processing; that makes it much easier to cut through the Gordian Knot. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From rxg218 at psu.edu Tue Mar 26 18:35:20 2002 From: rxg218 at psu.edu (Rajarshi Guha) Date: Tue, 26 Mar 2002 18:35:20 -0500 Subject: is'nt Tkinter a standard module? Message-ID: Hi, I'm trying to run Sketch on my Linux box (RH 7.2) with Python 1.5.2 However when I run sketch I get: Traceback (innermost last): File "/usr/local/bin/sketch", line 34, in ? Sketch.main.main() File "/usr/local/lib/sketch-0.6.13/Sketch/Base/main.py", line 142, in main Sketch.init_ui() File "/usr/local/lib/sketch-0.6.13/Sketch/__init__.py", line 187, in init_ui __import__(name) File "/usr/local/lib/sketch-0.6.13/Script/export_raster.py", line 46, in ? from Sketch.UI.sketchdlg import SKModal File "/usr/local/lib/sketch-0.6.13/Sketch/UI/sketchdlg.py", line 64, in ? from Tkinter import Toplevel, IntVar, Frame, Checkbutton, Label ImportError: No module named Tkinter Is'nt the Tkinter module supposed to be a standard part of Python? I installed Pythomn from RPM's - or am I supposed to get the Tkinter modules from somewhere else? -- ------------------------------------------------------------------- Rajarshi Guha | email: rajarshi at presidency.com 417 Davey Laboratory | web : http:// www.jijo.cjb.net Dept. Of Chemistry | ICQ : 123242928 Pennsylvania State University | AIM : LoverOfPanda ------------------------------------------------------------------- GPG Fingerprint: DCCB 4D1A 5A8B 2F5A B5F6 1F9E CDC4 5574 9017 AF2A Public Key : http://pgp.mit.edu/ ------------------------------------------------------------------- Paper or plastic? Not 'Not paper AND not plastic!!' -- Augustus DeMorgan in a grocery store From philh at comuno.freeserve.co.uk Thu Mar 14 11:08:32 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 14 Mar 2002 16:08:32 +0000 Subject: Good book on Python? References: Message-ID: On Thu, 14 Mar 2002 13:35:53 +0100, Federico Caboni wrote: > >I recently bought "Programming Python" by O'Really, Oh. Really? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From joonas at olen.to Fri Mar 1 17:28:02 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Sat, 02 Mar 2002 00:28:02 +0200 Subject: Securely passing arguments when opening a pipe to a program References: <3C7FE115.9832EE5C@olen.to> Message-ID: <3C800072.43CEC524@olen.to> Donn Cave wrote: > > Quoth Joonas Paalasmaa : > | I am using Gnokii to send SMS messages with Python. Gnokii is started > | with > | popen2.popen2 like this: > | > | gnokiiRead, gnokiiWrite = popen2.popen2("gnokii --sendsms %s" % > | phonenumber) > | gnokiiWrite.write(message) > | gnokiiWrite.close() > | response = gnokiiRead.read() > | gnokiiRead.close() > | > | The problem is that the phonenumber string is not safe; it can even be > | "000; rm -fR ~/*". How can I securely pass arguments when opening the > | pipe? > | Is there a way to pass the arguments like in os.execv. > > Yes! I hear this isn't documented as well as it could be, but > popen2 accepts either a string or a sequence, and in the latter > case the sequence is argv, like in os.execv. Thanks for the answer. I wonder why this very helpful feature isn't documented in os-module's documentation? From aseem at neurobs.com Thu Mar 21 12:09:38 2002 From: aseem at neurobs.com (A M) Date: 21 Mar 2002 09:09:38 -0800 Subject: HTTP session objects Message-ID: Hi All, Does python have the ability to r/w and use HTTP session objects like servlets. Is there a third party tool or API available to allow us to use it in Python. Any help or references to resources will be greatly appreciated. Thanks, A From frederic.giacometti at arakne.com Sun Mar 3 16:47:41 2002 From: frederic.giacometti at arakne.com (Frederic Giacometti) Date: Sun, 03 Mar 2002 21:47:41 GMT Subject: Stackless Platform Independence? References: <987e7uoo5v87fsjruq0ug6bff0vha5ear0@4ax.com> Message-ID: <3C829AA2.1B21E205@arakne.com> Aahz Maruch wrote: > In article , > Frederic Giacometti wrote: > > > >In addition to all the benefits that Christian has described so far, > >stackless python would make it possible to have a different OS > >multi-threading implementation for calling external C/C++ libraries; one > >that does not require interpreter lock operations. > > > > [...] > > > >Stackless just means that function calls executed by the bytecode are > >executed by a C function that returns immediately; thus disconnecting > >the C call stack from the virtual machine call stack. In current > >python, they are interleaved one-on-one; making it impossible to switch > >context within the VM unnless you do Christian's last 'non-portable' > >assembly language manipulation. > > How's that again? In the absence of pre-emptive thread scheduling, what > good is the immediate return from the C function? More than that, how > can you possibly call external libraries without the interpreter lock, > if those libraries have any access to Python variables? If they *don't* > have access to Python, how is that any different from just using the > macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS? Just reverse the paradigm: have the python VM run in a single thread, using stackless microthreads for python multithreading, and run the C calls in a pool of threads. This way: no lock is needed, since only one thread runs the VM, with the help of microthreads, and C calls run in other threads. FG From sandskyfly at hotmail.com Sat Mar 16 05:17:59 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 16 Mar 2002 02:17:59 -0800 Subject: psyco, jython, and python speed tests References: Message-ID: > Skip> How did you "psycoize pystone"? > > Sandy> Basically, I took the pystone included in Armin's psyco cvs > Sandy> distribution and simplified the main() function to get rid of the > Sandy> comparitive stuff. > > Modification of the source to pystone is a no-no, otherwise you're comparing > apples and oranges. Instead, try something like > > >>> import pystone > >>> pystone.main() > Pystone(1.1) time for 10000 passes = 2.51 > This machine benchmarks at 3984.06 pystones/second > >>> pystone.main() > Pystone(1.1) time for 10000 passes = 2.54 > This machine benchmarks at 3937.01 pystones/second > >>> pystone.main() > Pystone(1.1) time for 10000 passes = 2.53 > This machine benchmarks at 3952.57 pystones/second > >>> import psyco > >>> pystone.Proc0 = psyco.proxy(pystone.Proc0) > >>> pystone.Proc1 = psyco.proxy(pystone.Proc1) > >>> pystone.Proc8 = psyco.proxy(pystone.Proc8) > >>> pystone.main() > Pystone(1.1) time for 10000 passes = 0.58 > This machine benchmarks at 17241.4 pystones/second > >>> pystone.main() > Pystone(1.1) time for 10000 passes = 0.57 > This machine benchmarks at 17543.9 pystones/second > >>> pystone.main() > Pystone(1.1) time for 10000 passes = 0.58 > This machine benchmarks at 17241.4 pystones/second I agree that your method is cleaner. My modification, however, was actually an attempt to bring the version of pystone included in psyco cvs closer to the one in the standard python distro, all while retaining Armin's explicit use of psyco.proxy() Just for comparison here are the main functions of each version of psyco: Standard pystone (py22 distro) ------------------------------ def main(): benchtime, stones = pystones() print "Pystone(%s) time for %d passes = %g" % \ (__version__, LOOPS, benchtime) print "This machine benchmarks at %g pystones/second" % stones My modified psyco pystone (psyco cvs distro) ---------------------------------------------- def main(): print "Pystone(%s) time loops per second" % __version__ psy_time = pystones_psycho(LOOPS)[0] print "Psyco for %d passes %g %g" % (LOOPS, psy_time, mydiv(LOOPS, psy_time)) Unmodified psyco psytone (psyco cvs distro) ------------------------------------------- def main(): print "Pystone(%s) time loops per second" % __version__ py_time, = pystones_reg(LOOPS1+LOOPS) pyloop_time = py_time / (LOOPS1+LOOPS) print "regular Python for %d passes %g %g" % \ (LOOPS1+LOOPS, py_time, mydiv(1, pyloop_time)) psy_time1, psy_time = pystones_psycho(LOOPS1, LOOPS) print "Psyco for %d passes %g %g" % \ (LOOPS1, psy_time1, mydiv(LOOPS1, psy_time1)) print "Psyco for %d more passes %g %g" % \ (LOOPS, psy_time, mydiv(LOOPS, psy_time)) print "Total for %d passes %g %g" % \ (LOOPS1+LOOPS, psy_time1+psy_time, mydiv(LOOPS1+LOOPS, psy_time1+psy_time)) # invert the equation system: # psy_time1 = start_time + LOOPS1*loop_time # psy_time1+psy_time = start_time + (LOOPS1+LOOPS)*loop_time loop_time = psy_time/LOOPS start_time = psy_time1 - LOOPS1*loop_time print "Separated compilation/execution timings for %d passes" % \ (LOOPS1+LOOPS) print "Compilation (i.e. start-up) %g %g" % \ (start_time, mydiv(1, start_time)) print "Machine code execution %g %g" % \ (loop_time*(LOOPS1+LOOPS), mydiv(1, loop_time)) print print "Relative execution frequencies (iterations per second)" print "iterations Psyco Python Psyco is ... times faster" for d in range(8): n = 10**d psyco1 = mydiv(n, start_time+n*loop_time) print " %8d %g %g %.2f" % \ (n, psyco1, mydiv(1, pyloop_time), psyco1*pyloop_time) # invert the equation # start_time + c*loop_time = c*pyloop_time if pyloop_time <= loop_time: print "Psyco is always slower than regular Python." else: c = mydiv(start_time, pyloop_time - loop_time) print "Cut-off point: %.1f iterations" % c if start_time < 0.07: print "Note: start-up time is very low, the above figure is not reliable." print "You should consider running the same benchmark a large number of times" print "and taking the mean value for the cut-off point." -------- What's important in any case is that Psyco most definitely accelerates your code. I've actually tried it in a practical example using certain calculations with sparse matrices and it more than halved my execution time. regards, Sandy From mickey at tm.informatik.uni-frankfurt.de Sat Mar 2 08:53:31 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 2 Mar 2002 15:53:31 +0200 Subject: Possible to fake object type? Message-ID: <3c80e76b@nntp.server.uni-frankfurt.de> Hi, suppose I have the following code: class Dockable: "Represents a dockable window" def __init__( self, childclass, handlepos = gtk.POS_LEFT ): self.__dict__["_handlebox"] = gtk.HandleBox() self.__dict__["_child"] = childclass() self._handlebox.add( self._child ) def __getattr__( self, attr ): print "requesting attribut: '%s'" % attr return self.__dict__.get( attr, None ) \ or getattr( self._child, attr ) Dockable is composition of two classes trying to mimick the interface of the childclass and thus hiding that the childclass is embedded in a HandleBox. So far so good. The Problem: PyGTK (which I'm using) has typechecking. I cannot use my composition class instead of a - say gtk.HandleBox(), because I get, for instance: TypeError: child should be a GtkWidget It's no option to make Dockable a GtkWidget, for instance, by deriving it from gtk.HandleBox, because GtkWidget itself contains methods which I call on a Dockable but which should be reflected to the _child rather than be handled by the - then - baseclass GtkWidget. So: Is it possible to fake the type of a class or is it possible to magically override the method call "bouncing" to the base class ? Yours, :M: -- |----------------------------------------------------------------------------| | Dipl.-Inf. Michael 'Mickey' Lauer mickey at tm.informatik.uni-frankfurt.de | | Raum 10b - ++49 69 798 28358 Fachbereich Informatik und Biologie | |----------------------------------------------------------------------------| From ken at ineffable.com Fri Mar 8 11:48:41 2002 From: ken at ineffable.com (Ken Causey) Date: 08 Mar 2002 10:48:41 -0600 Subject: Handling bad tags with SGMLParser In-Reply-To: References: Message-ID: <1015606121.399.17.camel@temp> On Thu, 2002-03-07 at 11:12, Sean 'Shaleh' Perry wrote: > > > > The user of SGMLParser needs to be able to handle invalid tags. This > > handling may be complex or as simple as just ignoring it and asking > > SGMLParser to skip this tag and move along. As far as I can tell this > > is not an option. > > > > As a side note, the text error message thrown is particularly > > uninformation as it simply includes the first letter of the tag, in > > other words always '<'. > > > > match = special.match(rawdata, i) > if match: > if self.literal: > self.handle_data(rawdata[i]) > i = i+1 > continue > # This is some sort of declaration; in "HTML as > # deployed," this should only be the document type > # declaration (""). > k = self.parse_declaration(i) > if k < 0: break > i = k > continue > > is the offending code. 'special' is defined as re.compile(r']*>'). > > I see two options: > > 1) change the definition of special to a noop match. Something that is > relatively cheap but can never match. > > 2) write your own parse_declaration() method. > Well, I upgraded to Python2.2, which didn't exactly fix the problem, but changed the complexion somewhat. For now I decided to hack up sgmllib so that any SGMLParseError's on tags starting with Carel, Thanks for the explanation, below. Very interesting. Yes, I agree with your basic analysis that producing an iterator for an integer makes a lot more sense if one accepts integers as first-class objects. The fact that Python treats integers as well as everything else as first-class objects is one of the big reasons why I like Python so much. Jim =========================================================================== Carel Fellinger wrote >>>>>>>>>>>>>>>>> Jim, I think I finally solved the riddle. >From your first post on this subject I had this voice in the back of my head telling me: think objects. The post I'm responding to now reinforced that voice, so I finally gave in:) In 2.2 we happily see the type/class split healed. And one of the consequences of that is that we now *see* that integers have methods, we can even call them: >>> (1).__add__(2) 3 To you, comming from smalltalk, that's just how it's supposed to be, but to me it looks a little awkward. Probably because to me integers are a mathematical abstraction, and I don't see how it could know how to add. Addition is something that's not inherent to integers but a layer that's put on top of integers. I guess this just goes to show my ignorance on mathematical issues:( And now you're stretching this object oriented view of integers even further. You ask an integer to iterate or, if you like, to count. The funny thing however is that I don't have this reservation with strings:) Strings to me have always been a programmers construct, there are no character strings in the real world, but they sure come in handy in a program. When I made the switch to OO I saw that it was practical and sound to put the actions and the data together. So the same for strings. I ask a string whether it has uppercase chars, I ask it to split itself, to count itself (len). I'm even prepared to ask it to translate itself. No problem. I just never made that step for numbers. And I'm not alone in that. I remember from the 80's that there were heated discussions whether to go `all the way' and define integers to be objects or stop at the level of some primitive types when defining the object hierarchy. There were implementation issues but also filosofical and usability considerations. Some language designers choose to hide the object nature of integers from the programmers and provided a bunch of syntactic sugar solely to make number manipulation look more like ordinary math. To conclude, you propose to go `all the way' with treating integers as objects, and some of use haven't been exposed to such a thing long enough to either be blind for its pecularity or to finally appreciate its soundness. I think given enough time and exposure I can get to appreciate it, I don't know for the public in general. And though we hardly hear off it these days, Guido is aiming at `programming for everybody'. <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< From curtin at ubsw.com Tue Mar 12 12:35:56 2002 From: curtin at ubsw.com (craig curtin) Date: 12 Mar 2002 09:35:56 -0800 Subject: nonblocking i/o on windows? References: Message-ID: <4c7395cb.0203120935.3f9de2b9@posting.google.com> skip, how about: hnd=win32file.FindFirstChangeNotification(d , 0, winnt.FILE_NOTIFY_CHANGE_LAST_WRITE ) win32event.WaitForSingleObject(hnd, -1) craig Skip Montanaro wrote in message news:... > At the end of asyncore.py a non-blocking file_dispatcher class is defined > like so: > > class file_dispatcher (dispatcher): > def __init__ (self, fd): > dispatcher.__init__ (self) > self.connected = 1 > # set it to non-blocking mode > flags = fcntl.fcntl (fd, fcntl.F_GETFL, 0) > flags = flags | os.O_NONBLOCK > fcntl.fcntl (fd, fcntl.F_SETFL, flags) > self.set_file (fd) > > def set_file (self, fd): > self._fileno = fd > self.socket = file_wrapper (fd) > self.add_channel() > > Unfortunately, this uses fcntl, which is only available on Unix systems. Is > there something similar on Windows that will allow me to put a Python file > object in non-blocking mode? I thought perhaps there would be something > defined in msvcrt, but I didn't see anything in the lib ref manual or the > msvcrt source. > > Thx, From case at ironwater.com Tue Mar 19 18:41:02 2002 From: case at ironwater.com (Case Van Horsen) Date: Tue, 19 Mar 2002 15:41:02 -0800 Subject: Newbie: EOF Error when making arrays .fromfile References: <33e33d88.0203191243.454d39b8@posting.google.com> Message-ID: <3c97cc37$1@solnews.wv.mentorg.com> Why not use the original file? import urllib, string, array data=urllib.urlopen('http://dnijaguar.tripod.com/planet0.dat').readlines() datapoints=string.split(string.join(data)) coord=array.array('d', map(string.atof, datapoints)) cvh "Matt Strange" wrote in message news:33e33d88.0203191243.454d39b8 at posting.google.com... > hello all, i am very new to python and i'm using v2.2 on a Win98SE > machine. i needed to read in double-type data from an ASCII file > (http://dnijaguar.tripod.com/planet0.dat). this file contains 3000 > doubles separated by the tab("\t") value. after reading information > posted on this newsgroup, i decided that it would be best to first > translate this ASCII data into a binary file using a c++ program > (http://dnijaguar.tripod.com/atb.cpp). then, i could read in this > binary file (http://dnijaguar.tripod.com/bin0.dat) with the following > lines of python: > > >>> coord = array('d') > >>> coord.fromfile(open("bin0.dat",'r'),3000) > > however, there is a problem. i recieve the error: > Traceback (most recent call last): > File "", line 1, in ? > EOFError: not enough items in file > > and when i type in "coord" from the >>> prompt to see what is stored > inside it, i see the values listed at the very end of this message; > i.e. the correct values, but definately not 3000 of them like i > wanted. i would appreciate it if someone would tell me the reason i > am having this problem and the code necessary to fix it (with ASCII or > binary files). thank you very much for your help. > > value of coord shown on command line: > > array('d', [100000.0, 10000.0, -10000.0, 99995.0, 10001.0, -9998.0, > 97469.199999 > 999997, 10493.200000000001, -8994.9799999999996, 94890.199999999997, > 10969.0, -7 > 986.0299999999997, 92255.0, 11426.4, -6971.3000000000002, > 89560.100000000006, 11 > 863.4, -5950.9799999999996, 86801.800000000003, 12277.799999999999, > -4925.369999 > 9999999, 83976.100000000006, 12666.6, -3894.8499999999999, > 81078.399999999994, 1 > 3026.799999999999, -2859.9699999999998, 78103.5, 13354.6, > -1821.4400000000001, 7 > 5045.800000000003, 13645.5, -780.21400000000006, 71898.800000000003, > 13894.20000 > 0000001, 262.42399999999998, 68655.199999999997, 14094.4, 1304.74, > 65306.5999999 > 99999, 14238.299999999999, 2344.4000000000001, 61843.599999999999, > 14316.2000000 > 00001, 3378.1500000000001, 58255.099999999999, 14316.299999999999, > 4401.5, 54528 > .599999999999, 14223.5, 5408.04, 50649.400000000001, 14018.5, 6388.46, > 46600.699 > 999999997, 13676.4, 7328.8599999999997, 42363.400000000001, > 13164.299999999999, > 8207.8999999999996, 37917.5, 12439.6, 8991.7999999999993, > 33244.199999999997, 11 > 447.799999999999, 9625.9500000000007, 28333.599999999999, 10126.6, > 10022.7000000 > 00001, 23197.5, 8424.3799999999992, 10051.5, 17877.599999999999, > 6340.1099999999 > 997, 9557.7600000000002, 12415.1, 3945.0, 8431.9799999999996, > 6784.3100000000004 > , 1310.78, 6655.5600000000004, 863.47900000000004, > -1607.8800000000001, 4227.600 > 0000000004, -5535.2299999999996, -5062.9700000000003, 1022.54, > -12557.1, -9702.5 > 100000000002, -3429.2600000000002, -19426.0, -17103.799999999999, > -10433.2999999 > 99999, -21219.700000000001, -28053.400000000001, -20689.5, > -16580.799999999999, > -38120.0, -30341.599999999999, -9804.4699999999993, > -46184.900000000001, -38337. > 099999999999, -2476.6100000000001, -52974.699999999997]) From python at rcn.com Sat Mar 2 01:46:49 2002 From: python at rcn.com (Raymond Hettinger) Date: Sat, 2 Mar 2002 01:46:49 -0500 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: "Carel Fellinger" wrote in message news:a5orjv$7j0$1 at animus.fel.iae.nl... > Seriously I would like you to add something in your PEP that addresses > this simple alternative and explain why you favour yours. True, > `i in range(len(sequence))' doesn't look very pleasing, but > `i in indici(sequence)' does. And as an added bonus it's > very similar to `(i, item) in indexed(sequence)'. > > > > [Carel Fellinger] Yes! There is a pair of ideas that are intuitive, clean, and routinely useful: for i in indici(seqn) for i, item in indexed(seqn) Both ideas could be implemented as generators and work sequencially off the iter() of the sequence. This will accommodate lazy evaluation, low memory use, objects without a __len__ property, xrange objects, file objects, and objects with sequencial access defined by __getitem__ -- basically anything that could be used by a 'for item in sequence'. It may be that 'sequence' isn't the best choice of words. Iter() takes a 'collection' and 'for' takes an iterable. No matter what you call it, the pair of ideas looks like a great general purpose solution. I would add one little wrinkle. Define the functions to have an optional starting point. def indici(seqn, start=0). This will accommodate the common case of using natural numbers (starting from 1) or less common cases for those who start their check numbers at 1001. Let's implement those two ideas, cross-off the todo list (loop counter iteration proposals), then declare victory and get on with life. Raymond Hettinger "In theory, there is no difference between theory and practice. In practice, there is." From gcordova at hebmex.com Fri Mar 8 18:45:46 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Fri, 8 Mar 2002 17:45:46 -0600 Subject: RFC PEP candidate: q''quoted ? Message-ID: <19650FF08A99D511B19E00B0D0F0632301D6892C@SRM201002> I like the idea. If only as a method to keep all the data pertaining to a program --images, even-- in a single file. I hate having to lug around lots of icons and images just for a single program. icon = q'###END#OF#ICON###' aklkflj as.asd.a.s ... lotsa data ... lkjasd flaskdflakals ak ###END#OF#ICON### But then, I'm weird that way. Kinda like a CDATA section in a program. I like it. But I'm not gonna die without it. AND before someone else utters "save everything into a BSD db file and distribute that", don't; it's a dumb idea. I'd rather distribute an XML file with lotsa items and CDATA sections for binary or quoted data. Hmmm... that doesn't seem like such a bad idea. Except having to lug around an XML parser, and all the whatwithyou that it takes. :-( Hmmm... miniXML is for that... Please disregard everything I said. tgif :-) -gus From phr-n2002a at nightsong.com Tue Mar 5 22:22:01 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 05 Mar 2002 19:22:01 -0800 Subject: Why KeyError ??? References: <7dee885c.0203051843.36efa5c2@posting.google.com> Message-ID: <7xvgcabcti.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > > KeyError: šđčćž > > >>> a == b > > 1 > > Hmm. I don't get the same identity check results as you do: > >>> a = '\xe7\xd0\x9f\x86\xa7' > >>> b = unicode(a,'cp1250') > >>> a is b > 0 Try == rather than 'is'. The docs are a little bit imprecise about what's supposed to happen here, but 2.2.7 "Mapping types" says about numeric keys: A dictionary's keys are almost arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g. 1 and 1.0) then they can be used interchangeably to index the same dictionary entry. That makes it surprising if two unicode strings that compare as == don't index the same dictionary item. From cce at clarkevans.com Sat Mar 23 17:43:22 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Sat, 23 Mar 2002 17:43:22 -0500 Subject: Memory sizes of python objects? Message-ID: <20020323174322.A1111@doublegemini.com> Hello. I'm trying to figure out how much memory overhead is used with using strings, tuples, lists, and maps. In particular, say I have a nested structure like... entry = (92939938,"This is one of thousands of map entries", """ It even has multi-line data in it, appx 400 characters per entry. ""","2002-31-02 12:20 +500","Dogmeat") dict = {"Dogmeat":entry, # about a thousand more "indexed" entries } lst = [ entry, # about a thousand more entries ] etc. Is there some rule of thumb that I can use to estimate, for example, take the character data you have and multiply by a factor of 4 to find the in-memory footprint of tuples, and each map is 1K plus 64 bytes per entry.. Best, Clark From jriveramerla at yahoo.com Tue Mar 26 18:53:53 2002 From: jriveramerla at yahoo.com (Jose Rivera) Date: 26 Mar 2002 15:53:53 -0800 Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> <11e94203.0203232201.4dde9883@posting.google.com> Message-ID: <11e94203.0203261553.24850b7b@posting.google.com> The URL calculated : http://avisos.elnorte.com/casa_venta_result.asp?fotos=0&Order=order+by+colonia&Precio_i=-1&Presentacion=Tabla&Precio_f=-1&PLANTAS=0&pagina=1&id_inmueble=3&dia=&RECAMARAS=0&constr_f=-1&COLONIA=0&BANOS=0&Tipo=CASAS&Constr_i=-1&Terreno_i=-1&Terreno_f=-1&zona=0 works on my PC, but: The first time it gives me the error that you said, but a click on the http address of iExplorer and an enter on the keyboard load succesfully the page. I hope that help to find the problem... From BPettersen at NAREX.com Fri Mar 29 16:47:19 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 29 Mar 2002 14:47:19 -0700 Subject: List problem Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158DC2@admin56.narex.com> > From: Jon Cosby [mailto:jcosby at mindspring.com] > > Can anyone se why this is coming up empty in the "cols" list? > I've tried something similar in the interpreter, and > everything here looks right. For some reason, it isn't > finding any matches here. > [snip] > > # Word dictionary > dict = "c:\data\dict.txt" Try either r"c:\data\dict.txt" or "c:\\data\\dict.txt". -- bjorn From martin at v.loewis.de Sat Mar 2 03:36:04 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Mar 2002 09:36:04 +0100 Subject: PEP 263 comments References: Message-ID: "Jason Orendorff" writes: > Unfortunately it's all impossible. Unfortunately, yes. Let me explain how this will work under PEP 263. > * All my existing Python code should continue to run. They will, but you will might get a DeprecationWarning; eventually, your code might stop being accepted. > * I shouldn't have to understand what Unicode is, if all I want > is to bang out a quick script to say "hello world" in my native > language. You won't need to understand what Unicode is. You will need to understand what encodings are, though, i.e. you should know that "Gr?? Gott" requires Latin-1. With that knowledge, you can either change the system default encoding, or put an encoding declaration in your file. > * I should be able to send Python files to other people in > other countries, and they should run fine there too. That will work for the encoding declaration case (either with the Unicode marker, or the UTF-8 signature). If people have changed the system default encoding, this property may not hold. > * I should be able to use 'print' on strings and unicode strings > and get sensible output (I'll know it when I see it ). That will work depending on the terminal. In IDLE, it does currently work. For plain strings, it will also normally work, unless the file's encoding differs from the system encoding (or, rather, the user's terminal encoding). For Unicode strings, I'll write a PEP describing the use of Unicode at system interfaces, which targets this issue. > * Comments shouldn't affect the meaning of code. They won't in phase 1 of the PEP (although you will get a warning if you haven't declared an encoding, and left the system encoding at ASCII). In phase 2, you'll get a warning if the comment is not well-formed under the encoding. > * Random binary garbage in comments should be ignored, just like > it is today. That property may go away in phase 2. E.g. in a UTF-8 encoded file, Python will eventually verify that the comments actually are UTF-8. Some people consider this a good thing, as editors can't really round-trip files with different encodings at different offsets. Regards, Martin From cjensen at bioeng.ucsd.edu Tue Mar 26 20:03:23 2002 From: cjensen at bioeng.ucsd.edu (Curtis Jensen) Date: Tue, 26 Mar 2002 17:03:23 -0800 Subject: list of empty lists Message-ID: <3CA11A5B.5000501@bioeng.ucsd.edu> Is there a easy way to make a list of an arbitray number of empty lists? I can do something like: >>> some_number = 3 >>> l = [[]] * some_number >>> l [[], [], []] Unfortunatly this has an unfortunate side affect. Whatever I do to one of the list gets done to the other lists. ie: >>> l[0].append(1) >>> l [[1], [1], [1]] In this case, what I would like is three independantly empty lists. I can make a for loop to loop "some_number" of times and append an empty list at each itteration. Is there a simpler way? Thanks. -- Curtis Jensen cjensen at bioeng.ucsd.edu http://www-bioeng.ucsd.edu/~cjensen/ FAX (425) 740-1451 From jeff at ccvcorp.com Thu Mar 28 20:55:13 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 28 Mar 2002 17:55:13 -0800 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> <3CA3768B.32BB6AC9@ccvcorp.com> Message-ID: <3CA3C981.2433ECD7@ccvcorp.com> phil hunt wrote: > On Thu, 28 Mar 2002 12:01:15 -0800, Jeff Shannon wrote: > > > >I disagree. I'm just as happy that Python doesn't try to guess what would be a > >suitable "default" value for non-existent keys. > > The default value should always be None. > > None should act like 0 or "" or [] or {} where appropriate, i.e.: > > None + 1 --> 1 > None + "x" --> "x" > None * 4 --> 0 > None + ['x'] --> ['x'] > None + {2:3} --> {2:3} I strongly disagree with that. Next thing you know, you'll be saying that (3 + 'one' ) should evaluate to 4. Python has strong typing for a reason, just as it has dynamic typing for a reason. I wouldn't want to blur the line on types like this. I *want* to know that None is not valid for all of those operations, so that I can *tell* when I've got an error condition. > >It seems to me to be entirely > >consistent with the philosophy of "explicit is better than implicit". > > But that isn't the philosophy of any high level langauge. In fact, > the more high level any language is, the more implicit things are. > And I would argue that's a pretty good definition of what a high > level language is. I disagree with your conception of high level language. A high level language hides unnecessary details, but I don't think that conversion between different data types is an unnecessary detail. High level means that a logical step can be done in one or two lines of code, not that it does magic transmutations in the background. There's a large class of cases where the interpreter, in trying to "do the right thing", is as likely to guess wrongly as it is to guess right. If you want an interpreter that guesses anyhow, use Perl. I'll stick with Python, where uncertain cases are brought to my attention instead. Jeff Shannon Technician/Programmer Credit International From gimbo at ftech.net Mon Mar 18 12:51:54 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 18 Mar 2002 17:51:54 +0000 Subject: Correct to use instance = module.__dict__[class_name]() ? Message-ID: <20020318175154.GC19877@andy.tynant.ftech.net> I need to be able to take a string containing the name of a python module (without the .py) and a string containing the name of a class defined in that module, import the module, and create an instance of the class. I did have the following code, which works: def foo(module_name, class_name): import_statement = "import %s" % (module_name) exec import_statement handler = eval("%s.%s()" % (module_name, class_name)) return handler Given recent "exec/eval considered harmful" threads, I resolved to change it to something less controversial, and now have: def bar(module_name, class_name): module = __import__(module_name, globals(), locals(), []) handler = module.__dict__[class_name]() return handler Is this correct? In particular I'm worried that __dict__ is not the thing to use to get at the class object, but only really because I don't recall seeing it used like this before. Again, it seems to work fine - I just want to make sure I'm doing The Right Thing. :-) All input appreciated. Thanks, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From philh at comuno.freeserve.co.uk Wed Mar 13 09:39:29 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Wed, 13 Mar 2002 14:39:29 +0000 Subject: RFC PEP candidate: q''quoted ? References: Message-ID: On 13 Mar 2002 01:13:13 GMT, Bengt Richter wrote: >>> >>> q'|'c:\foo\bar\| >> >>"""c:\foo\bar\""" and r"c:\foo\bar\" work just as well. >> >You didn't mean that ;-) > > >>> """c:\foo\bar\""" > ... > ... (it's waiting for three unescaped quotes in a row) > ... """ > 'c:\x0coo\x08ar"""\n\n(it\'s waiting for three unescaped quotes in a row)\n' > >>> > >>> r"c:\foo\bar\" > File "", line 1 > r"c:\foo\bar\" > ^ > SyntaxError: invalid token > >>> > >>The best solution, of course, is to not use Windows. >> >You probably did mean that ;-) Absolutely. It's the solution I use, and it's never failed me yet. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From nospam at bigfoot.com Fri Mar 1 14:35:34 2002 From: nospam at bigfoot.com (Gillou) Date: Fri, 1 Mar 2002 20:35:34 +0100 Subject: hotmail References: Message-ID: If you got a pop3 access to your hotmail account, have a look at the "poplib" package. This is the easiest way. If you can only read your mail through Web pages, I think that "urllib" (performs HTTP GET/POST requests and retrieve Web pages) and "htmllib" (simple HTML parser) will help you for that job. But it's harder. HTH --Gillou "Ed" a ?crit dans le message news: d5534716.0203011007.4cfeb8b8 at posting.google.com... > hi > im just wondering whether it is possible to access hotmail thru python > so that i have a far quicker way of checking my emails. can telnetlib > do this? > thanx > ed From rjones at ekit-inc.com Wed Mar 13 20:14:38 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 14 Mar 2002 12:14:38 +1100 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: <200203132309.g2DN9rq30923@mail.merlinsoftech.com> References: <200203132236.WAA11518@crown.off.ekorp.com> <200203132309.g2DN9rq30923@mail.merlinsoftech.com> Message-ID: <200203140114.BAA00967@crown.off.ekorp.com> On Thu, 14 Mar 2002 10:10, Andy McKay wrote: > Roundup has always struck me as a more of an issue tracker rather than a > bug tracker which Bugzilla is aimed at. Interesting statement - I've used it in two jobs now in which it's used as a bug tracker... It doesn't have any workflow enforced, if that's what you're referring to. This can be implemented using the flexible detector mechanisms built into roundup... it's just that no-one has yet. > Bugzilla has lots of features and > problems as well, but add email support to Bugzilla and you have a good > scalable database with more features than Roundup. Unfortunately its in > Perl The underlying database in roundup is fully flexible - here we're looking at setting it up as the target of our customer feedback email address. That way emails get sent into the tracker and have "open/replied/closed" and our customer service people (and anyone else who is involved) may discuss the issue on the "mini mailing list" that is automatically handled by Roundup. > I would recommend looking at both them to any one installing a bug tracker, > but lets face it, the Python isnt likely to change soon ;) Oh yeah - that'd be a world o' pain :) Richard From grante at visi.com Thu Mar 14 23:29:27 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Mar 2002 04:29:27 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> Message-ID: In article <2b57f654.0203141934.391d1bcc at posting.google.com>, wealthychef wrote: > selectables = [theProcess.childerr, theProcess.fromchild] > (input, output, exc) = select.select([],selectables, selectables) It looks like you've got the first two parameters to select reversed. After the above call, output is going to contain writable sockets. If you're wanting to read data, you should do: (output, input, exc) = select.select(selectables,[],selectables) > if output: > for theOutput in output: > if theOutput == theProcess.childerr: > eoutput = theProcess.childerr.readline(bufsize) > print eoutput > elif theOutput == theProcess.fromchild: > stdoutput = theProcess.fromchild.readline(bufsize) > print stdoutput I think you're names output/input are confusing since (they're named from the child's point of view?). But that's just a style issue. BTW, the "if output:" isn't needed. If the "output" value is empty, then the for loop executes zero times. > It blocks forever waiting for theProcess.childerr.readline(bufsize) to > return. I expect it to block waiting for select.select(); When select returns a file descriptor, that means that read() won't block. If only a partial line is available, then readline() will still block. I doubt that this is going to be an issue, since your output is probably line-oriented. The code you posted got line-wrapped by your news client, and I'm too lazy to fix it. If the above tips don't get things running, post again (unwrapped code), and I'll give it another shot. -- Grant Edwards grante Yow! Am I accompanied by at a PARENT or GUARDIAN? visi.com From infinitystwin.SPAM at IS.BAD.yahoo.com Mon Mar 25 02:29:03 2002 From: infinitystwin.SPAM at IS.BAD.yahoo.com (Greg Krohn) Date: Mon, 25 Mar 2002 01:29:03 -0600 Subject: files and reading from them References: Message-ID: "Avi Homes" wrote in message news:auzn8.71680$Vl.2635455 at typhoon.austin.rr.com... > I am writing a dictionary to a file, like so > f.write(str(Info)) > > and what it is writing to the file is the following.. > {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} > > and if i write in two things, i get.. > {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} > {'IPrice': '2', 'IName': 'notworking, 'IDesc': 'annoying'} > > What i would like to do is pull a readline or somesuch.. and have it take in > the whole thing, and then just let me assign that to a empty name, and turn > it into a new dictionary.. like say > file.seek(1) > //thats how i'd go to the first place in the file correct? > X=file.readline() > > and now i can say print X['IName'] ... and its turned into a dictionary.. i > am most likely going about this *all* wrong. I'm assuming that you just want to create a dictionary from each line in your file. all you need is eval(). Like this: dict1 = eval(file.readline()) dict2 = eval(file.readline()) ... etc. greg From greg at cosc.canterbury.ac.nz Tue Mar 26 20:29:15 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 27 Mar 2002 13:29:15 +1200 Subject: list comprehension question References: Message-ID: <3CA1206B.7DB410B2@cosc.canterbury.ac.nz> Tim Peters wrote: > > He had already projected both the depth and sincerity of > your sorrow to six significant digits Using decimal or binary arithmetic? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From jeff at ccvcorp.com Tue Mar 5 15:33:02 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 05 Mar 2002 12:33:02 -0800 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <8fc4b19e.0203040130.17140530@posting.google.com> <8fc4b19e.0203042338.141afe8b@posting.google.com> Message-ID: <3C852B7E.2AD1FD64@ccvcorp.com> Geoff Gerrietts wrote: > Quoting Brian (brian at lodoss.org): > > OK - now I have another question (and remember I'm new to Python) if > > map and lambda are part of the core language and have well defined > > behavior, why is it that using them is considered bad form? Are they > > just the redheaded step-children of the language, or what? ;-) > .... > I think that I have seen notables in the python community (I would > name names, but I don't have quotes to reference) have indicated > regret at the introduction of map() and friends into the language. > They end up being appropriate only very, very rarely. > > The lambda construct doesn't suffer from quite the same stigma, though > I think some feel that it's overused, and to bad effect. To my understanding, you have this almost exactly backwards. The functions map(), filter(), etc, are standard functional-programming features and are very useful, in the right places. I can't recall them being specifically looked down on, or regretted. However, they are frequently used in places where list comprehensions would do the job better. List comps are a later addition to the language, though, so many people familiar with map() et. al., prefer to keep using them. Lambdas, on the other hand, are the ugly child that looks just like the postman... With functional constructs like map() being added to the language, functional programmers everywhere were begging for lambdas, as well (they're used heavily in Lisp and other f.p. languages). However, due to various reasons (mostly issues with the Python parser, IIRC), Python lambdas are crippled -- they can only contain a single expression, so they aren't *quite* equivalent to anonymous functions, but they still have the (relatively high) cost of a function call. They also have (IMHO) confusing syntax. The big gain in using list comprehensions, comes from the fact that it often eliminates the need to use an expensive (and, IMO, ugly) lambda. The line z = map(lambda x: MyClass(), range(y)) has y extra function calls (to the lambda) that are not present in z = [MyClass() for x in range(y)] Also note that the lambda doesn't really avoid the extra 'x' variable -- you're still using it as a parameter to the lambda, which is then ignored. Jeff Shannon Technician/Programmer Credit International From tim.one at comcast.net Sun Mar 31 15:43:15 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 31 Mar 2002 15:43:15 -0500 Subject: New-style exceptions? In-Reply-To: Message-ID: [Magnus Lie Hetland] > Is there a reason why new-style objects can't be used in the raise > statement? Almost certainly . If the question is really whether this is the intended final behavior, the answer is almost certainly no. From fdrake at acm.org Wed Mar 13 00:16:57 2002 From: fdrake at acm.org (Fred L. Drake) Date: Wed, 13 Mar 2002 00:16:57 -0500 (EST) Subject: [development doc updates] Message-ID: <20020313051657.CF40428696@beowolf.fdrake.net> The development version of the documentation has been updated: http://python.sourceforge.net/devel-docs/ Mostly minor updates; closed a few bug reports. From mcherm at destiny.com Tue Mar 12 13:21:34 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 12 Mar 2002 13:21:34 -0500 Subject: Has Mark Hammond attained pariah status yet? Message-ID: <3C8E472E.5090704@destiny.com> Um... look folks. We can all point at the article and laugh, but some people appear to be confused about what is and what isn't intended to be taken with a . So let me state a few facts quite clearly, with no sarcasm (or humor) intended. 1) Mark Hammond has made HUGE contributions to the Python community. The degree to which he personally has contributed to usability on the Windows platform is clearly an important contribution. 2) Mark generally has a decent sense of humor. So do lots of folks in the Python community -- after all, it's not named for a snake! We LIKE to laugh when journalists (or anyone!) makes a silly statement and uses it as a lead. 3) Not everyone will want to use a .NET version of Python if Mark were to create such a thing. (Not everyone will have a platform where they COULD use it.) But everyone (pretty much everyone) will be pleased that such a thing exists. Everyone (pretty much everyone) in the Python community thinks that Python is a really cool tool and would like as many people as possible to be able to use it! Python everywhere! 4) Mark should have more support from within the Python community for the work he is doing. So should Guido. And so does Andrew Kuchling, Robin Dunn, Finn Bock, and MANY, many others. We could all use an extra hand. I hope Mark gets the support he needs, much as I hope all the other projects make headway. Okay... now back to your regularly scheduled enabled sense of humor. This message has been sponsored by the C.C.U.P.M.H.B.P.W.A.H.S.H. (Committee to Cover Up the Pariah-ization of Mark Hammond By Pretending We All Have a Sense of Humor), a sub-committee of the PSU. From jgardn at alumni.washington.edu Thu Mar 14 21:59:25 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Fri, 15 Mar 2002 11:59:25 +0900 Subject: Windows Installation Message-ID: <7gdk8.277$ID.1679@news.hananet.net> I have a free software program (http://sf.net/projects/bttotalcontrol/) and I am having great difficulty writing an installation script for windows. I don't want to use distutils because I am not writing a module - but an entire distribution with images, data files, and executable programs. I would like to put icons on the desktop and stuff in the start menu as well. I am at a major disadvantage because I don't have access to a windows machine, and so I can't test anything directly. However, I do have a few people who actively test for the project at home. Anyone have any suggestions on where I should go? Anyone can help me out here? Jonathan From greg at cosc.canterbury.ac.nz Tue Mar 5 19:01:04 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 06 Mar 2002 13:01:04 +1300 Subject: Status of PEP's? References: <3C8445FC.A1816810@cosc.canterbury.ac.nz> Message-ID: <3C855C40.9061EF31@cosc.canterbury.ac.nz> David Eppstein wrote: > > Checking that the outer expressions contain one item rather than a tuple > needs to be done at run time. Of course, the compiler can catch some > instances where the expression is obviously non-single. I expressed myself a bit cryptically there. What the grammar should *really* say is for_stmt: 'for' (exprlist 'in' testlist | expr lt_op something lt_op expr ... but that would lead to a conflict between 'exprlist' and 'expr', so I made them both 'exprlist' with the intention that it would be restricted to a single 'expr' later. But since a run-time test is needed anyway, it mightn't be worth the bother. > the outer expressions should be or_expr to respect Python's > precedence rules I can't find 'or_expr', but I'm looking at the 1.5.2 grammar. Has it been added later? > and the inner one should be identifier. That's a bit too restrictive -- any lvalue should be allowed (as for-in does). Unfortunately there's no grammar symbol corresponding exactly to an lvalue. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From Tom_Good1 at excite.com Fri Mar 1 14:58:03 2002 From: Tom_Good1 at excite.com (Tom Good) Date: 1 Mar 2002 11:58:03 -0800 Subject: dirwalk.py generator version of os.path.walk References: Message-ID: jimd at vega.starshine.org (Jim Dennis) wrote in message news:... > In article , Just van Rossum wrote: > >In article , > > jimd at vega.starshine.org (Jim Dennis) wrote: > > >>> I wrote a different implementation of this general concept at: > > >>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105873 > > >>> You don't really need to keep a stack of directories and push/pop > >>> things, because with generators you can recurse instead. > >>> Tom > > BTW: Tom, I did come across your version in the ASPN a day or so > after I wrote mine. I agree it looks cleaner and simpler. > I might still use a list (FIFO or stack) and while loop instead > of the recursion. (see below). > If you've considered both approaches and prefer a non-recursive implementation, then sure, do it the way you like best. I wanted to point out another option in case you hadn't thought of it. [snip] > However, it would be nice if I > created a useful Python module which provided all of the power > for Python that the "find" command provides to the shell. That sounds cool. Post it when you're done :-) Tom From heiko.wolf at dlr.de Thu Mar 7 04:54:46 2002 From: heiko.wolf at dlr.de (Heiko Wolf) Date: 7 Mar 2002 01:54:46 -0800 Subject: Python/C - Memory-Management Message-ID: Hi there, I've got some C-functions that shall be adressed from Python. Thats no problem, thanks to SWIG. But now there is a problem about the memory management: One of the C-functions allocates memory for all the other functions. In C it works that way: static char *memory = NULL; int init_mem (void) { memory = (char *)malloc(sizeof(char) * 1000); } int free_mem (void) { free(memory); } If another function calls init_mem, it can use memory until free_mem is called... I want to do the same now in Python, but it seems as if the static memory isnt kept somewhere? When I try accessing it, I get a Segmentation Fault... Any suggestions? Cheers, Heiko From bkd at graphnet.com Wed Mar 20 06:26:54 2002 From: bkd at graphnet.com (Bruce Dykes) Date: Wed, 20 Mar 2002 06:26:54 -0500 Subject: classes for fun and newbies Message-ID: <0c0601c1d002$26eef0f0$5102020a@graphnet.com> Just to make sure I'm on the right track here... I'm reading records from a file. This is a flat file, with one line per record, and each line being some 380+ characters long, with about 40 fields in each record. Now I'm thinking that the easiest way to deal with these records (in preparation for developing a Zope app to interface with them), is to set up a class, with attributes for each field: class call_record: def __init__(self, record=''): self.record_id=record[0:5] self.date=record[6:11] etc... Now what I expect to be able to do is say: log = readlines(today.log) and then summon discrete bits of info like so: print call_record.record_id(log[1]) However, all I get when I try this is the return of of the object attribute instance and its memory address. Am I on the right track and just overlooking something obvious? Is there already an app that does something similar that I can browse for pointers? On a side note, it was fun just cranking out a python script that created the class code from the file documentation. 8-) bkd From akakakhel at attbi.com Sun Mar 3 20:00:49 2002 From: akakakhel at attbi.com (Ali K) Date: Mon, 04 Mar 2002 01:00:49 GMT Subject: The Text Widget Message-ID: <5Hzg8.72869$vP.290047@rwcrnsc51.ops.asp.att.net> I would like to know how to make it so that whenever I insert some text into the text widget from inside my program, it is inserted on a new line? Please Reply Thank You. Ali K. From bosahv at netscapenospam.net Thu Mar 14 12:34:12 2002 From: bosahv at netscapenospam.net (Bo Vandenberg) Date: Thu, 14 Mar 2002 17:34:12 GMT Subject: Good book on Python? References: Message-ID: I really like _Core Python Programming_ by Wesley J. Chun, I think it's very well written and really tied a lot together for me. Check out the url: http://starship.python.net/crew/wesc/cpp/README.htm I think it has a regular considerred approach which is the thing I really wanted in a book, as opposed to the online refs. If you out there, thanks author author = ('Wesley J Chun' , 'Mr. Chun', 'Wesley') Any way you slice it :) From delgado at eva17.Mathematik.Uni-Bielefeld.DE Tue Mar 19 02:25:53 2002 From: delgado at eva17.Mathematik.Uni-Bielefeld.DE (Olaf Delgado) Date: 19 Mar 2002 02:25:53 MET Subject: Tkinter and lengthy computations Message-ID: Hi all! What is good way to prevent a GUI from blocking during lengthy computations? Actually, the only thing I need is to have the application's main window be redrawn each time it becomes visible, so the user can do something else and come back from time to time to check the progress. After studying the documentation and the cookbook for inspiration, the solution I came up with is to initiate a daemonic "worker" thread on startup which receives tasks from and returns results to the GUI via two Queues (see example code at the bottom). It seems to work fine, so far, but looks somewhat complicated to me. Maybe I am missing something obvious. I am actually more an algorithms man than an application programmer and have never touched threads before. Cheers, Olaf # ============================================================ import Tkinter import threading import Queue import time class GUI: def __init__(self, master, tasks, results): self.tasks = tasks self.results = results self.counter = 0 self.master = master Tkinter.Button(master, text = "Work!", command = self.work).pack() self.output = Tkinter.Label(master, text = "") self.output.pack() self.poll() def work(self): self.counter = self.counter + 1 self.tasks.put(self.counter) def poll(self): try: item = self.results.get_nowait() except Queue.Empty: pass else: self.output.configure(text = str(item)) self.master.after(100, self.poll) def work(tasks, results): while 1: try: task = tasks.get_nowait() except Queue.Empty: time.sleep(0.1) else: results.put("Task %s started." % task) # Pretend to do a lengthy computation: time.sleep(20) results.put("Task %s completed." % task) tasks = Queue.Queue(1) results = Queue.Queue(1) worker = threading.Thread(target = work, args = (tasks, results)) worker.setDaemon(1) worker.start() root = Tkinter.Tk() root.title("Threading test") GUI(root, tasks, results) root.mainloop() # ============================================================ -- //// Olaf Delgado Friedrichs, Dept. of Chemistry, Olaf Arizona State University, Tempe AZ 85287, USA `=' phone +1-480-965-6570 fax +1-480-965-2747 http://www.mathematik.uni-bielefeld.de/~delgado From eric.brunel at pragmadev.com Fri Mar 22 09:46:13 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 22 Mar 2002 14:46:13 +0000 Subject: __* name mangling documentation References: Message-ID: Michel Pelletier wrote: > http://www.python.org/doc/current/ref/id-classes.html > > sort of left me hanging on why __ name mangling exists and why it would be > used. Simple: private attributes and methods: class C: def __init__(self): self.__a = 1 self.b = 2 o = C() ## Attribute "b" has no "__" => no name mangling ## => public => this works: o.b = 3 print o.b ## Attribute "__a" has a "__" => name mangling ## => private => this doesn't work: o.__a = 4 print o.__a This mimicks the behaviour of an attribute declared "private" in languages like C++ or Java. Sorry if you already know about all this, but it actually implements the OO concept known as "encapsulation": an object should only expose attributes and methods that are meaningful to the "outside world". Any attribute or method used internally should not be seen from outside the object. > I'm curious because I'm looking at some code right now that uses it in > a somewhat tricky way and I want to know why. I can't figure out what could be "tricky" about private attributes or methods: they can only be accessed from inside the class's instances, and that's all there is about them... Can you provide an example of what you mean by "tricky"? HTH - eric - From bokr at oz.net Sat Mar 9 16:56:14 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 21:56:14 GMT Subject: Is current integer for-loop syntax a wart? References: Message-ID: On Sat, 9 Mar 2002 13:05:56 +0000, philh at comuno.freeserve.co.uk (phil hunt) wrote: [...] > >You can get a dictionary's keys, so you ought to be able to do so >with sequence types, in the same way. > This is a nice insight. There ought to be a repository where the above snip and others like it could be placed, so they don't get lost. Some kind of keyword tagging for searching maybe also. XML? Regards, Bengt Richter From briner at infomaniak.ch Tue Mar 26 03:34:41 2002 From: briner at infomaniak.ch (cedric_briner) Date: Tue, 26 Mar 2002 08:34:41 -0000 Subject: list element of a class with the for statement Message-ID: hi, I'm interesting to know which method of a class I have to define to list the __records of this class: class CRdb: __fieldsName= [] __keyname= [] __records = ['first','secnd','third'] __iRecord= 0 because I would like to write something like: db=CRdb() for entry in db: print entry and then get first secnd third please let me know any pointer refering this topic...or even better a quick solution .. thanks. Briner From geoff at gerrietts.net Sat Mar 9 02:17:54 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 8 Mar 2002 23:17:54 -0800 Subject: broken pipes, import errors (LONG, INVOLVED) In-Reply-To: References: Message-ID: <20020309071754.GA8360@isis.gerrietts.net> Quoting Bengt Richter (bokr at oz.net): > On Fri, 8 Mar 2002 16:13:54 -0800, Geoff Gerrietts wrote: > >At work, I'm seeing an "interesting" problem in my production > >environment, or maybe two problems. It's one of those problems that > > I don't have a clue about your situation, but it strikes me that exec and eval both > use name spaces (local and global dictionaries) that you could specify, but don't. > > I'm wondering if the default (current scope) is ok in your context. If we were to specify namespaces, globals() and locals() would be the appropriate namespaces to specify. So we don't. In this case, exec and eval are both being used as shortcuts, because the long form in either event is ... longer. A little more code for the import, a little more code for the eval(): statement = "import module.submodule.SubSubModule" exec statement where statement consists of translates roughly into: toplevel = "module" modpath = "module.submodule.SubSubModule" locals()[toplevel] = __import__(modpath) The eval() structure can be similarly replaced with a looped getattr() on each of the path components. It's just clumsier to do it this way. Note: while "statement" is assigned directly in the sample code, that's really just to show everyone what the variable contains. "statement" is dynamically built, as is "object_nm". We've tried replacing the eval and exec, to no effect. The variables do contain the expected values. For two years, they've worked pretty well. We have no idea what might have changed to make them stop working pretty well. > If you are repeatedly reusing the same current scope (e.g., doing > those exec and eval lines inside a loop) for unrelated things, maybe > there are name collisions? When you try to import a module twice, import just does nothing (or at least very little) after the first effort. In fact, when you first import, Python caches a copy of the module in the global namespace. When you subsequently import, it re-uses that cached copy. The cached copy is also corrupt. > Maybe logging the output of dir() before and after those lines would > reveal something? We've done that, and compared successful runs with runs where the error erupts. "module" is populated correctly each time. "submodule" varies fairly drastically in its contents between a successful run and an unsuccessful run, but it's not clear why. > Or try specifying local and global dicts and .clear() them after use > (maybe the default environment is keeping something alive that > should get garbage-collected and have its destructor executed? Or > maybe one finally does fire off after a same-name rebinding of a > reference, and the old destructor is doing inappropriate cleanup for > the new environment? How does memory usage look?) This error almost always occurs within the first twenty minutes of a process (Zope process) that's accustomed to run for a week or so without being restarted. > These are just ideas trying to jog your thoughts, hopefully helpfully ;-) > No specific recommendations -- you'll have to figure what's appropriate for your situation. I appreciate all the efforts to help. Much of what you've suggested, we've considered. I may recommend trying local dictionaries which we then destroy after exiting the function body, to see if we can elicit any more information from doing so. I confess I have little hope that it will solve our problem -- there's nothing happening in that namespace to remove these objects. They just never show up in the first place; the import quits halfway but fails to raise an error. Thanks for the thoughts, --G. -- Geoff Gerrietts "Punctuality is the virtue of the bored." --Evelyn Waugh From usenet at woggo.org Tue Mar 12 02:12:11 2002 From: usenet at woggo.org (Will Benton) Date: 11 Mar 2002 23:12:11 -0800 Subject: m2crypto problems Message-ID: <9625d523.0203112312.6a972d51@posting.google.com> Hello, all. I'm trying to run the example echo server (from the m2crypto docs), but I get the following error: [willb at ludwig ~/src/python/examples]$ ./sslecho.py Traceback (innermost last): File "./sslecho.py", line 3, in ? from M2Crypto import SSL, X509 File "/usr/lib/python1.5/site-packages/M2Crypto/__init__.py", line 6, in ? import _m2crypto File "/usr/lib/python1.5/site-packages/M2Crypto/_m2crypto.py", line 2, in ? import _m2cryptoc ImportError: /usr/lib/python1.5/site-packages/M2Crypto/_m2cryptoc.so: undefined symbol: d2i_SSL_SESSION It looks like that symbol is defined in libcrypto, which is in my LD_LIBRARY_PATH. I'm using Red Hat 7.2, OpenSSL 0.9.6b, and m2crypto 0.05_snap4. Anyone know how I can fix this? Thanks, wb From bokr at oz.net Tue Mar 26 01:50:42 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Mar 2002 06:50:42 GMT Subject: beginner question References: Message-ID: On Tue, 26 Mar 2002 05:25:28 GMT, "Qiang.JL" wrote: >for this line: > >>>> g=(lambda x: ' '.join(x.split())) or (lambda y: 'second') > I doubt if this expression is doing what you want. It is the same form as g = a or b which will set g to a, unless a counts as false (e.g., None,'',[],(), or zero), in which case g will be set to b irrespective of b's value. So your expression is effectively equivalent to g=(lambda x: ' '.join(x.split())) Since you are binding to g anyway, you might as well do it the straight forward way: def g(x): return ' '.join(x.split()) >now by calling g(str(something)) make sure i always pass a string to the >function(ignore exception if improper stuff in str). I want to know what If you are always going to call it that way, it would make more sense to put it in the function, e.g., def g(x): return ' '.join(str(x).split()) >parameter i can pass to the lambda function so that the first condition >false then second condition get executed? If you just want an alternate expression when the first is "false", just add it to the return expression, e.g., def g(x): return ' '.join(str(x).split()) or 'second' >or as long as i pass a string,it's always true for the first condition? > The best way to find out is play with the interpreter. It will tell you: >>> def g(x): ... return ' '.join(str(x).split()) ... >>> g('') '' Or try it with a lot of mixed white space, which split will get rid of: >>> g(""" \t \r\r\r\n\n\n ... \t \t ... \f ... """) '' Now what will happen if we tack on an 'or' to that expression? Trying it: >>> '' or 'second' 'second' What happens if we pass a non-string as argument? Try it! (e.g., g is a function, not a string): >>> def g(x): ... return ' '.join(str(x).split()) or 'second' ... >>> g(g) '' >>> g(0) '0' >>> g(' ') 'second' >>> g('') 'second' If you really don't want to use def and you want to use your original expressions, use another lambda to tie them together, e.g., (OTTOMH, not very well tested ;-) >>> g = lambda x: (lambda x: ' '.join(x.split()))(str(x)) or (lambda y: 'second')(str(x)) >>> g(' ') 'second' >>> g(g) ' at 0x007DB060>' >>> g(' a bc def') 'a bc def' Notice that the ouside lambda has a body that both defines _and_ calls the internal lambdas with the str()-protected arguments. The second lambda will only be called if the first one returns ''. The outside lambda then returns the result from whichever internal one. But I'd say that's pretty ugly to read compared to >>> def g(x): ... return ' '.join(str(x).split()) or 'second' ... ;-) Regards, Bengt Richter From ken at ineffable.com Thu Mar 7 12:30:26 2002 From: ken at ineffable.com (Ken Causey) Date: 07 Mar 2002 11:30:26 -0600 Subject: Handling bad tags with SGMLParser In-Reply-To: References: Message-ID: <1015522226.444.21.camel@temp> On Thu, 2002-03-07 at 11:12, Sean 'Shaleh' Perry wrote: > > > > The user of SGMLParser needs to be able to handle invalid tags. This > > handling may be complex or as simple as just ignoring it and asking > > SGMLParser to skip this tag and move along. As far as I can tell this > > is not an option. > > > > As a side note, the text error message thrown is particularly > > uninformation as it simply includes the first letter of the tag, in > > other words always '<'. > > > > match = special.match(rawdata, i) > if match: > if self.literal: > self.handle_data(rawdata[i]) > i = i+1 > continue > # This is some sort of declaration; in "HTML as > # deployed," this should only be the document type > # declaration (""). > k = self.parse_declaration(i) > if k < 0: break > i = k > continue > > is the offending code. 'special' is defined as re.compile(r']*>'). > > I see two options: > > 1) change the definition of special to a noop match. Something that is > relatively cheap but can never match. > > 2) write your own parse_declaration() method. > Yes, but both of these changes would violate the object model of SGMLParser, at least as evidenced by the module documentation. It would also, I suspect be non-portable among Python versions. For example the behaviour of 1.5.2 is quite different here. I'm inclined at the moment to report this situation as a bug. But I wanted to get some opinions as I'm neither an SGML expert nor fully confident of my understanding of the SGMLParser class. The easiest fix I can come up with at the moment is to modify the SGMLParseError throw so that the position in the rawdata of the error is returned with the exception so that the data can be resubmitted skipping the offending tag (reporting the endpoint of the bad tag would be even handier). Of course this also involves modifying private implementation details. By the way, I'm nikos on #python if anyone cares to discuss this in a more "live" context. Ken From olc at ninti.com Sat Mar 30 19:46:40 2002 From: olc at ninti.com (Michael Hall) Date: Sun, 31 Mar 2002 10:16:40 +0930 (CST) Subject: CGI/modpython ??? Message-ID: I'm writing Python CGI scripts using the MySQLdb module and getting a grasp on things fairly quickly ... Python is a cool language (I'm coming to it from PHP). Thanks to Drew and Emile for sorting out my looping function, it works fine now. Now I'm wondering how modpython is used. If Apache has the modpython module installed, how do I use it? What form do scripts take? Do they still look like CGI scripts, or do they look more like a PHP script (some sort of embedded scripting)? Does a script still use '#!/usr/bin/python', or are file endings (eg .py) used to call the Python interpreter? Is the script located in public_html or cgi-bin? What would I have to do with a CGI script written in Python to use it with modpython? Thanks ----------------------------- Michael Hall mick at ninti.com ----------------------------- From sdm7g at virginia.edu Mon Mar 4 14:50:02 2002 From: sdm7g at virginia.edu (Steven Majewski) Date: Mon, 4 Mar 2002 14:50:02 -0500 (EST) Subject: Twain Scanners and some other questions In-Reply-To: <005801c1c39a$a5418900$0101010a@local> Message-ID: On Mon, 4 Mar 2002, Chris Gonnerman wrote: > > > The wonderful Daily Python-URL (http://www.pythonware.com/daily) just > > > pointed to http://twainmodule.sourceforge.net a few days ago. > > > > but this only works on windows, making it useless for real computers. > > Ah, dix is interested in *TWAIN* scanner drivers, so necessarily that means > Windows. The TWAIN driver interface isn't used outside the M$ world AFAIK. It's also a very common interface on Macintosh. I don't know of any reason the spec couldn't be implemented on unix, but I also don't know if any implementation. ( And without commercial apps that use it like Photoshop, there's probably not much demand. ) [BTW: You can find the spec at www.twain.org.] -- Steve Majewski From jkraska at san.rr.com Wed Mar 27 20:43:15 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 28 Mar 2002 01:43:15 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <8gv3au47846mgol398j4oc5t0ufoi274b4@4ax.com> Message-ID: >I've just tried: > >suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT | NEWLINE >suite: simple_stmt | NEWLINE INDENT stmt* DEDENT >suite: simple_stmt | NEWLINE [INDENT stmt+ DEDENT] > >None of which work. Mind you, I don't know the language of the >python parser-generator, having never seen it before, and so I am >just guessing things that looks like they might work. No doubt >someone more familiar with it could do better. I'm not saying it's impossible, but I'm not surprised these changes didn't work. I've recently clean-roomed a ANTLR parser for Python and discovered a lot along the way. As it turns out, some major conceptual pieces of Python are directly related to the domain space of inferred-block-delimited programming languages. What I'm trying to say here is that there are things about Python that, if you had never seen Python but had implemented an inferred-block-delimited language of your own, you'd say "oh, of course." Optional pass could be done. I'm sure. But with hair. So it's not. And it's no big deal, really. There's so many other fish to fry. When something is an artifact of implementation versus problem- domain constraints, I always consider this a wart, but then there's warts and there are warts. "pass" isn't worth stuggling over, in my mind. I can think of other warts in other languages, much worse. Take Java. They didn't do MI for implementation reasons. And as part of the domain space, MI is a highly valuable problem solver. I view Java's lack of MI as a very grave sin, the ultimate admission of defeat by the implementer. C// From pearu at cens.ioc.ee Fri Mar 22 09:29:57 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Fri, 22 Mar 2002 16:29:57 +0200 Subject: mutlifile inheritance problem In-Reply-To: <9896e047.0203211303.741f695a@posting.google.com> References: <9896e047.0203211303.741f695a@posting.google.com> Message-ID: On 21 Mar 2002, Marc wrote: > class ImStream_SavedBitmaps(cbase01.CImStream): > > def __init__(self): > cbase.CImStream.__init__(self) ^^^^^ This should be cbase01, right? > *************************************************************** > > If I run test02 I get the traceback > > Traceback (innermost last): > File "", line 1, in ? > File "D:\PythonCode\pna\eyeTracking\tests\test02.py", line 15, in ? > x0 = wrappers_A01.ImStream_SavedBitmaps() > File "D:\PythonCode\pna\eyeTracking\tests\wrappers_A01.py", line 21, > in __init__ > cbase.CImStream.__init__(self) > TypeError: unbound method must be called with class instance 1st > argument Though, I cannot explain how the above typo could cause this exception. Pearu From sasoft at gmx.de Fri Mar 29 10:24:06 2002 From: sasoft at gmx.de (cruciatuz) Date: Fri, 29 Mar 2002 15:24:06 +0000 Subject: Anyone need a program written? In-Reply-To: <7o_o8.17314$Ou.7311@atlpnn01.usenetserver.com> References: <3ca43ef4.3666136@news.tudelft.nl> <7o_o8.17314$Ou.7311@atlpnn01.usenetserver.com> Message-ID: <20020329152406.GA2671@blackscarab> On Fri, Mar 29, 2002 at 08:55:51AM -0500, Steve Holden wrote: > "Fused" wrote in > message news:3ca43ef4.3666136 at news.tudelft.nl... > > However, I detest building programs that have already been > > built a kazillion times and aren't of use to anyone. ! > > Can anyone think of a program that I could build that would actually > > have use to someone (you?)? I'm trained in Delphi, know some Java and > > rudimentary C, so the programs don't need to be newbie-easy ( I like a > > challenge: the greater the challenge, the faster I'll learn ;-) ). > > I'd really like to see a Python mail/newsreader. That would teach you a lot, > and keep you busy for a while... mhh, it wouldn't be _too_ useful, i think: http://freshmeat.net/browse/31/?filter=178&topic_id=31 but it would be great to have something like that based on python's Tk wrapper, because i am also interested in good communication-tools in python, but i ran into (installation-)trouble with the different gui-toolkits. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 240 bytes Desc: not available URL: From gimbo at ftech.net Mon Mar 4 18:18:29 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 4 Mar 2002 23:18:29 +0000 Subject: question about an installation of a new module In-Reply-To: <"020304203918Z.WT13248.28*/PN=Francois-regis.Chalaoux/O=RESEARCH/PRMD=SANOFI/ADMD=ATLAS/C=FR/"@MHS> References: <"020304203918Z.WT13248. 28*/PN=Francois-regis.Chalaoux/O=RESEARCH/PRMD=SANOFI/ADMD=ATLAS/C=FR/"@MHS> Message-ID: <20020304231829.GB22326@andy.tynant.ftech.net> On Mon, Mar 04, 2002 at 07:23:13PM +0100, Francois-regis Chalaoux wrote: > After my 'configure', 'make' and 'make install' of Python , I > modified the 'Setup' from Module directory and then I ran 'make' as > explained in the README.txt. > > However, should I run again 'make install' again after this > modification ? Yes - otherwise the rebuilt code isn't installed, it's just sitting wherever you built it. Note that you could have modified Modules/Setup any time after .configure, and didn't need to run make && make install first. -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From jeff at ccvcorp.com Thu Mar 28 13:53:32 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 28 Mar 2002 10:53:32 -0800 Subject: IDiscMaster interface References: Message-ID: <3CA366AB.934E9719@ccvcorp.com> Chris Gonnerman wrote: > I have been investigating the IDiscMaster interface implemented > in Windows XP. It appears to be a COM interface (I'm a Linux/Unix > type of guy and know very little about Windows internals), but I > can find no type library. Has anyone else used this interface > (component, whatever) via Python? I'd really like to be able > to burn CD's automatically for backup purposes. Note that there are (effectively) two types of COM interfaces -- "custom" and "automation" (I'm not sure I've got the terms exactly right, but...) Pythoncom currently only handles automation interfaces (which were inteded to be used from scripting languages), not custom interfaces (which were effectively intended to be used from C++). As I understand it, in order to handle a custom interface (which I am guessing the IDiscMaster interface is), you'd need to delve deep into the internals of pythoncom. Of course, I'd *love* to be proved wrong about this... ;) Jeff Shannon Technician/Programmer Credit International From sjones16 at rochester.rr.com Sun Mar 3 14:38:26 2002 From: sjones16 at rochester.rr.com (Seth Jones) Date: Sun, 03 Mar 2002 19:38:26 GMT Subject: Trouble running programs References: Message-ID: Hi. I think your problem is you're trying to run the script from the wrong window. The 'run script' menu item in idle runs the script that is in the same window as the menu you're using. So when you open up a new window to write a script, that window should have a menu that you can select 'Run Script' from. Note "working directory" of the script will not be the same directory the script is actually in, as I recently learned. This means if you're doing any file i/o, you'll need to supply the full path, which is obnoxious. IDLEfork does properly handle the working directory: See http://idlefork.sourceforge.net/ You probably won't need to worry about it if you're not doing file i/o, though. "default_renegade" wrote in message news:mailman.1015181645.9476.python-list at python.org... > Just started learning Python, but having trouble running a programs. > First, I open IDLE, then open a new window > Then I write a program and save it, then I close the window > When I'm back at the Python Shell and select Run Script It gives me > an error "Not Saved - The bugger for Python Shell is not saved. > Please save it first!" > However, I can run the program from the DOS prompt. > > From arigo at ulb.ac.be Tue Mar 19 13:02:34 2002 From: arigo at ulb.ac.be (Armin Rigo) Date: Tue, 19 Mar 2002 19:02:34 +0100 Subject: Returning an element from a C struct References: <3C9772AB.1691D362@saic.com> Message-ID: <3c990582$0$29676$ba620e4c@news.skynet.be> > How about > > def __getattr__(self,name): > try: > return self.__dict__[name] > except KeyError: > return getattr(self.ptr, name) It even looks like the first 'return' is not needed. If the attribute is found in the instance then __getattr__() is not called at all. Armin From skurland at juggler.net Tue Mar 12 22:07:33 2002 From: skurland at juggler.net (Scott Kurland) Date: Tue, 12 Mar 2002 21:07:33 -0600 Subject: frustrated stupid newbie question References: <8B012C611E@kserver.org> Message-ID: > > > > Why isn't this $%^*#$% program working? > > > > > > > #Searching for perfect numbers > > > > > > > > howhigh= input ("How high should I check?") > > > > for number in range (1,howhigh): > > > > factorsum = 0 > > > > halfnumber=number/2 > > > > for checking in range (1,halfnumber): > > > > if number/checking == int (number/checking): > > > > factorsum = factorsum + checking > > > > if number == factorsum: > > > > print number > > > > > > > > > > What do you mean it isn't working? It ran without crashing when I tried > > it. > > > Here is the output from a sample run: > > > > > > >>> > > > How high should I check?50 > > > 10 > > > > > > Are you expecting some other type of output? What are you expecting? > > > > Well, I was expecting failure, which we got. What I hoped for was the two > > perfect numbers between 1 and 50, 6 and 28. > > You really should play with the interpreter window open, or add more print > statements to your code so that you can see what is happening at all of the > intermediate steps. Consider the data in this interactive session: The former didn't help. I'll try the latter. Thank you. > > >>> howhigh = 10 > >>> range(1,howhigh) > [1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> range(1, howhigh + 1) > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > >>> for number in range(1, howhigh + 1): > print "for number = ", number, > print "halfnumber = ", number/2 > > > for number = 1 halfnumber = 0 > for number = 2 halfnumber = 1 > for number = 3 halfnumber = 1 > for number = 4 halfnumber = 2 > for number = 5 halfnumber = 2 > for number = 6 halfnumber = 3 > for number = 7 halfnumber = 3 > for number = 8 halfnumber = 4 > for number = 9 halfnumber = 4 > for number = 10 halfnumber = 5 > >>> > > Is this what you expect of the data in the intermediate steps? Nope, I was hoping for .5, 1, 1.5.... > > > > > Flame away, I can't feel dumber than this. > > > > > > Oh, now what newsgroup mistreated you so, that you would expect such a > > > thing? We don't do that here in comp.lang.python! > > > Goodness! I'll have to mind my manners carefully, then; usenet has roughened > > them some. > > > > Thank you, Sheila. > > Are you saying, that we need to watch out for flames from you??? > Oh, dear! > (donning my asbestos suit...) No, no, I'll do my best to be a Good Boy, honest. From claird at starbase.neosoft.com Wed Mar 20 10:29:34 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 20 Mar 2002 09:29:34 -0600 Subject: MySQL's applicability (was: Java and Python) References: <3C96DBB4.6040109@pobox.com> <3C984F44.1090001@pobox.com> <3C9887B9.6090603@thinkware.se> Message-ID: <82B3E32A4EFF0E57.126AAAECC4E2B809.F8613C4251DB7A4B@lp.airnews.net> In article <3C9887B9.6090603 at thinkware.se>, Magnus =?ISO-8859-1?Q?Lyck=E5?= wrote: >Hi, as a Java coder you might want to look >into Jython and combine your skills. That >would for instance enable you to quickly >prototype Java programs in Python. Worth repeating. > > >Ahmed Moustafa wrote: > >> May I ask you what the scal for your webapp was? (Because MySQL is >> related to small to mid-size web applications). Is it the same case with >> Python? > > > >Not at all. > > >But I think both MySQL and Python scales well. >MySQL has some shortcomings, and since the >purchase cost is so low :) it's a good >choise for systems with a small budget. But >don't dismiss is as a weak database in larger >settings. In places where you have many more >reads than transactions, MySQL might well be >the fastest choise. Undeniably. That's certainly the conclusion of "the first time a computer publication has published database benchmark results ...", as *eWeek* did in its 25 February 2002 issue. The subtitle of the article was "Oracle9i and MySQL top the field ..." So, no, MySQL is NOT "related to small to mid-size web applica- tions". I rarely use MySQL myself, because it doesn't happen to meet my most common needs. There are indeed several aspects in which "scalability" can be interpreted in a way which disqualifies MySQL. I can imagine these might be particularly prominent for someone coming from an OS/390 background. The precision of answers seen here, though, correlates the specificity of questions quite closely. When we're asked whether Python scales as poorly as MySQL, with little more context, responses are ... unlikely to hit the questioner's exact-although-unexpressed target. . . . >There are many big web apps written in Python. Worth repeating. . . . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From ocscwar at h-after-ocsc.mit.edu Tue Mar 26 15:08:50 2002 From: ocscwar at h-after-ocsc.mit.edu (Omri Schwarz) Date: 26 Mar 2002 15:08:50 -0500 Subject: urllib question. (asseumbling an HTTP post request) Message-ID: Hi, all, I'm trying to parse an HTML form in Python, assemble a POST and send it off. Right now, here is what the script I have does: # a regex to gather the inputs: findinput = re.compile('\|\') # then later on: c = urllib.urlopen(b).read() subject = findsubject.search(c) if subject: print "Is this spam?\n" print subject.groups()[0] if (raw_input()[0] =='y') : # here's the part that may be going wrong: for cb in findinput.findall(c): print cb if cb[3] == 'checkbox': if cb[5] == 'checked' : poststring[cb[4]]= 'on' if cb[0] == 'hidden': poststring[cb[1]]=cb[2] d = urllib.urlencode(poststring) print d res = urllib.urlopen('http://www.spamcop.net/sc',d).read() The form has hidden inputs, checkboxes, and the submit button. When I use a browser (Netscape or Lynx), everything is fine. When I try to use this script, I get server side errors that are no help to me. So, has anyone already written a form parser for this purpose? Can anyone think of other problems that might be happening? Thanks, in advance. -- Omri Schwarz --- ocscwar at mit.edu ('h' before war) Timeless wisdom of biomedical engineering: "Noise is principally due to the presence of the patient." -- R.F. Farr From dsavitsk at e-coli.net Tue Mar 12 16:13:45 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 12 Mar 2002 21:13:45 GMT Subject: sorting nested dictionary Message-ID: i have a dictionary that looks something like the following: {'ids': {'2778xxxxx': {'weighted': 4.6, 'raw': 5.0}, '3059xxxxx': {'weighted': 6.1, 'raw': 6.0}, '3188xxxxx': {'weighted': 3.2, 'raw': 4.0}, '3216xxxxx': {'weighted': 10.1, 'raw': 7.0}, '3257xxxxx': {'weighted': 9.7, 'raw': 9.0}, '3266xxxxx': {'weighted': 4.8, 'raw': 3.0},}} i would like to sort this portion by 'weighted'. is there a quick (as in programming time, not sorting time) better way to do this other than dumping the values to a list, sorting, and realigning the data? that seems so unpythonic to me somehow. thanks, doug From nhodgson at bigpond.net.au Tue Mar 19 17:20:11 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 19 Mar 2002 22:20:11 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: Martin v. Loewis: > Subclassing may not be the right solution - perhaps it is better to > admit that ntmodule.c really should be different from > posixmodule.c. What do you think? There is also a lot that should be shared, such as the docstrings, much of the argument parsing as well as many of the posix calls. Splitting may lead to more breakage when common patches aren't applied to both. Creating a separate file for NT doesn't generalise that well to the many splits really present in posixmodule, with a quick look showing OS/2, QNX, SCO and Windows splits along with at least three compilers on Windows (Microsoft, Borland, Watcom). It needs a way to specify the base generic posix case cleanly but then to allow platforms to specialise or remove those functions needing different implementations or which can not be implemented. In my own C++ work, I normally do this through subclassing. Neil From grante at visi.com Fri Mar 15 12:39:06 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 15 Mar 2002 17:39:06 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> Message-ID: <_kqk8.25881$N7.5410299@ruti.visi.com> In article , David Bolen wrote: > grante at visi.com (Grant Edwards) writes: > >> That is true under Win32 -- Just one of the problems when using >> an OS where the networking was pasted on (badly) as an >> afterthought. >> >> Under Unix, select works on all file descriptors (sockets, >> pipes, serial ports, etc.). That demonstrates the _right_ way >> to paste on networking as an afterthought. > > Of course, to be fair, it's not really networking that was pasted on > badly but rather the socket interface. TCP/IP networking that was pasted on as an afterthought, and that's when select came into the picture. > If you're using native Win32 operations on native Win32 file > handles, you can perform asynchronous I/O and wait for > completion on just about all the native kernel objects Are TCP/IP connection native kernel objects? > - and even mix in other signaling objects simultaneously. > > And winsock does provide a way to tie socket I/O into the same > event system. > > In Unix, select just happens to be a more generic function, > whereas in Windows it was grafted on as part of the socket > library. But that's more a portability issue than a comment on > Windows internals. Fair enough. -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From peter at engcorp.com Tue Mar 12 00:00:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Mar 2002 00:00:02 -0500 Subject: should i learn it first ? References: <7CWi8.104549$aFN.34864@news1.bloor.is> Message-ID: <3C8D8B52.FAB4E102@engcorp.com> Chris wrote: > > In article <7CWi8.104549$aFN.34864 at news1.bloor.is>, Qiang.JL > writes > >yeah. i have been following my post. thanks for everyone's input. It > >helps! > >seems a lot people recommend C over C++, i would keep this in mind and > >get a go at it. i think i get a list of language to learn and go deeper > >now : Java, C, Perl, Python, Lisp > > I've been following it, too, with great interest. > I reckon I'm going to go for Python and Java. > Java is particularly attractive because you can distribute your programs > to absolutely anybody in the form of applets. Don't put much weight on the applet thing. If you're thinking of having people run your program with their browser, you have to consider (a) the gross incompatibilities with the different implementations, and (b) that many (most?) people run with Java disabled, or don't have Java in their browser at all. Having tried in depth Java, C, C++, and Python (as well as many others) I would suggest you learn Python, _then_ C, only _then_ Java, and only C++ if you have a very specific business need for it (i.e. because you'll become rich if you agree to prostitute yourself and write software using it, or kidnappers force you to do so). And by the way, I'm a fan of both C and Java.... -Peter From aahz at pythoncraft.com Sun Mar 31 20:36:55 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 20:36:55 -0500 Subject: New-style exceptions? References: Message-ID: In article , Raymond Hettinger wrote: >"Aahz" wrote in message >> Magnus Lie Hetland wrote: >>> >>>Is there a reason why new-style objects can't be used in the raise >>>statement? >> >> Because that's the way it currently works. Inherit from Exception and >> Bob's your uncle. > >Is there a reason why Exception can't be defined to inherit from >'object' so that Uncle Bob does the right thing? Patience, grasshopper, patience. It will be at least another version or two before any classic classes get converted to new-style classes, and I doubt Exception would be the first. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From wayne at mishre.com Sun Mar 3 23:43:15 2002 From: wayne at mishre.com (Wayne Pierce) Date: Sun, 03 Mar 2002 20:43:15 -0800 Subject: Snack mod for python References: Message-ID: <3C82FB63.60007@mishre.com> Russell Voutour wrote: > Hi i'm using the Snack sound module for python and i've run into a problem and > was wondering if anyone had ever used it before. It installed find but when i use > the .play() method it tries to open my /dev/dsp and it gets a error because the > device does not exists it's under dev/sound/dsp. i've looked in the tkConfig file > and the tclConfig file and can't find anything any sugestions would be helpfull > thanks Ok, so I'm going to show some clueless-ness here...but can you just link /dev/dsp to /dev/sound/dsp? Granted this may not be the "best" way to do it...but if /dev/dsp isn't used then it might work...keyword is might. Wayne -- Wayne Pierce web: http://www.mishre.com email: wayne at mishre.com "What you need to know." From python at rcn.com Sat Mar 2 03:46:52 2002 From: python at rcn.com (Raymond Hettinger) Date: Sat, 2 Mar 2002 03:46:52 -0500 Subject: map-like function on dict values? References: Message-ID: "Skip Montanaro" wrote in message news:mailman.1014929989.16553.python-list at python.org... > > def mapvalue(f, d): > keys = d.keys() > map(operator.setitem, [d]*len(keys), keys, map(f, d.values())) > The mapvalue test needs a tune-up. Skipping the operator module and calling setitem directly speeds things up a bit: def tunedmap(f, d): return map( d.__setitem__, d.keys(), map(f, d.values()) ) I re-timed the result and it was close to the same as achieved for iteriteritems. Raymond Hettinger From cfelling at iae.nl Fri Mar 1 19:31:42 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 2 Mar 2002 01:31:42 +0100 Subject: string to dictionary References: Message-ID: les ander wrote: > Hi, > i have a list of strings like this: > aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3',...] > i want to convert this to a dictionary with a_i -> b_i without > using loops (it is trivial to do it with loops) > i tried this > dict={} > map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList) try: >>> map(lambda x: d.__setitem__(*x), [x.split() for x in aList]) [None, None, None] >>> d {'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'} of with 2.2: >>> d = dict([x.split() for x in aList]) >>> d {'a_3': 'b_3', 'a_2': 'b_2', 'a_1': 'b_1'} -- groetjes, carel From greg at cosc.canterbury.ac.nz Tue Mar 19 21:27:23 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Wed, 20 Mar 2002 14:27:23 +1200 Subject: For loops with explicit indices -- again References: <3c9789ed$0$29676$ba620e4c@news.skynet.be> Message-ID: <3C97F38B.6631F75C@cosc.canterbury.ac.nz> Armin Rigo wrote: > > it = iter(lst) > for x in it: > if x>0: > lst[it.count-1] -= 1 I find this ugly, particularly the need to use count-1 rather than just count. It's just begging for off-by-one errors. > it.count += 1 # skip next element > it.count -= 1 # process the same element again > it.count = 0 # full rewind > it.count -= 1; del lst[it.count] # remove bad item from list This is even worse! It's tantamount to modifying a loop control variable inside the loop, which is widely regarded as a Bad Thing To Do from a maintainability standpoint. If the ability to modify the count is dropped, I see nothing that can't be achieved more elegantly using an iterator-wrapper such as the proposed indexed() function that returns (index, value) pairs. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From donn at u.washington.edu Mon Mar 18 18:22:11 2002 From: donn at u.washington.edu (Donn Cave) Date: 18 Mar 2002 23:22:11 GMT Subject: os.popen4 and exit codes References: <3C966B18.BB1E81BD@bgb.cc> Message-ID: Quoth Don Garrett : | My understanding for the popen2-4 functions was that they returned the exit | code as the result of the last related call to close(). This seems to be | working for me under Windows, but not Linux. This is the inverse of what I | would expect. | The close DOES return the exit code when I use os.popen(), but I need to be | able to capture stderr. On UNIX, popen3 is implemented in Python, out of fork and pipe functions, and unlike popen it returns 100% stock, common file objects. To get exit status, you have to use the Popen3 class explicitly, so you can call its wait() function. Donn Cave, donn at u.washington.edu From lac at strakt.com Sat Mar 9 13:09:25 2002 From: lac at strakt.com (Laura Creighton) Date: Sat, 09 Mar 2002 19:09:25 +0100 Subject: PEP 284, Integer for-loops (code bash?) In-Reply-To: Message from Michael Chermside of "Mon, 08 Apr 2002 11:10:03 EDT." <3CB1B2CB.4050601@destiny.com> References: <3CB1B2CB.4050601@destiny.com> Message-ID: <200203091809.g29I9QtB024853@ratthing-b246.strakt.com> > Laura Creighton writes: > > I think that it > > would have been nice if when Guido was designing the language he > > used Haskall's syntax for loops. But he didn't. > > I *still* haven't found time to learn Haskall, and a quick browse of the > docs didn't get me anywhere. Can you summarize what Haskall's syntax > for loops IS? I realize this is a little off topic, but I'm curious. > > -- Michael Chermside > 1. Michael! Your Computer thinks its April! You are making python archives one month ahead of yourself! (see: http://mail.python.org/pipermail/python-list/2002-April/091714.html) 2. Haskell, which I mispelt, shame on me, I know better, is a functional language. It has functional syntax - don't go there looking for a 'for loop'. However, it also has list comprehensions, (which is where we got them from, I think). So, what I meant was 'I wish that Guido had used Haskell's syntax for arithmetic sequences in Python's for loops'. That is as follows: [1..10] => [1,2,3,4,5,6,7,8,9,10] [1,3..8] => [1,3,5,7] [1,3..] => [1,3,5,7,9, ... (infinite sequence) This is not restricted to numbers, char works great. ['A','B'..'Z'] => the upper case letters in English in alphabetical order you can also roll your own: If you make a user-defined enumerated class, such as statWisdom, you can use it like this: [inane..enlightened] => [inane, stupid, idiotic, uneducated, educated, learned, wise, enlightened] I have probably forgotten something, somebody else can add it. 3. Make the time to learn Haskell. It is simply too much fun. Laura Creighton From peter at engcorp.com Mon Mar 25 19:46:35 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 19:46:35 -0500 Subject: RELEASED: Python 2.2.1c1 References: Message-ID: <3C9FC4EB.B92DCFB8@engcorp.com> mo wrote: > > > Michael Hudson writes: > > > > > Depending on how many problems are found in this release, 2.2.1 > > > final or a second release candidate will follow next week. > > > > It will be 2.2.1c2 and it will be released in about 22 hours time. > > This is like pacing outside a delivery room. Thank you for this > update. More importantly, thanks to all of you "Doctors" laboring on > our behalf. Since when do _doctors_ do the "labor"? ;-) -yo-momma-ly yr's, Peter From hamish_lawson at yahoo.co.uk Sun Mar 10 11:34:45 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 10 Mar 2002 08:34:45 -0800 Subject: import gadfly causes 500 Server Error -- anyone know how to fix? References: <3C8AFB43.275714BB@erols.com> Message-ID: <915a998f.0203100834.6a247558@posting.google.com> > I discovered that adding the "import gadfly" statement results > in: > > 500 Server Error If you are using Python 2.2, you can make use of the now-standard cgitb module to get a traceback report of the problem sent to your browser. Put the following lines as early in the program as you can: import cgitb cgitb.enable() Once you can see a fuller report of the problem you will be that much closer to a solution. For earlier versions of Python see http://web.lfw.org/python/ to get hold of cgitb and instructions on how to deploy it. Hamish Lawson From store_li at sina.com Mon Mar 4 10:42:06 2002 From: store_li at sina.com (Ricky) Date: Mon, 4 Mar 2002 23:42:06 +0800 Subject: How can I use a foreign language char in Swing References: Message-ID: I sorry to post on the wrong newsgroup. Any way,thank you for any help! "Ricky" wrote in message news:a5uoj2$a4su5$1 at ID-12869.news.dfncis.de... > I installed J2SDK 1.4.0 several days ago. I need to get some strings from > database which stored in GB2312 encode method, and display it using Swing. I > got correct result in Windows2000(Use China as default region and GB2312 as > encode method.) While I??run it on Windows(English Edition), all I can see > is ?????. > > What should I do? I think ResourceBoundle can't help me. Is there any other > method can help me? > > > > From newsfroups at jerf.org Mon Mar 11 20:12:08 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Tue, 12 Mar 2002 01:12:08 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: Message-ID: <3C8D5580.8020306@jerf.org> Andrew Koenig wrote: > Rather, it seems to me that Microsoft is saying that they will not > allow their products to be used in any way that might potentially > compel Microsoft to disclose any of their own source code. This is true. The FUD lies in the fact that this is a chimera. It does not matter what *I* do with free software and Microsoft software. Nothing I do can possibly compel Microsoft to do *anything*. Any theoretical activity I may wish to do that might require the release of Microsoft code is not *legal* for me to engage in, because it requires rights I don't have. And even if I did engage in this activity, I woud be in violation of the law, and MS would *still* be obligation free. There is no way Microsoft does not know this. There is no way the lawyer(s) writing this did not know that. The stated concerns are absurd; thus, the only logical conclusion is that MS is trying to spread the ***blatent*** falsehood that some user somewhere of your software may strip you of your software rights. I'm not an "MS Hater", but I call 'em like I see 'em. From sjmachin at lexicon.net Sat Mar 23 06:39:59 2002 From: sjmachin at lexicon.net (John Machin) Date: 23 Mar 2002 03:39:59 -0800 Subject: Sorting distionary by value References: <7xd6xwntgx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7xd6xwntgx.fsf at ruckus.brouhaha.com>... > Artur Skura writes: > > No, and it seems the problem is not with sorting. > > I wanted to write a compact word counting script (well, in shell > > it can be done in a 5 lines or so), just for fun. > >... > > for i in a: > > if i not in known: > > This is horrendously slow because for every input word, you're comparing > it against all the previously seen words. Horrendously slow can be better than not at all. > > > it seems it's slow not because of sorting... > > Correct. I didn't examine your code carefully enough to be sure, but > what I think you want is something like this: > > counts = {} > a = string.split(open(sys.argv[1],'r').read()) > for w in a: > if counts.has_key(w): > counts[w] += 1 > else: > counts[w] = 1 > > words = counts.keys() > words.sort() > words.reverse() > > for w in words: > print words[w], w Sorry, but this doesn't work. If you were to actually *run* your code, you would get this result [after adding import string, sys at the start of the script]: print words[w], w TypeError: sequence index must be integer At this stage "words" will be bound to something like ['zot', 'foo', 'bar'] and you are trying to access words['zot'] but "words" is a list not a dictionary -- unlike in some other languages of which you may have heard, like awk, they are different concepts in Python. The problem starts back further with "counts.keys()". You need to use the .items() method to get both the keys and the values out of the dictionary, in a list of 2-tuples, like [('foo', 1), ('bar', 666), ('zot', 42)]. Then you need to fiddle with this list to bring the count to the front of each tuple so that it can be the primary sort key. For more information, google('Schwartzian transform Martelli') either web-wide or in comp.lang.python. If as is usual the result is to be presented in descending order of frequency, some care is required so that words with the same frequency don't come out in reversed order. Try replacing the last part of the script with: words = [(-count, word) for word, count in counts.items()] words.sort() for count, word in words: print word, -count HTH, John From op73418 at mail.telepac.pt Sat Mar 2 22:13:52 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sun, 03 Mar 2002 03:13:52 +0000 Subject: PEP 276 -- What else could iter(5) mean? References: <2e138uoj0kivrqbju7c1oimt6fpv03bpgr@4ax.com> Message-ID: On Sun, 03 Mar 2002 02:09:50 +0000, Gon?alo Rodrigues wrote: >On Sat, 02 Mar 2002 17:47:00 -0800, David Eppstein > wrote: > >>Here's another way of looking at the same question. >>An iterable object has a next() function, that's what it means to be >>iterable. If numbers are iterable, we can call number.next(), right? >>So what should 5.next() be? Surely anyone familiar with the Peano axioms >>would say 6, not 0! > >Let me add the following example on my post: > >>>> class Bogus: >... def __init__(self, n): >... self.n = n >... def __iter__(self): >... return range(n) >... >>>> a = Bogus(10) >>>> a.next() >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: Bogus instance has no attribute 'next' >>>> As you have probably noticed there is an EGREGIOUS error in the above. My apologies for it (Is past 3 a.m. ...). It should go as >>> class Bogus: ... def __init__(self, n): ... self.n = n ... def __iter__(self): ... return range(self.n) ... >>> a = Bogus(6) >>> a.next() Traceback (most recent call last): File "", line 1, in ? AttributeError: Bogus instance has no attribute 'next' >>> From BPettersen at NAREX.com Fri Mar 29 21:10:46 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 29 Mar 2002 19:10:46 -0700 Subject: Another stab at a "switch/case" construct (for Python 3000): Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158DC3@admin56.narex.com> > From: Steven Majewski [mailto:sdm7g at Virginia.EDU] > > On Fri, 29 Mar 2002, Bjorn Pettersen wrote: > > > > From: Steve Lamb [mailto:grey at despair.dmiyu.org] > > > > > > its_called_a_directory_pointing_to_functions = {'case':closed} > > > > > > I do not believe that any language which can have a hash > > > of function pointers has any business with a case statement. > > > > But that only works when all the functions in all the branches take the > > same number and types of arguments -- hardly the general case. > > > > table = {} > > table[key] = func, (args,...) > ... > > def doit( k ): > return table[k][0]( *table[k][1] ) Point taken, but is this an argument for or against the match/switch statement ? Personally, I don't think it's worth adding a match statement unless we can have ML style pattern matching... Not-sure-what-a-good-Pythonic-spelling-would-be-though'ly y'rs -- bjorn From maxm at mxm.dk Tue Mar 19 04:10:21 2002 From: maxm at mxm.dk (Max M) Date: Tue, 19 Mar 2002 09:10:21 +0000 Subject: Pure python alternative to mx.DateTime? References: Message-ID: <3C97007D.6000605@mxm.dk> Lutz Schroeer wrote: > One of my web hosts does not have a C compiler installed so I can't install > mx.DateTime on that machine, because it need some C routines. > > Unfortunately I'm in need of some simple time and date calculations > (ISO-time, how many days from now, weekdays, etc.). > > Is there any alternative to mx without inventing the wheel for the second > time and programming it by myself? Hmm you could just pull out the DateTime module from Zope. It is not as well developed as the mx tools, but will probably do what you need. I just looked at it, and it doesn't seem to be dependent on anything in Zope. regards Max M From tdelaney at avaya.com Wed Mar 6 18:11:48 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 7 Mar 2002 10:11:48 +1100 Subject: PEP 276 -- What else could iter(5) mean? Message-ID: > From: James_Althoff at i2.com [mailto:James_Althoff at i2.com] > > [Bernhard Herzog] > > That's not quite right, I think :) > > > > [f(x) > > for x in range((4 in range(3)) in range((2 in range(3)))) > > if x in range((x+1 in range(x*2)))] > > > > would me more like it (but it's late so there may still be > a mistake :) ) > > Thanks (I think ). > > > [James Althoff] > > Can you suggest a less contrived example that might be a problem? > [Bernhard Herzog] > > x, = 1 > > > > would assign 0 to x instead of raising an error. > > Agreed. Note that this example has been in the PEP from the > beginning. And in my opinion would be something that should be checked by PyChecker ... Tim Delaney From jason at jorendorff.com Mon Mar 4 05:49:30 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 4 Mar 2002 04:49:30 -0600 Subject: How can I use a foreign language char in Swing In-Reply-To: Message-ID: Martin v. Loewis wrote: > "Jason Orendorff" writes: > > 1. Missing Fonts. Seems unlikely. But if this is the problem, > > it's easy to fix. :) > > Actually, this is quite likely: MS normally choses "?" as the > replacement character, and you need to explicitly request CJK fonts > when installing the English edition of W2k. If "Windows" really means > "W9x" in this context, things are probably even worse. Wow, really? I know next to nothing about it - but it feels as though I once heard that fonts have an explicit "i-am-stumped" glyph, usually an empty box... In any case, under Swing, it seems empty blocks are used as placeholders for characters that are not present in any font. (I had thought that installing the Java 1.4 SDK installs at least one rather comprehensive Unicode font, but on tinkering around just now, it seems many scripts aren't included. Blah.) It also seems that Java likes to convert unrecognized bytes to '?'s when decoding. So: yes, missing fonts are a much more likely problem than I guessed -- but I suspect that there's also a problem with encodings somewhere. (sigh) ## Jason Orendorff http://www.jorendorff.com/ From sjmachin at lexicon.net Fri Mar 1 07:07:26 2002 From: sjmachin at lexicon.net (John Machin) Date: 1 Mar 2002 04:07:26 -0800 Subject: Apology to Bill Gates (was Re: ASV module, CVS modules) References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: sjmachin at lexicon.net (John Machin) wrote in message news:... > > my_data.input_from_file("c:\test_data.csv", ASV.CSV(), > > File "C:\PYTHON22\ASV.py", line 222, in input_from_file > > file = open(input_file, "rb") > > IOError: invalid argument: rb > Bill behaving badly: Seems like Bill chucks a wobbly if there is > a_bloody_tab_character in a file name. I could be maligning Bill > unjustly; could be GvR & Co -- I'll have a look at the Python source > in a minute -- but I'd bet a couple of pots of beer that it's down to > Bill. Looks like the Windows compiler runtimes, enforcing the (sensible, IMO) Windows rule that file names shouldn't have "unprintable" characters in them, are faced with signalling the error with a least-bad choice of errno: ENOENT ("No such file or directory") or EINVAL ("Invalid argument"). Borland chose ENOENT, MS chose EINVAL. Python, starting from a Unix background, where there is evidently no such thing as an invalid character in a file name, can only imagine that EINVAL must refer to the mode argument, and in fact special-cases EINVAL (see below) to produce the error message that baffled (inter alia) the OP. if (errno == EINVAL) PyErr_Format(PyExc_IOError, "invalid argument: %s", mode); else PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); However given what Tim P. said in a recent posting, I won't add to the patching bottleneck by rushing off to file an enhancement request on this one. From skip at pobox.com Tue Mar 26 06:08:49 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 26 Mar 2002 05:08:49 -0600 Subject: Memory Error while simulating matrix In-Reply-To: References: Message-ID: <15520.22209.295989.738490@12-248-41-177.client.attbi.com> slick> When i execute the code(part of an algorithm code) given below, i slick> get a MemoryError. row = [] # list row = [0] * 1000000 # each row contains million columns matrix =[] # contains a collection of rows for i in range(1000): # creating a matix of 1000 rows each matrix.append(row[:]) # having a million columns You are trying to create 1,000 lists, each with 1,000,000 elements, or 10**9 4-byte object pointers, so at minimum you will be chewing 4GB of virtual memory, probably much more once your matrix becomes a bit less uniform. To keep from getting a MemoryError you should have at least that much swap space. Actually much more. Integer overhead is 12 bytes per object. (Float overhead is 16 bytes per object.) Assuming most of the elements of your matrix are not recycled integers between -1 and 100, your memory consumption will be closer to 20GB than 4GB. Obviously, you can use the array module or NumPy. Both of those are going to push the memory consumption closer to the 4GB end of things. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From I.j.w.Wever at student.tnw.tudelft.nonsense.nonsense.nl Fri Mar 29 09:35:57 2002 From: I.j.w.Wever at student.tnw.tudelft.nonsense.nonsense.nl (Fused) Date: Fri, 29 Mar 2002 14:35:57 GMT Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: <3ca47917.18551297@news.tudelft.nl> Two replies in a message: Pearu Peterson wrote: > >Great! How about implementing Delphi to Python translator? >Basically, you'll need to write a parser that reads Delphi (OOP) code and >then translates it to the corresponding Python code. >There are many yacc/lex type of packages already available that will ease >this job. I recommend PLY > http://systems.cs.uchicago.edu/ply/ > That would be very satisfactory to implement. However, I think I'd spend lots of time on understanding lex/yacc and meticulously analysing the Delphi grammar and less time actually building something in Python. Then again, almost every non-trivial program requires acquiring additional knowledge. Interesting idea, thanks. "Steve Holden" wrote: > >I'd really like to see a Python mail/newsreader. That would teach you a lot, >and keep you busy for a while... > It would teach me indeed, especially since I know next to nothing about mail/news protocols :) But why would you specifically want a Python mail/newsreader, when there are plenty of good mail/newsreaders around? From borcis at geneva-link.ch Mon Mar 11 09:35:58 2002 From: borcis at geneva-link.ch (Boris^2) Date: Mon, 11 Mar 2002 15:35:58 +0100 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> Message-ID: <3C8CC0CE.50509@geneva-link.ch> Hans Nowak wrote: > Eric Brunel wrote: > >>Hi all, >> >>Found the following link on comp.lang.tcl. A bit long, but worth reading... >> >>http://groups.google.com/groups?hl=en&selm=3B40A4A7.6E39BD%40brad-aisa.com&rnum=1 >> > > It's not April 1st yet... What sounds really like April 1st is M$ naming open source software (rather than, eg, Outlook or Windows) "potentially viral software". Cheers, Boris Borcic From uwe at rocksport.de Tue Mar 26 05:49:46 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 26 Mar 2002 10:49:46 GMT Subject: wxPython and wxFlexGridSizer problem References: <3C9FBE22.A72B4A27@ccvcorp.com> Message-ID: Jeff Shannon wrote: | Are you sure that you want to use ShowModal()?? How are you setting up your | window? | This function looks okay to me, as far as it goes, but it's hard to say what | might be going on if we don't know where window is coming from. I presume that | it's a wxDialog of some sort? If so, why aren't you subclassing wxDialog and | putting this code in your __init__(), then calling ShowModal() from the function | that creates the dialog? I got the answer in the wxwindows-group: there is just a window.Layout() call missing. Thats it and everything is fine.. Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From justin at iago.org Thu Mar 7 11:12:44 2002 From: justin at iago.org (Justin Sheehy) Date: Thu, 07 Mar 2002 11:12:44 -0500 Subject: PEP 276 -- What else could iter(5) mean? References: <6qpu2gzktu.fsf@abnoba.intevation.de> Message-ID: Bernhard Herzog writes: > Do we really want all of these new behaviors? No. Please, no. I still don't see what this proposal provides in terms of a real gain in order to offset the obvious potential for ugliness, mistakes, and the appearance of ambiguity. Not having to type "range" or "xrange" doesn't count as a real gain. The PEP describes having to use range in this context as a wart, but I don't remember it ever being referred to as such before this PEP. -Justin From sdm7g at Virginia.EDU Thu Mar 21 16:03:41 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Thu, 21 Mar 2002 16:03:41 -0500 (EST) Subject: How Can I Determine the Operating System with Python? In-Reply-To: Message-ID: On Thu, 21 Mar 2002, David Eppstein wrote: > In article , > Cliff Wells wrote: > > > > >>> os.environ['OS'] > > > 'Windows_NT' > > > > > > No idea what it does on other platforms. > > > > It depends upon whether the environment variable "OS" is present, so it's > > probably less reliable than sys.platform (doesn't exist on RH Linux, at > > least). > > Another one where os.environ['OS'] doesn't exist: > > >>> import sys > >>> sys.platform > 'mac' > >>> import os > >>> os.environ > {} > >>> os.name > 'mac' > > Not sure how you're supposed to distinguish Classic from Darwin... On OSX, running the command-line (unix) mach-o python: Python 2.2.1c1 (#1, Mar 19 2002, 02:06:22) [GCC 2.95.2 19991024 (release)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os,sys >>> sys.platform 'darwin' >>> os.name 'posix' But running the carbonized MacPython on OSX yields same as Classic: Python 2.2 (#123, Dec 22 2001, 00:11:59) [CW CARBON GUSI2 THREADS GC] on mac Type "copyright", "credits" or "license" for more information. >>> import sys,os >>> sys.platform 'mac' >>> os.name 'mac' -- Steve Majewski From jochen at unc.edu Tue Mar 19 20:06:07 2002 From: jochen at unc.edu (Jochen =?iso-8859-1?q?K=FCpper?=) Date: 19 Mar 2002 20:06:07 -0500 Subject: Python 2.2 seriously crippled for numerical computation? In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sat, 09 Mar 2002 00:17:40 -0500 Tim Peters wrote: Tim> I hope the bogus underflow problem is fixed in CVS Python now. Tim> Since my platform didn't have the problem (and still doesn't, of Tim> course), we won't know for sure until people try it and report Tim> back. Ok, looking at SourceForge and google this seems to be fixed in cvs HEAD. Would it be possible to put the same patch into the cvs python-2.2 branch, please? [1] Greetings, Jochen Footnotes: [1] If it is in there, it doesn't work for me with current python cvs branch release22-maint. I still have to manually add -lieee. (RedHat-7.0 with current updates.) - -- University of North Carolina phone: +1-919-962-4403 Department of Chemistry phone: +1-919-962-1579 Venable Hall CB#3290 (Kenan C148) fax: +1-919-843-6041 Chapel Hill, NC 27599, USA GnuPG key: 44BCCD8E -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6-cygwin-fcn-1 (Cygwin) Comment: Processed by Mailcrypt and GnuPG iEYEARECAAYFAjyX4IAACgkQiJ/aUUS8zY52jgCbB69a8KZmCuk9MYIKzNu7EpBR 3fIAmQEYH1/ipB7OoiBcBPIAHev3dRlU =5l6n -----END PGP SIGNATURE----- From olc at ninti.com Sun Mar 31 16:34:30 2002 From: olc at ninti.com (Michael Hall) Date: Mon, 1 Apr 2002 07:04:30 +0930 (CST) Subject: relational database? In-Reply-To: Message-ID: I find MySQL very easy to set up and use with Python (and PHP). All you need is the MySQLdb module ... easy to install and use. Mick On Sun, 31 Mar 2002, Trung Hoang wrote: > What relational database is easy to setup and use with python? besides msql > (im having some problems) > > Cheeeers.. > trungie > > > > > ----------------------------- Michael Hall mick at ninti.com ----------------------------- From martin at v.loewis.de Wed Mar 20 01:40:33 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 20 Mar 2002 07:40:33 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) writes: > I know there are several solutions available for building standalone > binary executables from Python programs (Freeze, py2exe, McMillan > Installer, etc.) -- I just wondered if it would be possible to add > functionality like this to distutils? That is certainly possible; freeze would be the obvious choice for such a mechanism (IMO). Alas, distutils is unmaintained, so don't wait for anybody else to implement it for you. Regards, Martin From joonas at olen.to Tue Mar 12 05:57:10 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Tue, 12 Mar 2002 10:57:10 GMT Subject: IDv2/IDv3 Tag on mp3-files References: Message-ID: <3C8DDFDC.7090601@olen.to> Andreas Penzel wrote: > Hello NG! > > Is it possible, to read the IDv2 or IDv3 Tag from mp3-files? Yes, it is. http://id3-py.sourceforge.net/ From peter at engcorp.com Fri Mar 29 22:30:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 22:30:45 -0500 Subject: execfile() - change python version? References: Message-ID: <3CA53165.E3A765A4@engcorp.com> Trung Hoang wrote: > > Hi, > > i was wondering if there is a way to change which version of python > processing the file when execfile(). No. execfile() is basically "execute this file using the currently running version of Python". > i wish to use python2.2 on the main file, and python2.1 on the file passed > into the argument of execfile(). Don't use execfile(). Use os.system() and run the version you want instead. > reason being: there is some sort of mis configuration error on the server i > am using python on. Sounds like there must be an easier way to solve the problem. Can you give more detail on this "misconfiguration error"? From jason at jorendorff.com Mon Mar 11 05:24:31 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 11 Mar 2002 04:24:31 -0600 Subject: python name spaces In-Reply-To: Message-ID: > I must admit I am frustrated by Python's seeming lack of powerful name > space support. For example, in Perl I can do something like this, > > [...] > > Arbitrarily creating variables and subroutines with different scopes. > (The actual example seems silly, but really isn't.) Oh yes it is. Give a realistic example, and maybe you'll get a decent response. Until then, http://groups.google.com/groups?selm=000701bde83f%249e2bdba0%24589e2299%40ti m ## Jason Orendorff http://www.jorendorff.com/ From philh at comuno.freeserve.co.uk Tue Mar 12 16:54:05 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Tue, 12 Mar 2002 21:54:05 +0000 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8D5580.8020306@jerf.org> Message-ID: On Tue, 12 Mar 2002 01:12:08 GMT, Jeremy Bowers wrote: > >There is no way Microsoft does not know this. Indeed so. >There is no way the >lawyer(s) writing this did not know that. The stated concerns are >absurd; thus, the only logical conclusion is that MS is trying to spread >the ***blatent*** falsehood that some user somewhere of your software >may strip you of your software rights. Lying to get money = fraud I think MicroShit's directors and laywers should be banged up for a few years. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From jeff at ccvcorp.com Fri Mar 22 14:04:34 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 11:04:34 -0800 Subject: Newspaper infiltration References: Message-ID: <3C9B8042.81117726@ccvcorp.com> Neil Hodgson wrote: > It appears that some Python force is contaminating the ordinarily > technically challenged mainstream Australian press. First we get an > Interview with Mark, then this Zope article turns up on the second page of > the IT section of the local paper: > http://www.it.mycareer.com.au/news/2002/03/19/FFXF7G6VSYC.html > > Could it be a sleeper from the And it appears that that entire site has been redirected. Coincidence? I doubt it. ;) Jeff Shannon Technician/Programmer Credit International From chris.gonnerman at newcenturycomputers.net Sat Mar 9 00:19:02 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 8 Mar 2002 23:19:02 -0600 Subject: PEP Parade References: <3C895594.60601@sneakemail.com> Message-ID: <00a801c1c729$f1ae40c0$0101010a@local> ----- Original Message ----- From: "Joshua Macy" > > Just out of curiosity, what does the rest of your group develop in > then? FORTRAN? COBOL? ("and none of this ANSI85 crap, either...it gets > old trying to hit a moving target!") Yeah, but "major" language standards change every few years... Python releases come about 1-2 per year. We have to resist the urge to change something major in the core too frequently. From huaiyu at gauss.almadan.ibm.com Mon Mar 4 16:57:02 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 4 Mar 2002 21:57:02 +0000 (UTC) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: On Sun, 03 Mar 2002 00:44:50 +0100, Alberto Griggio wrote: > >#include >#include >#include >#include > >int main(void) >{ > double d; > errno = 0; > d = pow(1e-200, 2); > if(!errno) printf("OK: %f\n", d); > else printf("Error: %d, %s\n", errno, strerror(errno)); > return errno; >} > >prints: Error: 34, Numerical result out of range > >On slackware 8.0, GCC 2.95.3, libc 2.2.3, both the python and the C >code fail. > >Finally, if you change pow to powf in the C code above, it gives no >error. > >Hope someone can understand what's happening... It's more strange than first thought. This produce errno 34 on BOTH the following systems, but one raises exception while the other does not. Red Hat 6.1 upgraded piecewise to 7.1: C produce errno 34, but Python 2.2 does not raise. SuSE 7.1: C produce errno 34, and Python 2.2 raise. Details here $ python Python 2.2 (#1, Feb 28 2002, 16:44:48) [GCC 2.95.2 19991024 (release)] on linux2 $ rpm -q gcc glibc gcc-2.95.2-149 glibc-2.2-7 Can someone please expand on the above C program to test from other possible culprits? Huaiyu From tejarex at yahoo.com Sat Mar 23 11:11:54 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 23 Mar 2002 16:11:54 GMT Subject: Info needed on metaclasses / type-ing References: Message-ID: "Dimitris Garanatsios" wrote in message news:a7i109$ufh$1 at ulysses.noc.ntua.gr... > I recently browsed through an unfinished book of Bruce Eckel, "Thinking in > Python", Revision 0.1.2 > I found the following peace of code there: > class SingletonMetaClass(type): ... > My question is about the "SingletonMetaClass" class. > I have tried in the past to create my own types using Python and just could > not find a way of doing that since built-in type objects' structure where > not documented. > > The "SingletonMetaClass though", as far as i can understand, please help me > with that, is doing exactly what i wanted: a new type definition. Actually, you can new derive new types from old without using the more complex metaclass machinery. See below. > I browsed Python's manuals to find more about the attributes and functions > that are used, but found nothing... ... Everything you ask about is new to Python 2.2. Did you search *that* manual? Look in "What's new for Python 2.2" (or something like that) and read the GvR essay referenced therein which is a semi-tutorial on the new type/class stuff. Terry J. Reedy From phil at river-bank.demon.co.uk Sat Mar 23 19:56:29 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sun, 24 Mar 2002 00:56:29 +0000 Subject: ANNOUNCE: PyQt v3.1 Released Message-ID: <3C9D243D.8E24763C@river-bank.demon.co.uk> PyQt v3.1 is available to download from http://www.riverbankcomputing.co.uk/pyqt/download.php. PyQt is the set of Python bindings to Trolltech's GUI toolkit and contains 300 classes and over 5,750 functions and methods. Classes include access to Qt's XML parser, SQL support, as well as a comprehensive range of user interface widgets. PyQt supports all versions of Qt under Windows and UNIX/Linux, and Qt/Embedded for the Sharp Zaurus and the Compaq iPAQ. Binary packages are provided for the non-commercial edition of Qt under Windows and for the Zaurus (which may also work with the iPAQ). Changes in this release include... - support for Qt's thread classes - support for Qt/Embedded - addition of the qtpe (Qt Palmtop Environment) module Included with PyQt is pyuic which generates Python code from GUIs created with Qt Designer. Boudewijn Rempt's book on programming with PyQt can be found at http://stage.linuxports.com/projects/pyqt/. SIP v3.1 (the bindings generator used to create PyQt) is also available at http://www.riverbankcomputing.co.uk/sip/download.php. Note that the SIP run-time library is now implemented as a Python extension module. You should probably remove any earlier version before upgrading. http://www.riverbankcomputing.co.uk is the new home of SIP, PyQt and PyKDE. Phil From tim.one at comcast.net Thu Mar 21 01:29:52 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 21 Mar 2002 01:29:52 -0500 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) In-Reply-To: Message-ID: [Martin v. Loewis] > ... > Since March 2001, 30 distutils bugs have been closed, so one out > of three distutils bugs is still pending (for Python in general, the > ratio is 1:9). Dang, disutils is *still* winning! I was hoping to drive Python down to 1:2, but we just aren't getting enough HP-UX and AIX users to drive us to total despair. OK, how about everybody try threads, whether they understand threads or not (well, *especially* if not), and file a vague yet irate bug report for every behavior they don't fully understand? Throw some signals into the mix too. And GNU readline! If that ran on more platforms, we'd have plenty of chronic bug reports to push us over the coveted "give up" threshold. i-have-a-dream-ly y'rs - tim From r.salz at verizon.net Thu Mar 21 11:00:27 2002 From: r.salz at verizon.net (Rich Salz) Date: Thu, 21 Mar 2002 16:00:27 GMT Subject: #define equivalents and config files References: <3C9963BD.1040304@verizon.net> <3C9964FF.46805590@engcorp.com> Message-ID: <3C9A03A6.2020601@verizon.net> So are they #define's, which are compile-time read-only constants (hence my solution which allows runtime enforcement of read-only-ness :), or are they default values you can get and set from a config file (use the library module as others mentioned)? /r$ From mwh at python.net Thu Mar 7 05:39:07 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Mar 2002 10:39:07 GMT Subject: Python/C - Memory-Management References: Message-ID: heiko.wolf at dlr.de (Heiko Wolf) writes: > Hi there, > > I've got some C-functions that shall be adressed from Python. Thats no > problem, thanks to SWIG. > > But now there is a problem about the memory management: One of the > C-functions allocates memory for all the other functions. In C it > works that way: [snip] > If another function calls init_mem, it can use memory until free_mem > is called... I want to do the same now in Python, but it seems as if > the static memory isnt kept somewhere? When I try accessing it, I > get a Segmentation Fault... Any suggestions? No. More details? Cheers, M. -- > so python will fork if activestate starts polluting it? I find it more relevant to speculate on whether Python would fork if the merpeople start invading our cities riding on the backs of giant king crabs. -- Brian Quinlan, comp.lang.python From logiplexsoftware at earthlink.net Fri Mar 29 16:57:59 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 29 Mar 2002 13:57:59 -0800 Subject: Another stab at a "switch/case" construct (for Python 3000): In-Reply-To: References: <3ca33c88@news.mhogaming.com> Message-ID: <20020329135759.6050a0e0.logiplexsoftware@earthlink.net> On Fri, 29 Mar 2002 21:11:48 -0000 Steve Lamb wrote: > On Fri, 29 Mar 2002 10:48:15 GMT, Benjamin Schollnick wrote: > > IF X == 0: > > DO_THIS () > > ELIF X == 2: > > DO_THIS (2) > > ELIF X == 4: > > DO_THIS (X+2) > > ELIF Y == 6: > > DO_THIS() > > ELIF Z == "ZEBRA": > > DO_THIS ( ZEBRA ) > > ELSE: > > DO_NOT_DO_THIS () > > > > But, this routine is not exactly readable compared to a case: > > > CASE X of: > > 0 : DO_THIS() > > 2 : DO_THIS (2) > > 4 : DO_THIS (x+2) > > 6 : DO_THIS () > > ELSE: > > DO_NOT_DO_THIS() > > its_called_a_directory_pointing_to_functions = {'case':closed} > > I do not believe that any language which can have a hash of function > pointers has any business with a case statement. The case statement is definitely cleaner than the if/elif/else construct. I'd have to agree with Steve Lamb that you can use hash pointers, so you could also do (lambdas necessary to duplicate above case statement): { # case x of 0: lambda x: do_this(), 2: lambda x: do_this(2), 4: lambda x: do_this(x + 2), 6: lambda x: do_this(), }.get(x, lambda x: do_not_do_this())(x) But I'm not sure that this is very clear code (at least not at first glance). I don't feel that passionate either way on the subject. Probably having a case statement would make some things clearer but might also encourage less though out approaches to problems. Situations where you must test for many individual values are usually an indication that your solution isn't general enough. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From emile at fenx.com Sat Mar 23 08:24:22 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 23 Mar 2002 05:24:22 -0800 Subject: Extending the interactive mode [not really an ANN :) ] References: Message-ID: "Tjabo Kloppenburg" wrote in message news:mailman.1016879616.31903.python-list at python.org... > hi, > > I use python22 and dreamt about a comfortable way of using the interactive > mode to find information about what methods/functions a class/module provides > and what the helpful __doc__ string says (keeping ri [ruby] in my mind). > Do you know about help? >>> help (sys.exit) Help on built-in function exit: exit(...) exit([status]) Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status numeric, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure). -- Emile van Sebille emile at fenx.com --------- From logiplexsoftware at earthlink.net Mon Mar 11 17:48:19 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Mon, 11 Mar 2002 14:48:19 -0800 Subject: Using doctest and executing a process In-Reply-To: <10d46bdc.0203111449.6bd761f5@posting.google.com> References: <10d46bdc.0203111449.6bd761f5@posting.google.com> Message-ID: <20020311144819.45ff2d94.logiplexsoftware@earthlink.net> On 11 Mar 2002 14:49:55 -0800 Douglas Garstang wrote: > def tester3(): > """ > >>> import os > >>> os.system ('/bin/ls') > example.py example.pyc tester.py > 0 > """ [snip] > WHY? It runs fine interactively. It also knows to expect the right > stuff. It just SEEMS to think its only getting the return status code > of 0. Where did the other output from the external program go? I also > tried using os.spawnv instead of os.system and I got the same results. os.system returns the exit status of the program (0 in this case). The directory listing went to stdout. Try: import os ls = os.popen("/bin/ls", 'r').read() which will capture stdout into the variable ls. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From dalke at dalkescientific.com Sat Mar 23 16:35:40 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 23 Mar 2002 14:35:40 -0700 Subject: Getopt / matching problem References: <3C9751DD.1070204@beth.uniforum.org.za> Message-ID: Andy Gimblett: >From the getopt module documentation: > > Long options on the command line can be recognized so long as they > provide a prefix of the option name that matches exactly one of > the accepted options. For example, it long_options is ['foo', > 'frob'], the option --fo will match as --foo, but --f will not > match uniquely, so GetoptError will be raised. > >So it's nothing to worry about, just the documented behaviour, and >really the way we'd want it to work, if you think about. Hmm. It's not the way I want it to work. I didn't expect it to work. I don't like stemming because if it's used then it prevents future version of the code from introducing a new option which introduces ambiguous stemming. Andrew dalke at dalkescientific.com From jeff at ccvcorp.com Thu Mar 7 19:57:35 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 07 Mar 2002 16:57:35 -0800 Subject: Status of PEP's? References: Message-ID: <3C880C7F.E304D98C@ccvcorp.com> Jesse W wrote: > The ugly posibiliites: > for i in 5: > print i*2, > #Would print: 8 6 4 2 0 > #Why? What posible sense would this make? No, it would print: 0 2 4 6 8 It doesn't make any less sense to do this than it does to say for i in xrange(5): print i * 2 These two loops would become equivalent. > var=-2 > for i in var: > print i > #Would generate an error of some kind because var is negative. Well, the same thing happens with 'for i in range(var):' in this case. Actually, range() on a negative number returns an empty list; I'd presume that iter() on a negative number should immediately raise StopIteration. > #Or, look at this: > def foo(var): > var=int(var) > var=var*5 > var=var/3 > var+= 12.3 > for i in var*2: > print i > #Will this generate an error? This may actually be a valid point -- range(float) currently is equivalent to range(int(float)), but PEP 276 doesn't propose any new behavior for floats, so this should raise an exception. Still, I think that it's reasonable to expect for programmers to not try to iterate/loop over a float value. > I am sure that others can think of more unpleasent posibilities. > The basic problem is that the proposal is simply too broad. One of the things that really disturbs me about this proposal, is the possibility of integers taking on a new meaning in other contexts than loops, where the iterator protocol is used but this behavior might *not* be 'natural' for integers. I don't know of any other such contexts off the top of my head, except for if statements. Personally, I see 'if x in 5' being a wonderful chance to create all sorts of confusion, but others may disagree. (Of course, I see 'for x in 5' as being likely to create confusion, and others *obviously* disagree with that. ) Jeff Shannon Technician/Programmer Credit International From emile at fenx.com Sun Mar 31 14:51:31 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 31 Mar 2002 19:51:31 GMT Subject: PEP 285: Adding a bool type References: <3CA751EF.10F25F2D@ndh.net> <3CA75ECC.389A0186@alcyone.com> Message-ID: <2NJp8.140405$Yv2.43077@rwcrnsc54> Erik Max Francis > Stefan Schwarzer wrote: > > but on the other hand have to keep in mind subtle interactions between > > bools and ints. For example, I consider it very unintutive that > > "True == 1" should by true but "True == 2" should be false. > > Why? Implicit conversions seem un-Pythonic, so why would this be > unfortunate? When you write (True == 2) you're asking, "Is the value > true equal to the integer value 2?" the answer to which is clearly no. If a=b, shouldn't a==a, a==b and b==a all be true? Someone (Guido?) already mentioned that testing for true is redundant, but doesn't : if 2: imply if 2 == True: which in turn then implies that: True == 2 is true? Or-would-we-be-restricted-to-while-1:-ly y'rs -- Emile van Sebille emile at fenx.com --------- From peter at engcorp.com Wed Mar 6 22:54:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Mar 2002 22:54:09 -0500 Subject: Threading help? References: <3C867E68.B4C3FED2@accessforall.nl> <20020306132612.4a5d756a.logiplexsoftware@earthlink.net> <3C86BD6F.9D258DA7@engcorp.com> Message-ID: <3C86E461.BE9BFDAA@engcorp.com> Cliff Wells wrote: > Peter Hansen wrote: > > Cliff Wells wrote: > > > Hm. Okay, I had to reconsider this. Clearly if the processing is slower > > > than .1s and data is being added to it every .1s, the Queue is going to > > > endlessly grow as more data is added to it. If this is the case, it might > > > make sense to have more than one consumer thread (B) doing the processing. > > > > I might be missing something, but I don't see how adding another thread > > (with a slight extra overhead associated with it) would actually increase > > performance for what I infer is CPU-bound processing in thread B. > > Yes, I thought of this, but I believe that this would give the net effect > of increasing thread priority for the B threads (since they will get more > CPU time as a whole vs threads A and C). Ah, interesting. I hadn't thought before of how the Python interpreter's technique of executing a set number of instructions before switching context would let you do something tricky like that. Neat. In any case, when you said "have thread A retrieve the data every .1s" I figured this was a soft realtime situation, and stealing CPU from thread A would not necessarily be what you need. If between A and B you are taking up all the time, you need to optimize the code, or do what you suggested below and drop data (or increase the sampling period): > But maybe a better approach would be this: if processing time is greater > than .1s and we don't care about out-of-date data (big assumption, but not > unreasonable), then use the Queue between A and B and simply have B empty > the Queue on every iteration, processing only the newest data. This would > keep the Queue to a reasonable size at the cost of dropping data. I suppose the acceptability of that depends on your requirements... dropping data is never a very general approach. :-) -Peter From neal at metaslash.com Fri Mar 22 17:18:19 2002 From: neal at metaslash.com (Neal Norwitz) Date: Fri, 22 Mar 2002 17:18:19 -0500 Subject: Copmlex structures.... References: Message-ID: <3C9BADAB.3F8D1123@metaslash.com> "Dmitry S. Makovey" wrote: > > Hi. The problem itself is - I want to use complex structures like described > below, but i want it another way.... > > 01. >>> f={} > 02. >>> f['name']='dimon' > 03. >>> f['age']=20 > 04. >>> a=[] > 05. >>> a.append(f) > 06. >>> print a > 07. [{'age': 20, 'name': 'dimon'}] > 08. >>> f['age']=22 > 09. >>> print a > 10. [{'age': 22, 'name': 'dimon'}] > > I don't like result in the last like I've expected to have [{'age': 20, > 'name': 'dimon'}], how could i do this? > > I know that it must be as simple as using something like b[:], but what? f.copy() >>> f={} >>> f['name'] = 'dimon' >>> f['age']=20 >>> a=[] >>> a.append(f.copy()) >>> print a [{'age': 20, 'name': 'dimon'}] >>> f['age']=22 >>> print a [{'age': 20, 'name': 'dimon'}] Neal From robin at jessikat.fsnet.co.uk Wed Mar 27 04:19:19 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 27 Mar 2002 09:19:19 +0000 Subject: list of empty lists References: <3CA11A5B.5000501@bioeng.ucsd.edu> Message-ID: In article <3CA11A5B.5000501 at bioeng.ucsd.edu>, Curtis Jensen writes >Is there a easy way to make a list of an arbitray number of empty lists? > >I can do something like: >>>> some_number = 3 >>>> l = [[]] * some_number >>>> l >[[], [], []] > >Unfortunatly this has an unfortunate side affect. Whatever I do to one >of the list gets done to the other lists. ie: >>>> l[0].append(1) >>>> l >[[1], [1], [1]] > > >In this case, what I would like is three independantly empty lists. I >can make a for loop to loop "some_number" of times and append an empty >list at each itteration. Is there a simpler way? >Thanks. > there was a thread about this a while back mainly focussed on the most efficient way to do this for big lists. I think the winner was something like map(list, [[]]*n) -- Robin Becker From grante at visi.com Tue Mar 12 16:13:55 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Mar 2002 21:13:55 GMT Subject: serial port communication References: <3c8e6884.10907140@news.planetis.com> Message-ID: In article <3c8e6884.10907140 at news.planetis.com>, Hugo wrote: > Hi, > > I try to have a communication between two computers using the serial > ports. > > In the interpretor, I just try these instructions : >>>> from os import * >>>> fd = open ('/dev/ttyS0', O_RDWR) >>>> write (fd, "a") > 1 >>>> read (fd, 1) > and everything stop : the read() instruction is probably waiting for > something (I send a character from the other computer but it doesn't > work) ? Unless you've changed the port, it's probably in line-buffered (cooked) mode, and it's waiting for a newline before it hands over the line of text to you. > a stop byte ? or I have use a "timeout" thing ? or the termios > module ? That depends on what you want it to do. > I don't know ! We don't either ! There are a couple serial port libraries around that can make life easier. Mine is strictly for Posix (Unix) systems: ftp://ftp.visi.com/users/grante/python/PosixSerial.py There are some others that are cross-platform, and Googling for "serial" in comp.lang.python should find them. -- Grant Edwards grante Yow! .. my NOSE is NUMB! at visi.com From peter at engcorp.com Fri Mar 15 08:21:23 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 15 Mar 2002 08:21:23 -0500 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> Message-ID: <3C91F553.D9E511CB@engcorp.com> Gerhard H?ring wrote: > > Peter Hansen wrote in comp.lang.python: > > Jonathan Gardner wrote: > >> I am at a major disadvantage because I don't have access to a windows > >> machine, and so I can't test anything directly. However, I do have a few > >> people who actively test for the project at home. > >> > >> Anyone have any suggestions on where I should go? Anyone can help me out > >> here? > > > > Why not find and use one of the several free installer programs, rather > > than trying to write something from scratch yourself? > > > > For example, try looking at google with "free windows installers" and > > follow the first link you find. > > NSIS rocks. But AFAIR his problem is that he doesn't have a Windows > box to build the installer on. D'oh! You're right, my brain wouldn't absorb that concept. Someone writing a Windows installer in Python because he doesn't have a Windows box to run the real Windows installers on. It boggles the mind: how does he plan to test?! > The best solution to this problem is to give in and get a damn Windows > box. It's about the only solution, although "get" could mean "find someone else to help" in this case, as he suggested above. Pointless to build it from scratch. Well, I guess I take that back. If someone set up a Sourceforge project (no! not another! :) to build a Python-based Windows installer which would let someone distribute software easily and reliably to Windows without ever touching a Windows machine, I guess there'd be a small point. Pretty risky though, without that testing thing... -Peter From garys at ihug.com.au Sun Mar 31 19:05:34 2002 From: garys at ihug.com.au (Gary Stephenson) Date: Mon, 1 Apr 2002 10:05:34 +1000 Subject: OT Re: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: > One obvious difficulty with this suggestion is that it requires even > more careful class hierarchy design: if two classes A and B are both > formed from constraining the same superclass, then the intersection of A > and B should also be a class. Indeed! Without wishing to overstate my own limited understanding of the issues involved here, I believe that such a type system would need to be entirely consistent from a set-theoretical pespective. Which would imply (I think) that all subclasses must in fact define mutually exclusive subsets of their parent, and (obviously) that an object having any particular most-specific-type (MST) implicitly precludes it from also conforming to any heirs of that type. This in turn raises the thorny spectre that in order to define a subclass (subtype) one first needs full knowledge of all other extant subtypes! Of course, other difficulties also lurk. Each object needs to retain knowledge of both it's declared type and it's current most-specific-type, so that an object of current MST "square", but of declared type "Rectangle" would allow itself to somehow be mutated back to a MST of "Rectangle" (dubbed by Date and Darwen as "Generalisation by Constraint"), but if it's declared type was "square" it would not be so allowed. Etc, etc, ... > I haven't read those manifestos, though, so maybe they have some way of > addressing this difficulty. Anyway, this is getting a little far afield > from bools and ints... So? This is the Python list - it's OK to go OT, isn't it? Just so long as it's interesting - at least to somebody! ;-) cheers, gary From shimmie at shimmie.com Tue Mar 19 01:13:21 2002 From: shimmie at shimmie.com (Shimmie) Date: Tue, 19 Mar 2002 06:13:21 GMT Subject: Emacs EOF on sys.stdin.readline() Message-ID: <5GAl8.10139$Hz2.38961@news-server.bigpond.net.au> In Emacs, I'm always getting EOF back from a readline() call. My program's along the lines of: while 1: line = sys.stdin.readline() I run it using C-c C-c, however the readline() always returns EOF on everycall. Same thing happens if I use cmd.Cmdloop. If I run the py-shell though and type the code in, it works fine. What have I got configured weird? Emacs 21.1 on WinXP. Shimmie. From weeks at vitus.scs.agilent.com Sat Mar 9 10:53:12 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Sat, 9 Mar 2002 15:53:12 +0000 (UTC) Subject: should i learn it first ? References: <7xpu2ex6xz.fsf@ruckus.brouhaha.com> Message-ID: <1015698192.835972@cswreg.cos.agilent.com> Paul Rubin (phr-n2002a at nightsong.com) wrote: : The thing is, to really understand C++, you have to spend time working : on multi-programmer projects. If you only program by yourself, some : parts of C++ will never make sense to you. I don't see the complexity of C++ as deriving solely from the needs of large software projects. Suppose that performance was not an issue. Then Java is similarly suitable for large software projects. Yet Java is *much* simpler that C++. I can't argue the point here, but the complexity of C++ derives ultimately from the performance issue of object allocation/deallocation. C++ allows allocation on the stack, and it allows customized allocation on the heap. The complexity price is high for this. Indeed, the price is so high that I wish C++ would go away (even though the Standard Template Library is slick). So, Original Poster, I'd recommend that you learn C for high-performance and for closeness to the machine. Avoid C++. Greg From gcordova at hebmex.com Wed Mar 27 16:07:45 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 27 Mar 2002 15:07:45 -0600 Subject: Text to HTML algorithm. Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689EA@SRM201002> > Gustavo Cordova writes: > > > Does anybody have an implementation, or know of one, > > to format plain text into HTML? > > Sure. If it does not contain markup, > > print "
    %s
    " % plaintext > > will fulfill this requirement. > Er... that's not quite what I had in mind. I wish to create printable documentation from SQL scripts. The SQL parser is done, the structure annotator is done, it's already creating basic documentation. What's needed is a way to integrate all the special comments (which have a "@" as the first non-space char in the text) into the generated documents. Using
    ...
    would be quite easy, but then the quality of the output is greatly decreased. > > I need to preserve a minimum of structure, such as > > wrapping

    ...

    around paragraphs separated by > > at least one empty line and detecting unnumbered > > lists (at least). > > If you think you need a pre-existing library, you may want to try > HTMLGen. It knows much about HTML, but little about plain text. I'm already generating HTML using a much simpler library, just to balance tags and indentation. > > Regards, > Martin > Thanks. -gustavo From shalehperry at attbi.com Thu Mar 7 12:45:49 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 07 Mar 2002 09:45:49 -0800 (PST) Subject: Handling bad tags with SGMLParser In-Reply-To: <1015522595.442.24.camel@temp> Message-ID: On 07-Mar-2002 Ken Causey wrote: > On Thu, 2002-03-07 at 11:33, Sean 'Shaleh' Perry wrote: >> > >> > I'm inclined at the moment to report this situation as a bug. But I >> > wanted to get some opinions as I'm neither an SGML expert nor fully >> > confident of my understanding of the SGMLParser class. >> > >> >> I agree this is a bug because the class name is SGMLParser yet it is >> concerning >> itself with html tags. >> > > I'm not sure I understand this comment. What tag do you mean? All of > these are standard SGML tags as I understand it. > # This is some sort of declaration; in "HTML as # deployed," this should only be the document type # declaration (""). k = self.parse_declaration(i) sorry, at first reading I thought that comment meant it was complaining about non DOCTYPE declarations. Happily the code is better than that. Disregard. /me goes to find some tea and wake up. From jkraska at san.rr.com Fri Mar 8 22:29:21 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 09 Mar 2002 03:29:21 GMT Subject: why is python slow? References: Message-ID: >The irreducible fact is that Python needs extensive runtime type checks, >Java doesn't. I would wager that the larger cost on the execution of a Python program is involved in the late binding semantics. C// From kirill_simonov at mail.ru Wed Mar 27 08:19:23 2002 From: kirill_simonov at mail.ru (Kirill Simonov) Date: Wed, 27 Mar 2002 15:19:23 +0200 Subject: list comprehension question In-Reply-To: References: <5.1.0.14.2.20020325111055.044fbd08@202.95.131.154> Message-ID: <20020327131922.GA957@abulafia.local> * Tim Peters : > [Tripp Scott] > > thanks for the tip. actually, the essence of what i wanted to > > ask was: "can that SOMETHING be a list of more than one elements > > which will be _flatly_ added to the result list." > > No. len([f(x) for x in y]) == len(y) whenever no exception occurs, > regardless of the form of f() or type of y. How about such f(x)? def f(x): import sys sys._getframe(1).f_locals['_[1]'](-x) return x def test(f, y): print 'len([f(x) for x in y]) = %s,' % len([f(x) for x in y]), print 'but len(y) = %s' % len(y) test(f, range(10)) -- xi From jeff at ccvcorp.com Wed Mar 6 18:39:46 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 06 Mar 2002 15:39:46 -0800 Subject: How do you print? References: <659f82ff.0203041534.34ad2f91@posting.google.com> Message-ID: <3C86A8C2.88564A12@ccvcorp.com> Peter Scott wrote: > How can you print to a printer in Python? I know that you can do > platform-dependant things like using lpr (on UN*Xlike systems) or > "wordpad -p myfile" on windows, but that doesn't seem to be the Python > Way. > > I just need to print--for now--plain text. Can anyone help me? AFAIK, Python has no built-in cross-platform printer facilities. Various GUI toolkits do include printing frameworks, but if you're only needing to print plain text, they're almost certainly overkill. Your best bet is probably to abstract your printing needs into a single module with a consistent, well-defined interface, and then implement that module in the most natural way for each platform that you need to be able to run on. Not the most desirable solution, but probably the most practical. Jeff Shannon Technician/Programmer Credit International From emile at fenx.com Wed Mar 13 18:21:49 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 13 Mar 2002 15:21:49 -0800 Subject: basic statistics in python References: Message-ID: "dsavitsk" wrote in message news:OvQj8.10177$k5.3810357 at newssvr28.news.prodigy.com... > hi all, > > never having done numeric calculations in python* i am seeking advice on how > to best go about doing some basic statistics. in particular, i need to find > standard deviations and point bi-serial correlations**, and i am seeking > advice on the best way to go about it. i know how to do them, but i am > wondering if there are prebuilt modules that might simplify the task. You might want to take a look at rpy at http://www.cmat.edu.uy/~walterm/rpy/ -- Emile van Sebille emile at fenx.com --------- From danb_83 at yahoo.com Sat Mar 16 22:30:18 2002 From: danb_83 at yahoo.com (Dan Bishop) Date: 16 Mar 2002 19:30:18 -0800 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: Just van Rossum wrote in message news:... > In article , > Graham Ashton wrote: > > > On Fri, 15 Mar 2002 18:49:09 +0000, Skip Montanaro wrote: > > > > >>>>>> "Joe" == Joe Grossberg writes: > > > > > > Joe> Is there any effective difference between the two? > > > > > > Nope. > > > > I read somewhere (don't ask me where) that != is preferred. > > But it's not generally accepted. I for one prefer <>, if only because I > learned Pascal before C... Even for complex numbers, for which "less than or greater than" is meaningless? From jkraska at san.rr.com Sun Mar 24 15:55:51 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 24 Mar 2002 20:55:51 GMT Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> <3C9E2D31.E45278BC@engcorp.com> Message-ID: >I'm curious what the agent actually does if it doesn't share >anything. He already answered, suggesting a message architecture. In effect, however, this means that at least one agent exists to listen for the appropriate message. _That_ agent shouldn't be killed out of turn, but then it's likely that he's not considering it. C// From James_Althoff at i2.com Wed Mar 6 19:29:56 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 6 Mar 2002 16:29:56 -0800 Subject: PEP 284, Integer for-loops Message-ID: Appreciation to David for writing the PEP -- doing so takes time, energy, and commitment. Here are some comments: I think it would be good to add a sentence or two to the "issues" part of the PEP that notes the discussion that took place in prior posts about the limitation of the proposal in terms of needing to write a for-loop or list comprehension *twice* in cases where one wants to be able to handle both increasing and decreasing values in an interval. I think this should be noted as an issue or known limitation -- there are some words in the PEP that position this more as a feature -- because it is *not* a limitation of the current range and xrange functions. I would appreciate a sentence or two in the "issues" section that notes (explicitly) that shortcuts such as "for i < len(myseq)" will not be supported. I think this is relevant because I agree with Bjorn Pettersen that not everyone will consider "for 0 <= index < len(myseq):" to be a significant improvement over current methods for the common case of processing the indices of a sequence. I think the section that talks about loop semantics "one way of interpreting the existing Python for-loops: for item in list iterates over exactly those values of item that cause the expression item in list to be true." should be removed or modified. Python for-loops don't currently enforce that stated property as this simple example shows: >>> >>> class spam: ... def __init__(self): ... self.items = [1,2,3] ... def __iter__(self): ... for item in self.items: yield item ... raise StopIteration ... def __contains__(self,x): ... return 0 ... >>> spm = spam() >>> 1 in spm 0 >>> for x in spm: print x ... 1 2 3 >>> You could state the above as a property of various builtin Python objects, perhaps. But clearly, it is not an inherent property of (nor the defining semantics for) for-loops. I agree with other posters who stated concerns about the limitations of the proposal given that the proposal is heavyweight -- in the sense of requiring syntax changes -- where the limitations include as others have noted: - arbitrary step values not supported (already noted in the PEP), - no first-class interval objects (already noted in the PEP). The PEP is worded in such a way that the syntax change appears to be work *only* for certain existing builtin Python object types: "int" and "long" specifically. Is this really the intention? Will the syntax not work for instances of a subclass of int (now possible in Python 2.2), for example? Or other classes that support some reasonable protocol? If so, I think some words in the "issues" section are appropriate to highlight this limitation. I believe it is a pretty big limitation to have a major, new syntactic construct that can *only* support instances of two classes (int and long). Or is it the intention that the construct is *not* limited strictly to the Python builtin classes "int" and "long"? Will it work for any class that defines __lt__, __lg__, __gt__, __ge__, __add__, and __radd__ methods, for example? And if so, the specification part of the PEP should explain how this would work. For example, will __add__ be called with arg 1 or -1 (builtin integer objects)? So must __add__ be able to accept 1 and -1 as the arg to __add__ as part of the specification? Or does there need to be a "successor" method as was suggested in another post? A lot of thought and work has been put into the syntax part of the proposal. I think some more thought and work might be required on the semantics. Jim From philh at comuno.freeserve.co.uk Mon Mar 11 18:48:25 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 11 Mar 2002 23:48:25 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Mon, 11 Mar 2002 11:31:16 -0800, James_Althoff at i2.com wrote: > >One of your 3rd party components is a table. It has a basic access >protocol via methods like this: > def getRowCount(): pass > def getColumnCount(): pass > def getValueAt(rowIndex,columnIndex): pass > def setValueAt(rowIndex,columnIndex): pass > >[...] >Perhaps you could give some ideas on approaches that would be more >"Pythonic"? How about: def rowKeys(table): return xrange(0, table.getRowCount()) def someFunction(): for r in rowKeys(someTable): #...iterate over all the rows in (someTable) Note that this is less cumbersome than your chosen: for r in someTable.getRowCount(): #...iterate... -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From geoff at gerrietts.net Wed Mar 27 13:42:59 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Wed, 27 Mar 2002 10:42:59 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) In-Reply-To: References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Message-ID: <20020327184259.GA17039@isis.gerrietts.net> Quoting Gon?alo Rodrigues (op73418 at mail.telepac.pt): > On Tue, 26 Mar 2002 20:04:50 -0800, Geoff Gerrietts > wrote: > > >Quoting Courageous (jkraska at san.rr.com): > >> > >> >I'd say the skills required to write clear, readable > >> >software and clear, readable novels are not entirely > >> >disjoint! > >> > >> Oh certainly not, you just haven't backed up to a big > >> enough perspective of the cognitive domain. :) > > > >I think poetry and code are actually very similar. Some day I may > >write a paper on that thesis, but I'm still living the experience > >today.... > > Poetry and coding are similar in that they are both creative activities > needing inteligence, imagination, etc. But there is also a world of > difference between the two. A simple way to see this is how they relate > to their heritage, their common dead. I think the startling similarity that I see is that code is in many ways an extremely strict form of poetry. If you look to things like the Perl poetry contests, and even the innumerable obfuscated code contests, these are artistic in a way that forms a sort of continuum. Writing code is a lot like writing a poem, with a vocabulary that is extremely restricted and formal requirements that are invariably rigid. The sense of meaning one derives from a program is generally more pragmatic than what one gets from a poem. But both are appreciated as much for what they say as for how they say it. One notable difference between programming and poetry is that a programming cliche is acceptable, a rote that people are encouraged to re-use, whereas dropping someone else's clever turn of phrase into your poem is likely to backfire. I'm still a long way from a thesis, but I think the similarities are pretty astounding. And I don't think I can comment extensively on the "common dead", given that poets tend to take about 25 or 50 years to rise to prominence, and the widespread practice of programming in 3rd gen languages is still somewhat younger than that. I can comment on the "common living", though -- Silicon Valley and the Bay Area are both full of people who went to school for English and fell into writing HTML, Perl, PHP. I can't comment extensively on the quality of the code these writers-cum-programmers generate, but I'll bet their comments are at least a bit more intelligible -- and I'll bet their code is more readable. I've been programming for a long time -- most of my life at this point, and professionally for a bit more than 6 years. But my education was in poetry; I was trained as a poet, and somewhat successful at it, winning a few awards and being published in some out of the way places. I returned to programming when I realized that I was pretty good at writing, but I couldn't bring myself to do it in my spare time -- I was instead spending that spare time learning new programming languages, or learning Linux system administration. I didn't enjoy reading poetry all that much, but I could sit down and read a book on OO design or advanced programming techniques without hesitation. So I respect the differences; there are many, and I've chosen my road because of them. But the principal values of poetry: no wasted words, clear expression, clever expression, best use of language -- these values translate directly into writing code. Maybe that thesis isn't so many years off, after all.... --G. -- Geoff Gerrietts "Many a man's reputation would not know his character if they met on http://www.gerrietts.net/ the street." --Elbert Hubbard From James_Althoff at i2.com Mon Mar 4 19:05:55 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 16:05:55 -0800 Subject: Status of PEP's? Message-ID: "Hernan M. Foffani" wrote: > > indici(x) will replace the odd xrange(len(x)) idiom and address the problem > of open intervals where the length of the set is not known in advance. Just keep in mind that indici/indices/indexes-type proposals don't help in cases where __len__ is not defined. Two-dimensional structures, for example. Jython/Swing table models, for example. And PEP 276 -- adding an __iter__ method to class int -- doesn't prevent the above (nor any other for-loop-oriented enhancement) and can peacefully coexist with it. Jim From offer at sgi.com Mon Mar 25 16:28:41 2002 From: offer at sgi.com (Nhi Vanye) Date: 25 Mar 2002 21:28:41 GMT Subject: Porting a Python app to IRIX -- need help References: Message-ID: $ from dubois at users.sourceforge.net -#190139 | sed "1,$s/^/> /" > > >I am trying to get a Python-based app running on an SGI running IRIX 6.5. I >am running into a problem involving some objects being compiled "n32" and >others "o32". The linker refuses to link them. > >I got pretty far by setting environment variable CC to "cc" but then it >complained that the X11 library is o32. Can an SGI person tell me whether >o32 or n32 is "normal" and what I tell the compiler to be sure I get that? > I've just finished packaging up a new drop of Python for SGI Freeware (still 2.1.1). Hopefully it should fix a number of problems in the last release (files were directories). In addition I've enabled the cd and al modules, and I now ship the Tools (I needed the compiler for quixote) (although not installed, you'll have to do something like cd /usr/freeware/lib/python2.1/Tools/compiler ; python2 setup.py install; for any tools you want installed). You can get an alpha version here.. http://reality.sgiweb.org/offer/dist/fw_python2-20020325.tardist If there's any problems with it, let me know we'll be freezing the next freeware distribution at the end of the week. richard. -- Richard Offer Technical Lead, Trust Technology. "Specialization is for insects" __________________________________________http://reality.sgi.com/offer/ From jeff at ccvcorp.com Mon Mar 11 16:39:00 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 11 Mar 2002 13:39:00 -0800 Subject: Get reference to "owner" References: <20020305072655.GA1525@lilith.hqd-internal> <625h8.3294$tg2.206482@e3500-atl1.usenetserver.com> Message-ID: <3C8D23F3.B9ACF1A3@ccvcorp.com> Robert Oschler wrote: > Gerhard, > > Excellent!!! Never expected to find a language that could do this and it > something I've wanted very badly for a long time. Yes that's exactly what I > meant. B knows about the A that owns it without having to artificially pass > a reference of A to B during construction. IMHO, this isn't a good idea. Explicit is better than implicit, and if you need to use a reference to the container object, then it's best to explicitly pass that reference to the contained object on creation. This also avoids the limitation that someone else pointed out, that the solution that Gerhard H?ring came up with only finds the *creator*, not the container, and then only if that creator uses 'self'. It also allows you to change the containing object, if there's ever a reason to do that (like moving an object from a Pending collection to a Completed collection). Jeff Shannon Technician/Programmer Credit International From morus.walter at web.de Fri Mar 29 03:00:45 2002 From: morus.walter at web.de (Morus Walter) Date: Fri, 29 Mar 2002 09:00:45 +0100 Subject: re.split and lookaheads References: Message-ID: On Wed, 27 Mar 2002 13:23:18 +0100, John Machin wrote: > This is the case with *any* zero-width pattern (as at version 2.2) -- > see examples below. Thanks for your answer. I understand now, what's going on. > You should raise a documentation enhancement request. > Though I understand that pythons behaviour can be considered reasonable in the cases you list, I definitly prefer perls semantik, as using such RE makes a lot of sense to me in the case of lookaheads or lookbehinds. So a feature request might be more, what I want. But I'm not sure, whether that would be welcome, since it might break code. Fortunately one can easily write one's own split function, to avoid the problem. >>>> re.sub(r"\b", "z", "abc def ghi") > 'zabcz zdefz zghiz' Hmm. So re.sub accepts zero width matches? Strange. greetings Morus From a.clarke11 at pop.ntlworld.com Sun Mar 24 14:09:45 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Sun, 24 Mar 2002 19:09:45 +0000 Subject: advanced Python References: <3C9E6058.8D3EFE6F@gol.ge> Message-ID: <3C9E2479.1BF5BCD2@pop.ntlworld.com> Hi There is the "Advanced Python Programming" by David Beazely, extracts available as pdf at Python City at http://www.awaretek.com/tutorials.html Hope this helps Tony ............... You said Hello! I wonder if someone prompts me a book dedicated to the advanced topics of python? Something tailored a-la "Advanced C++" by James O. Coplien... Thanx in advance! Best regards, Giorgi From tejarex at yahoo.com Sun Mar 31 18:16:20 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sun, 31 Mar 2002 23:16:20 GMT Subject: PEP 285: Adding a bool type References: <3CA75F2F.198772EB@alcyone.com> Message-ID: <8NMp8.184567$2q2.15567243@bin4.nnrp.aus1.giganews.com> "Erik Max Francis" wrote in message news:3CA75F2F.198772EB at alcyone.com... > Aahz wrote: > > > But what do you think of changing bool() to truth()? > > In the new type unification scheme, bool seems a much better name than > truth. Yesterday, I gave four reasons for prefering 'truth' (or something else) to bool. Please consider them. Already, my prediction in point D is being borne out in some subsequent posts by some. Something about the word 'bool(ean)' sets off something in some people's brain that makes them want cripple a formalized Python truth type by prohibiting currently valid and useful behavior. I find this as offensive both to the spirit of Python and my programming freedom as the suggestion that sequence*int should be deprecated and then prohibited because it violates some standard of 'proper' sequence behavior. Rather than have to put up with and have to argue against such suggestions for the rest of my life, I would rather switch to a different term that does not carry with it the baggage that 'bool' so obviously does. Terry J. Reedy From sholden at holdenweb.com Wed Mar 27 15:53:09 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 27 Mar 2002 15:53:09 -0500 Subject: Text to HTML algorithm. References: Message-ID: "Gustavo Cordova" wrote in message news:mailman.1017254742.8781.python-list at python.org... Howdy y'alls. Does anybody have an implementation, or know of one, to format plain text into HTML? I need to preserve a minimum of structure, such as wrapping

    ...

    around paragraphs separated by at least one empty line and detecting unnumbered lists (at least). The StructuredText module from Zope sounds like it will do exactly what you want. regards Steve From roy at panix.com Sat Mar 9 09:04:43 2002 From: roy at panix.com (Roy Smith) Date: Sat, 09 Mar 2002 09:04:43 -0500 Subject: PEP Parade References: <3C895594.60601@sneakemail.com> Message-ID: Joshua Macy wrote: > Just out of curiosity, what does the rest of your group develop in > then? FORTRAN? COBOL? ("and none of this ANSI85 crap, either...it gets > old trying to hit a moving target!") For internal tools, mostly perl. For production code, mostly C/C++ and TCL. From mickey at tm.informatik.uni-frankfurt.de Sun Mar 24 13:16:10 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 24 Mar 2002 20:16:10 +0200 Subject: PyQt installation problems on windows References: Message-ID: <3c9e25fa@nntp.server.uni-frankfurt.de> Amit Mongia wrote: > Hi, > I have installed Python 2.2 , on my computer. I > created a gui using Qt Designer and used pyuic to make > a python file out of it. > Now i want to run that file using the python > interpreter. Whenever i try doing that it gives an > error: > > Traceback (most recent call last): > File "WrapperInterface.py", line 10, in ? > from qt import * > File "F:\PYTHON22\lib\qt.py", line 44, in ? > import libqtc > ImportError: DLL load failed: One of the library files > needed to run this applic > ation cannot be found. Place the qt.dll from the non-commercial windows version into /system32. :M: From michael.neuroth at freenet.de Tue Mar 5 17:03:33 2002 From: michael.neuroth at freenet.de (Michael Neuroth) Date: Tue, 05 Mar 2002 23:03:33 +0100 Subject: undefined symbols when linking Python into a shared library Message-ID: <3C8540B5.E133D407@freenet.de> Hello to all python experts, I have a question about embedding Python in an application. To be more precisely, I want to create a shared library which holds the python interpreter and some other functions registered at the Python interpreter (I used SWIG for that task). This shared library (or DLL) will be loaded dynamically from an application to support Python as script language. This way works well for Windows and (for simple scripts which do not load other modules) also for Linux. Unfortunately I get an "undefined symbol" error when I try to load other modules with the import statement on Linux. When I try to laod Tkiter in a simple test script, I get this error message on stderr from the embedded python interpreter: Traceback (most recent call last): File "", lind 2, in ? File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 35, in ? import _tkiter # If this fails your Python my not be configured for Tk ImportError: /usr/lib/python2.1/lib-dynload/_tkiter.so: undefined symbol: _Py_NoneStruct I link libpyhton.a into the shared library, I tried also to link with the option -Xlinker -export-dynamic, as told by the python documentation (section:Extending and Embedding the Python Interpreter, 5.6 Linking Requirements). The shared library is a little bit lager, but the resulting error is the same. How can I verify, that this symbols are in the shared library? I have no such "undefined symbol" problems, when I embed the python interpreter into the application directly (with the option: -Xlinker -export-dynamic). What is the magic option to solve that (linker?) problem? Has someone succeded to create a shared library with the pyhton interpreter which successfully loads other modules? Any help is welcome. Thank you in advance. Michael. PS: The appliation which I'm talking about is MinDia, an OpenSource (multiplatform) program for slide shows (with rollei diaprojectos), written in C++ and with Qt. The homepage and the sourcecode for MinDia can be found at sourceforge: http://mindia.sourceforge.net (The error can be reproduced when loading and running the sample script _tktest.py) ---------------------------------------------------------------------- Michael Neuroth, e-mail: michael.neuroth at freenet.de ---------------------------------------------------------------------- From orl_ando74 at hotmail.com Thu Mar 28 23:04:32 2002 From: orl_ando74 at hotmail.com (Giganews) Date: Fri, 29 Mar 2002 04:04:32 GMT Subject: Win32 Impersonation Message-ID: Hey all, I'm a newbie with Python, and I have been looking for a way to run a script as the administrator on Windows NT. I have the user name and password, and some code to do the impersonation, but when I try to use it, I receive a sort of access denied message. Upon reading the ActivePython docs, I found that the user who runs the impersonation script needs SE_TCB_NAME, SE_CHANGE_NOTIFY_NAME, and SE_ASSIGNPRIMARYTOKEN_NAME priveleges. Maybe I'm missing the point here, but the only two accounts on these systems with these priveleges are the administrator and the local system account. Obviously, if I already were the administrator I wouldn't have this problem. I think I'm missing something. Anyway, here is the template of the code that I'm having problems with: admin=win32security.LogonUser('administrator_account','domain','password') win32security.ImpersonateLoggedOnUser(admin) Has anyone gotten this to work on their systems, if so please help me! Is there another way? Any help would be greatly appreciated, Pablo Manzanera From mnations at airmail.net Fri Mar 29 12:18:06 2002 From: mnations at airmail.net (Marc) Date: 29 Mar 2002 09:18:06 -0800 Subject: Stopping a thread from an imported file Message-ID: <4378fa6f.0203290918.21be5409@posting.google.com> Hi, I am writing an application that has a front end Tkinter GUI and a back end process. The back end process is being imported into the GUI, which acts as the main thread in the program. When the 'GO' button is clicked, the GUI starts a thread which calls a function that sends control to the back end. The problem is that when this function has ended, the thread does not die. So when the button is clicked to start the application again, it won't start because it thinks the thread is still active. I have another thread within the GUI application that simply keeps track of elapsed time. I don't have the same problem with this thread which actually restarts every time the button is clicked. That, to me, is even more confusing, since I know that thread is still running. And since my experience with threads is limited, I'm simply going based on what works and what doesn't to get this program working, and I can't reason out what I've seen. Which leads me to two questions: 1) When a function in an imported file completes, how does the thread in the main file know to stop. 2) If you can't restart a thread while it is active (which is the error I receive in the first thread) then how can the second thread simply restart when it is called again. Here's the relevant code: class GuiPart: def __init__(self, master, endCommand, thread1, thread2): self.endCommand = endCommand self.thread1 = thread1 self.thread2 = thread2 self.master = master self.mainFrame = Frame(master) self.mainWindow = Frame(self.mainFrame) self.mainFrame.pack() self.mainFrame.master.title("Running OCN cards") self.mainWindow.pack() self.createWidgets() def validation(self): self.startTime = time.time() flag = 0 flag = self.validateIP( self.ipaddr.get() ) validOcn = self.var.get() if validOcn == '': showerror(title='Invalid OCN',message='Please select an OCN Type') flag = 0 else: flag = flag * 1 if flag: self.go_thread() def go_thread(self): self.thread1.setDaemon(1) self.thread2.setDaemon(2) self.thread1.start() self.thread2.start() <...snip...> class ThreadedClient: def __init__(self, master): self.master = master self.ok = 1 self.thread1 = Thread(target = self.ocnRun) self.thread2 = Thread(target = self.elapsedTime) self.gui = GuiPart(master, self.endApplication, self.thread1, self.thread2) self.periodicCall() def periodicCall(self): if not self.ok: #os._exit(0) sys.exit(0) self.master.after(100, self.periodicCall) def ocnRun(self): print "In ocnRun" counter, total = 0, 0 for testgroup, titles, groupRow, groupCol in self.gui.testGroups: for module, row, col, status, color in testgroup: modFlag = getattr(self.gui.modVar, module).get() total = modFlag * pow( 2, counter ) + total counter = counter + 1 self.gui.slot = self.gui.list.curselection() printAll( self.gui.ipaddr.get(), self.gui.var.get(), self.gui.list.get(self.gui.slot), total, self.gui.port.get(), self.gui.filename_field.get(), self.gui.password.get(), self.gui.debug_field.get() , self.gui.debugVar.get(), self.gui, self.gui.iterations.get() ) def elapsedTime(self): curTime = time.time() eTime = curTime - self.gui.startTime hours = str( int(eTime / 3600) ) mins = str( int(eTime / 60) ) secs = str( int(eTime) ) if atoi(hours) < 10: hours = '0' + hours if atoi(mins) < 10: mins = '0' + mins if atoi(secs) < 10: secs = '0' + secs elapsedTime = hours + ':' + mins + ':' + secs self.gui.elapsTime.insert(END, elapsedTime) self.gui.master.after(1000, self.elapsedTime) def endApplication(self): self.ok = 0 """ Begin Main Processing """ root=Tk() client = ThreadedClient(root) root.mainloop() The first thread calls ocnRun which calls a function from an imported file. Somehow I need to tell ocnRun that PrintAll has stopped. But I assumed that would simply happen when PrintAll ran to completion. Anyway, I think that's all the relevant information. I've read as much stuff on threads from this newsgroup and other resources as I could find, but still can't find the answer. Any help would be appreciated. Thanks ahead of time, Marc From nde at comp.leeds.ac.uk Mon Mar 4 10:35:24 2002 From: nde at comp.leeds.ac.uk (N D Efford) Date: Mon, 4 Mar 2002 15:35:24 GMT Subject: Deitel and Deitel Book... References: Message-ID: Jason Orendorff wrote: > I dislike Deitel & Deitel because of their casual disregard for > correctness. I can't open any of their books without finding an error. > In C++HTP, they illustrate "Circle" as a subclass of "Point". ...and compound the error by making Cylinder a subclass of Circle! This has been there for at least the past three editions. Criticisms of it in book reviews and other forums have not persuaded them to correct the misconception. Nick From cs1spw at bath.ac.uk Tue Mar 5 07:55:17 2002 From: cs1spw at bath.ac.uk (Simon Willison) Date: Tue, 5 Mar 2002 12:55:17 GMT Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> Message-ID: <3C84C032.1070409@bath.ac.uk> I figured it out and I'm kicking myself now. It was a case sensitivity problem - my regular expression wasn't picking up something tags. Doh! From gcordova at hebmex.com Wed Mar 13 10:54:46 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 13 Mar 2002 09:54:46 -0600 Subject: Has Mark Hammond attained pariah status yet? Message-ID: <19650FF08A99D511B19E00B0D0F0632301D68949@SRM201002> > > Unfortunately development effort seems to be going to premature > optimization -- an x86 JIT, regex opcodes, counting the cycles taken > by the main loop -- instead of filling in the missing pieces, so I'm > getting increasingly skeptical that Parrot will provide a useful > substrate for anything. > > --amk Hmmm... but it's gonna be a hell of a fast substrate, though. It's like "going nowhere fast" :-) -gustavo From jgardn at alumni.washington.edu Sat Mar 16 08:59:04 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Sat, 16 Mar 2002 22:59:04 +0900 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> <3C92E590.749C1557@engcorp.com> Message-ID: Peter Hansen scribbled with his keyboard: > Jonathan Gardner wrote: >> I run a free software project that is trying to keep things compatible >> with Windows and Linux. So that means I am in *deep trouble* because I >> can't test windows directly. BUT! I do have a few guys who run windows >> and do try stuff out very actively. Unfortunately, they can't code well >> enough to do this themselves. > > I guess this means they aren't techie enough to run one of the > installers for you to package up your Windows distribution? > That's a bummer. :( Maybe you can find a volunteer to help > you, who can do just packaging and not have to do any testing? > It's not that we don't know how to figure stuff out, it's just that none of us have ever tried anything like this, and we are trying to get a start. Looking at the list (see below) of free installers, it sure does look very easy to use those tools. >> >> For example, try looking at google with "free windows installers" and >> >> follow the first link you find. >> >> To... http://www.wxwindows.org/technote/install.htm ? =) > > Yes. > You are right. I'll trust Google more in the future. >> I did try looking on google, and it looks like I have a choice between: >> >> a) Windows Installer >> b) WISE >> >> None of which seem to be free. I remember a long time ago that there was >> a popular installer offering a free version for free software. Was I just >> seeing things or was that so? > > Why is that the only choice? On that page it says those are commercial, > then lists five _free_ ones (not sure about GPL status). Are none of > those listed appropriate? (Why?) > No, these are very appropriate. I apologize for not reading the page closely. Jonathan From d95-bli.no at spam.nada.kth.se Sat Mar 23 08:15:40 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-1?Q?Bj=F6rn?= Lindberg) Date: Sat, 23 Mar 2002 14:15:40 +0100 Subject: Popular style document? References: Message-ID: <3C9C7FFC.26562E68@spam.nada.kth.se> Michael Chermside wrote: > Advantages of "Automatic" access to instance variables: > * Less typing. > * Somewhat more convenient to use objects (because you don't have to > type "self." in front of instance variable accesses. Mostly about > there being less typing.) But this is not the same question as the one i discussed. The fact that the variable "i" in a class in C++ hides a variable "i" in an outer scope is just that; scope rules. It works the same way as when "i" in a function hides a global variable "i". This is because of scope rules and doesn't have anything directly to do with the explicit reference to "self". > * Functions and Methods have a VERY simple relationship... methods > are just functions that take an instance as their first parameter. > This allows you to do things like "myObject.getFoo = myGetFooFunc", > to create a new method. This is what I was wondering about. I think it looks interesting, and as you say it couldn't reasonably be done unless "self" is explicit. Bj?rn From irmen at NOSPAMREMOVETHISxs4all.nl Wed Mar 27 17:58:14 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Wed, 27 Mar 2002 23:58:14 +0100 Subject: unicode experiments + questions References: Message-ID: A few quick additions; > How does Python know this charset, because in my syte.py encoding="iso-8859-15". That must be site.py ofcourse, to set the default encoding. [...] > for enc in ['utf-16','utf-8','utf-7','iso-8859-15','cp1252']: [...] Adding the well-known iso-8859-1 (iso-latin-1) to the list results in an exception: Latin-1 encoding error: ordinal not in range(256) as expected, because I found out that the Euro symbol is not in latin-1 but *is* in latin-9 (iso-8859-15). From just at xs4all.nl Thu Mar 7 08:49:15 2002 From: just at xs4all.nl (Just van Rossum) Date: Thu, 07 Mar 2002 14:49:15 +0100 Subject: PEP 276 -- What else could iter(5) mean? References: <6qpu2gzktu.fsf@abnoba.intevation.de> Message-ID: In article , Michael Hudson wrote: > Well, so long as your brother thinks the same, those of us in the > "anti" camp don't have to worry, right? At least, that's what I've > been hoping. That's what I've been hoping, too... I think we have little to worry about. Yet Bernhard Herzog's examples are very good to show the ugliness of the example. Just From erno-news at erno.iki.fi Thu Mar 21 04:10:34 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 21 Mar 2002 11:10:34 +0200 Subject: Python & IRC References: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> Message-ID: In article <_Wcm8.134736$Nn6.6764300 at e3500-atl2.usenetserver.com>, "Felix" writes: | I'm not sure if you guys here might be able ot help me but i have | been looking up and down for a irc client that alllows me ot script | in python. one is at . -- erno From matkin at iar.se Fri Mar 15 04:51:02 2002 From: matkin at iar.se (Mats Kindahl) Date: 15 Mar 2002 10:51:02 +0100 Subject: YANRQ (yet another regex question) References: <4f5k8.435$zT5.13755@news.itd.umich.edu> Message-ID: Mats Kindahl writes: > Michael George Lerner writes: > > > I wanted to match this: > > > > (?Pfoo | foo | foo | foo | foo) > > > > without typing in all of the different combinations of 'foo' and spaces. > > > > (Tim kindly pointed out the typos in the above, which I've corrected) > > > > Mats Kindahl wrote: > > > > > Depending on the definition of easy, this is the alternative I would > > > use. > > > > > r = re.compile(r'(?P(?=.{7}) *foo *)') > > > > > > Of course, your milage may wary. > > > > Doesn't quite work for me: > > > > >>> import re > > >>> r = re.compile(r'(?P(?=.{7}) *foo *)') > > >>> s = r.match('foo ').groupdict()['foo'] > > >>> s > > 'foo ' > > >>> len(s) > > 12 > > >>> > > > > and I only want to match things that are seven characters long here. > > That's what I get for not reading the manual... :/ > > Of course it should be Bad style to follow up to one self, but... r = re.compile(r'(?P(?=.{7}$) *foo *$)') ^ ^ ! ! notice missing dollars --+--------+ -- Mats Kindahl, IAR Systems, Sweden Any opinions expressed are my own, not my company's. From spencer at efn.org Sat Mar 2 16:27:06 2002 From: spencer at efn.org (Spencer Ernest Doidge) Date: Sat, 2 Mar 2002 13:27:06 -0800 Subject: Windows GUI - which way? In-Reply-To: <3C7EC855.5844B19F@engcorp.com> References: <3C7EC855.5844B19F@engcorp.com> Message-ID: Thank you for this reply. I have another question that you sound unusually well-qualified to answer: I want to maintain and use a library of Python scripts. I want to invoke any script from this library by using a GUI app. The script itself would have no GUI features. It would be sending and receiving serial port messages. (This is like the script I am already running.) Some frequently-used scripts would be invoked directly from a Tools menu, others would be named in a File/Open dialog. I want to begin execution of the script by using either a menu, a dialog, or a toolbar icon. When the execution begins, I want to be able to abort the script at any time by either a dialog button, a menu item, or a toolbar icon. If I write the GUI app all in Python, is it a simple matter to, say, load and run the script in its own thread, and have it be responsive to a signal from the main thread telling it to abort? Those are the must-have features. For nice-to-haves, it would be nice to display some sort of output, even a progress control (thermometer, or whatever one calls it), or some text in an output window, the way it's done in Visual C++ when you build a project. Do you know of straightforward ways to accomplish the must-haves? What about the nice-to-haves? Thanks very much in advance for taking the time to read and reply to this post. Spencer Doidge www.spencerdoidge.com On Thu, 28 Feb 2002, Peter Hansen wrote: > Spencer Doidge wrote: > > > > I have a nice script running and doing useful work--in the Windows console > > mode. [...] I'd like to make this palatable for others around the company > > to use, and that means Windows GUI. > > So should I write up a program in my favorite style, Win32 API, and embed > > Python in it? > > Or should I write the whole thing in Python? > > > > Would somebody like to comment on the pros and cons? > > Write the whole thing in Python (my preference would be with wxPython) > and package it up with py2exe or equivalent. Use a standard > installer to distribute it and no one in the company will ever > know it was written with Python. Except for the higher reliability. > And your greater responsiveness in implementing feature requests > quickly. And how quickly you got it to them. Etc. :-) > > (We've written several utilities with wxPython and serial ports > running under Windows. So far the wxPython side of things > is quite primitive since we're still learning, but even in > their current state they're quite acceptable, and have no > real issues the way a more traditionally developed program > (i.e. Windows GUI with C/C++ or whatever) would have. > > -Peter > From tdelaney at avaya.com Sun Mar 24 23:57:50 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 25 Mar 2002 15:57:50 +1100 Subject: Debugging on windows via print statements -- reliable? Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > I don't recall if print flushes its output after each call, but if you > want to be certain it does, try calling sys.stdout.flush() after your > print calls. This is a console app, right?, and you aren't > redirecting > the output to a file? Make sure you run python as python -u to get unbuffered output ... Tim Delaney From i-have at no.mail Sun Mar 17 03:31:09 2002 From: i-have at no.mail (Jeffrey-man) Date: Sun, 17 Mar 2002 11:31:09 +0300 Subject: Begginers Guide - Exrcise. Help me, plz! References: Message-ID: Thank you very much! Here it is the final version: ----- from time import sleep sum = 0 sum_stop = 100 while sum < 100: num = input("Please enter the number: ") sum = sum+num if sum < 100: print "The sum is", sum else: print "The sum is > 100 and it is", sum print sleep(10) ----- Best regards. From gh_pythonlist at gmx.de Wed Mar 13 23:50:53 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 14 Mar 2002 05:50:53 +0100 Subject: Performance problem with filtering In-Reply-To: <20020314040837.GA403@lilith.hqd-internal> References: <20020314040837.GA403@lilith.hqd-internal> Message-ID: <20020314045052.GA550@lilith.hqd-internal> Le 14/03/02 ? 05:08, Gerhard H?ring ?crivit: > Anybody wrote a subclassed list yet that is optimized for __contains__? I just tried that by subclassing list in Python 2.2, but it turned out that I'd need to override almost all methods in order to not introduce any bugs. So I just built this minimal class which does exactly what I need here: class FastList: def __init__(self, l = None): self.count = {} self.l = [] if l is not None: for item in l: self.append(item) def append(self, item): self.count[item] = self.count.get(item, 0) + 1 self.l.append(item) def __contains__(self, item): return self.count.has_key(item) def __getitem__(self, pos): return self.l[pos] Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 7.4 ?C Wind: 1.1 m/s From usenet at thinkspot.net Sat Mar 23 02:52:16 2002 From: usenet at thinkspot.net (Sheila King) Date: Fri, 22 Mar 2002 23:52:16 -0800 Subject: Core Python Programming, chapter 5 exercises number 5-3, question on this exercise References: <8dbo9u8jv0j9p58h4dvhqojk2154m8vict@4ax.com> Message-ID: On Sat, 23 Mar 2002 07:37:56 GMT, John Warney wrote in comp.lang.python in article : > > PS---why is it that every mailing list or newgsroup posting i always > ask, i always answer my own dumbass question 5-10 mins after i > post/ask it??, lol I believe that is a corollary to Murphy's Law. On the other hand, it's incredibly useful for debugging your scripts. Just think about it: Do you want to find the bug in your script so badly that you're willing to endure public humiliation? Maybe it's a fair trade? ;) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From emile at fenx.com Wed Mar 27 21:13:48 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 27 Mar 2002 18:13:48 -0800 Subject: mutliple search and replace References: Message-ID: Trung Hoang > Suppose i have a map (or two lists). is it possible to make a sweep through > a string to find all occurances of key's in the map then replace them all in > one sweep? > >>> d = {'one':'een','two':'twee','three':'drie','four':'vier'} >>> s = "one two buckle my shoe three four je t'adore" >>> ' '.join([d.get(w,w) for w in s.split()]) "een twee buckle my shoe drie vier je t'adore" -- Emile van Sebille emile at fenx.com --------- From aahzpy at panix.com Sat Mar 23 02:27:36 2002 From: aahzpy at panix.com (Aahz) Date: 23 Mar 2002 02:27:36 -0500 Subject: mutlifile inheritance problem simplified References: <9896e047.0203211303.741f695a@posting.google.com> <3C9BAB77.B4E17C65@hotmail.com> <3C9C0B45.E3C51B0C@hotmail.com> Message-ID: In article <3C9C0B45.E3C51B0C at hotmail.com>, Marc wrote: >Aahz wrote: >> In article <3C9BAB77.B4E17C65 at hotmail.com>, >> Marc wrote: >>> >>>I'm using Windows NT, Python 1.5.2, and IDLE 0.5 >> >> Try switching to Python 2.1.2 or 2.2; I'm sure that reload() has had >> some changeds. > >OK, I've just tried Python 2.2 and IDLE 0.8. Same problem. > >This really seems quite mysterious? I'm surprised that others haven't >run into this. I'm sure I'm not the first person to use reload, or the >first to inherit from a class into different files. Not many people do use reload(), in my experience. I'm pretty knowledgeable about Python, I think, and I've been pretty regular on comp.lang.python for almost three years. It's not interesting enough to me personally to invest much of my time, I'm afraid. ;-) I still haven't seen any clear explanation from you for why you need to use reload() in the first place. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From jriveramerla at yahoo.com Sun Mar 24 01:01:45 2002 From: jriveramerla at yahoo.com (Jose Rivera) Date: 23 Mar 2002 22:01:45 -0800 Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> Message-ID: <11e94203.0203232201.4dde9883@posting.google.com> Thanks for your comments... the site uses POST method, so I saved to disk the page, and modify it to use GET so I could get an idea of the parameters used... The URL calculated : http://avisos.elnorte.com/casa_venta_result.asp?fotos=0&Order=order+by+colonia&Precio_i=-1&Presentacion=Tabla&Precio_f=-1&PLANTAS=0&pagina=1&id_inmueble=3&dia=&RECAMARAS=0&constr_f=-1&COLONIA=0&BANOS=0&Tipo=CASAS&Constr_i=-1&Terreno_i=-1&Terreno_f=-1&zona=0 works on my PC, try it, and let's see whats wrong. thanks for your time, and comments. Does anyone have an idea of how I can save it to a DataBase? Is there a better way? Thanks ... From logiplexsoftware at earthlink.net Thu Mar 7 12:32:41 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Thu, 7 Mar 2002 09:32:41 -0800 Subject: Threading help? In-Reply-To: <3C86E461.BE9BFDAA@engcorp.com> References: <3C867E68.B4C3FED2@accessforall.nl> <20020306132612.4a5d756a.logiplexsoftware@earthlink.net> <3C86BD6F.9D258DA7@engcorp.com> <3C86E461.BE9BFDAA@engcorp.com> Message-ID: <20020307093241.48ddfca0.logiplexsoftware@earthlink.net> On Wed, 06 Mar 2002 22:54:09 -0500 Peter Hansen wrote: > Cliff Wells wrote: > > Peter Hansen wrote: > > > Cliff Wells wrote: > > > > Hm. Okay, I had to reconsider this. Clearly if the processing is slower > > > > than .1s and data is being added to it every .1s, the Queue is going to > > > > endlessly grow as more data is added to it. If this is the case, it might > > > > make sense to have more than one consumer thread (B) doing the processing. > > > > > > I might be missing something, but I don't see how adding another thread > > > (with a slight extra overhead associated with it) would actually increase > > > performance for what I infer is CPU-bound processing in thread B. > > > > Yes, I thought of this, but I believe that this would give the net effect > > of increasing thread priority for the B threads (since they will get more > > CPU time as a whole vs threads A and C). > > Ah, interesting. I hadn't thought before of how the Python interpreter's > technique of executing a set number of instructions before switching context > would let you do something tricky like that. Neat. > > In any case, when you said "have thread A retrieve the data every .1s" > I figured this was a soft realtime situation, and stealing CPU from thread > A would not necessarily be what you need. If between A and B you are taking > up all the time, you need to optimize the code, or do what you suggested > below and drop data (or increase the sampling period): On my way home last night (immediately after posting this, of course), I realized that this is no good anyway as thread A will be sleeping/retrieving and thread C will be blocking, waiting for data on the queue, so having multiple thread B's wouldn't help much. This is a difficult problem in Python (assuming the processing time for B is longer than the time constraints given). Simply put, it can't be done in a straightforward fashion. Basically it comes down to this: data is required every .1s, but the processing on that data takes >.1s. I don't believe SMP comes into play much when using Python (even with threads), so the only approach that would work would be a distributed model (although this could be done on a single SMP PC by setting the affinity of the interpreters) or by dropping data. > > But maybe a better approach would be this: if processing time is greater > > than .1s and we don't care about out-of-date data (big assumption, but not > > unreasonable), then use the Queue between A and B and simply have B empty > > the Queue on every iteration, processing only the newest data. This would > > keep the Queue to a reasonable size at the cost of dropping data. > > I suppose the acceptability of that depends on your requirements... > dropping data is never a very general approach. :-) Not general, but acceptable in cases where single blocks of data are less important than the flow of data (i.e. streaming video). This case sounds like it might fall into that category (I'm guessing it's simply updating a web page with snapshots of data), so dropping data would be an option. Of course, all this speculation only applies if thread B's processing time is >.1s and that the process is long-running enough that building a large queue would be an issue. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From tchur at optushome.com.au Sat Mar 16 10:31:58 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 17 Mar 2002 02:31:58 +1100 Subject: basic statistics in python References: <3C931C23.B0B2BF75@kfunigraz.ac.at> Message-ID: <3C93656E.7B02F53C@optushome.com.au> Siegfried Gonzi wrote: > > Tim Churches wrote: > > > Note that stats.py also returns the 2-tailed p-value as well (which can > > also easily be obtained from R via RPy). > > > > Tim C > > As a side note (but not related to the above problem): there exists also > some peculiarities with the R-language: "Particularities" might be a better word to avoid the perjorative sense of "pecularity". > > For example: > > > data <- c(0.23,1.0023,1.223,1.235,5.6,9.0,23.3456,34.458,34.56,78.9) > > > summary(data) > > delivers: > > Min. 1st Qu. Median Mean 3rd Qu. Max. > 0.230 1.226 7.300 18.960 31.680 78.900 > > Everything is correct, except the 1st quantile and 3rd quantile. You mean 1st quartile and 3rd quartile, not quantile. And the values calculated by R are not wrong, just different (see below). > > First, I could not believe it and fired up XLispStat: > > (setf data (make-array 10 :initial-contents '(0.23 1.0023 1.223 1.235 > 5.6 9.0 23.3456 > 34.458 34.56 78.9))) > > (quantile data 0.25) and (quantile data 0.75) respectively: > > delivers: 1.229 and 28.9018 > > The R-language calculates not only on Windows the values wrong; even on > Unix: the values are the same as on Windows. The results given by R are indeed the same on both platforms, but they not wrong. > > Maybe they use some other method for calculating the quantiles. There are a number of methods for calculating quantiles. In R, the summary() function calls the quantile() function to calculate the 1st and 3rd quartiles and the median. The quantile() function uses linear interpolation to calculate the sample quantile for the probabilities of 0.25 and 0.75, whereas XLispStat is just taking the arithmetic mean of the 2nd and 3rd, and 6th and 7th values respectively (using zero-based indexing/counting, since this is the Python list). The methods used by R are fully described in the R manual (see help(quantile)), but a commonsense explanation of the R approach is as follows (again using zero-based indexing/counting). If the number of elements is even, the median (50th percentile) is the average of the 4th and 5th (ordered) values, which can be thought of the the "4.5th value" i.e. half way between the 4th value and the 5th value. Note that (9 - 0) * 0.50 = 4.5. By extension, the 25th percentile (1st quartile) should be the "2.25th value" i.e. one quarter of the way between the 2nd value and the 3rd value (noting that (9 - 0) * 0.25 = 2.25), and the 75th percentile (3rd quartile) should be the "6.75th value" i.e. three-quarters of the way between the 6th and 7th values (noting that (9 - 0) * 0.75 = 6.75), which is what R returns. If you think about your sequence of numbers as an empirical distribution function, then the appraoch used by R makes better sense, IMHO. > > Personally: I can not cope with the R-language. It is rich of many > build-in functions; but most of the time I am not successful in finding > what I am searching for. The R documentation is very extensive - if printed, I think the manual for the base package runs to over 800 pages, and there are scores of extension libraries each with their own documentation on top of that. Finding the right function can require persistence - R certainly does not take a minimalist approach to built-in functions like Python does - but the online help/manual pages are searchable at the word level, so it is unlikely that you will fail to find something if it exists. > > The graphics are good; but I would always prefer Dislin as long as I do > not need any specialized graphics from the field of statistics. The main problem with Dislin is that it is not open source, nor is it free on Unix or Mac OS/X platforms. R is distributed under the GPL. > > In R one can even read in binary files (you can even swap the binary > order). But plotting a large array is a pain in the neck. In Dislin it > is very fast and one can overlay maps (e.g. coastlines) without any > problems (you get even the x- and y-axis annotation right: > -180E....+180W,...). There is a maps library available for R but geographical mapping is not its forte. Tim C From cja at dds.nl Tue Mar 26 11:34:01 2002 From: cja at dds.nl (Christopher Abraham) Date: Tue, 26 Mar 2002 11:34:01 -0500 Subject: Python Books Galore References: Message-ID: Raymond: It most certainly is a very fine sign. I am also interested, now that there are so many and not so few, in finding a great trinity of Python Books for use at work. One for introductory study, one for advanced technique, and one as a reference book. Of course, this could be as many as five-seven books, but three is a pretty appropriate number this week of any. Cheers, Chris In article , "Raymond Hettinger" wrote: [snip] > I went back yesterday and found a full row (3 1/2 to 4 feet) filled with > Python books. [snip] > This has got to be a good sign. From timr at probo.com Sun Mar 3 19:06:42 2002 From: timr at probo.com (Tim Roberts) Date: Sun, 03 Mar 2002 16:06:42 -0800 Subject: ADO GetRows() example for newbies References: <2030665d.0203010927.38edc51@posting.google.com> Message-ID: sam_collett at lycos.co.uk (Sam Collett) wrote: >How could you do pages of records (in ASP for example), you may only >want a few records at a time (if you have 1000 records for example)? >For example I may want a page with 10 records per page, with the page >numbers at the bottom. >For 100 records: >10 pages (10 links) >Start at 1 on page 1, 11 on page 2 etc) Unfortunately, this varies from SQL provider to SQL provider. In Postgres, for example, I can say: SELECT * FROM users ORDER BY lastname OFFSET 20 LIMIT 10; That fetches me records number 21 through 30. By changing the OFFSET value, I change which subset I get. SQLServer uses a different syntax. I believe "TOP" is the SQLServer equivalent of LIMIT, but I don't know how to do "OFFSET". Another alternative is to use a cursor, but again the implementation vaires by backend. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From shalehperry at attbi.com Fri Mar 1 01:19:25 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 28 Feb 2002 22:19:25 -0800 (PST) Subject: what does this do? (really basic question) In-Reply-To: Message-ID: On 01-Mar-2002 Dave Marotti wrote: > Hey, > > Hopefully this is a really basic question. I'm still in the learning phase, > and came across this in a sample program: > > class Whatever: > def __init__(self, user_list, cmd_list, **kw): > code.... > > What does the **kw mean (specifically, the **) ? > the kw is a nmemonic for 'keyword'. >>> def foo(**kw): ... print kw ... >>> foo(a=3, b=6, c='Sean') {'b': 6, 'c': 'Sean', 'a': 3} >>> foo(c='David', a=42, b=25) {'b': 25, 'c': 'David', 'a': 42} the ** syntax means 'take every argument that was not matches elsewhere and store it in a dictionary. The key will be the variable name and the value will be its value'. So self, use_list, and cmd_list will get their values and then kw gets the rest. >>> def bar(name, **kw): ... print name ... print kw ... >>> bar('Sean', a=1,b=2,c=3) Sean {'b': 2, 'c': 3, 'a': 1} >>> def wuz(name, age): ... print name ... print age ... >>> wuz(age=25, name='Lesley') Lesley 25 Note the key=value syntax works even without the **kw magic. The advantage of using the key=value syntax is that it makes functions with several arguments easier to call without reading the docs. This is often handy for things like GUI toolkits and network code: win = MakeWindow(title="My Window", width=100, height=200, x=34, y=67) or socket = Network.Connect(url="http://www.python.org", keepalive=1, port=80) From l0819m0v0smfm001 at sneakemail.com Sat Mar 9 13:09:51 2002 From: l0819m0v0smfm001 at sneakemail.com (Joshua Macy) Date: Sat, 09 Mar 2002 18:09:51 GMT Subject: PEP Parade References: <3C895594.60601@sneakemail.com> Message-ID: <3C8A161D.50601@sneakemail.com> Roy Smith wrote: > Joshua Macy wrote: > >> Just out of curiosity, what does the rest of your group develop in >>then? FORTRAN? COBOL? ("and none of this ANSI85 crap, either...it gets >>old trying to hit a moving target!") >> > > For internal tools, mostly perl. For production code, mostly C/C++ and TCL. > Perl's latest stable release is 5.6.1 My linux box has 5.005 installed standard, and I'm told that there are sites out there that are still chugging away on Perl 4. Meanwhile the latest development version of Perl is 5.7.3 and Perl 6 is in the works. If your fellow developers think that makes Perl stable compared to Python's rate of change, I think they're fooling themselves. Joshua From herrn at gmx.net Tue Mar 5 17:18:36 2002 From: herrn at gmx.net (Marco Herrn) Date: Tue, 5 Mar 2002 23:18:36 +0100 Subject: how to give an object as argument for a method Message-ID: <20020305221836.GA3612@lurkabove.darkstar> Hello, I am new to python and have a question how to achieve $subject. I want something like the 'this' statement in java that gives you the current object. So when I call a method like f(this) I give the object that calls the method as argument. But how can I do this in python? I am using python 2.1. Bye Marco -- This life is a test. It is only a test. Had this been an actual life, you would have received further instructions as to what to do and where to go. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From quinn at barf.ugcs.caltech.edu Thu Mar 7 13:55:36 2002 From: quinn at barf.ugcs.caltech.edu (Quinn Dunkan) Date: 7 Mar 2002 18:55:36 GMT Subject: overloading a function References: Message-ID: On Fri, 8 Mar 2002 00:36:46 +1100, Dave Harrison wrote: >Hi there all, > >If I have a function, but I want to be able to call it two different ways - the ways being differentiated by the paramaters I pass the function) how do I do this ?? > >At the moment I have > >def Foo(num) > >def Foo(num,dflt) > >however I am only getting the first of the two, and the second function is ignored. I think you mean you're only getting the second. The first is not ignored, but replaced, in the same way that 5 is when you type: x = 5 x = 10 >I couldn't find anything in the documentation, any ideas ? In the case above: def foo(num, dflt=None): if dflt is None: ... ... In general: class A: def foo(self, bar): ... class B: def foo(self, bar): ... import random x = random.choice((A(), B()) x.foo(42) The 'foo' called depends on the type of 'x'. You can't do this for anything other than the first argument though, since python is mono-dispatch. If you really wanted you could hack together a multi-dispatch situation: class Generic: def __init__(self): self.tab = {} def __call__(self, *args): # call before-methods? v = self.lookup(args)(*args) # and after-methods return v def lookup(self, args): ts = map(type, args) ... lookup ts in self.tab using whatever ordering rules you want def add_method(self, f, types) self.tab[types] = f def f_ints(x, y): return x + y def f_int_string(x, y): return '%d %s%s' %(x, y, x != 1 and 's' or '') f = Generic() f.add_method(f_ints, (int, int)) f.add_method(f_int_str, (int, str)) It's not very pythonic though. From Bill.Scherer at VerizonWireless.com Mon Mar 4 10:22:28 2002 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Mon, 4 Mar 2002 10:22:28 -0500 (EST) Subject: Rotor in Jython? In-Reply-To: Message-ID: On Mon, 4 Mar 2002 brueckd at tbye.com wrote: > Thanks for the interesting discussion. This thread is getting tired so > I'll let it die now. ;-) Yes, it was, but before the thread dies, did anybody have a chance to look at my code? (I know a few did, access_log says so...) Can anybody say why my code can decrypt messages it encrypts but not messages encrypted by stdlib rotor? Thanks! -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From pekko at iki.fi Fri Mar 22 08:55:55 2002 From: pekko at iki.fi (Pekko Piirola) Date: 22 Mar 2002 13:55:55 GMT Subject: GNU plotutils and Python? Message-ID: I tried to find the manual of the libplot module (Python bindings for Gnu plotutils package) but failed. Does it exists? Where? -- Pekko Piirola From mlh at vier.idi.ntnu.no Mon Mar 11 23:04:04 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 12 Mar 2002 04:04:04 +0000 (UTC) Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> <4abd9ce7.0203101059.444f1ec1@posting.google.com> <3C8BBFD4.A29A69F1@engcorp.com> <4abd9ce7.0203102128.67c7fa0d@posting.google.com> Message-ID: In article <4abd9ce7.0203102128.67c7fa0d at posting.google.com>, damien morton wrote: [...] > The existing mass of python code would be unchanged. What evidence do you base this on? > The only issue that might occur is that something that is now an > error, would not be. Assuming that this statement were true, how does it follow that 'the existing mass of python code would be unchanged'? As I am sure you are well aware, exception handling is an important part of the control flow in any Python program. If something that previously raised an exception no longer does, any program relying on that behaviour would be broken. Just to take a quick example -- checking whether a given string is a lowercase character: >>> from string import lowercase >>> def islowercaseletter(object): ... try: return string in letters ... except: return 0 ... >>> islowercaseletter('x') 1 >>> islowercaseletter('X') 1 >>> islowercaseletter(2) 0 >>> islowercaseletter('foobar') 0 If your suggestion was accepted, the latter would suddenly return true. And this is assuming that your statement is true -- which I really think it isn't. It would not be a simple matter of making this check illegal. You would have to sort out all kinds of things wrt. strings' relationship to sequences and how strings are iterable. Since the suggestion is full of inconsistencies, these would have to be patched up somehow. For instance, assuming that you still want to be able to iterate over the characters over a string (or, for that matter, still want to be able to use indexing or slicing on them), you would suddenly end up with the following oddity (among *many* others): >>> 'foo' in 'foobar' 1 >>> 'f' in 'foobar' 1 >>> 'foo' in iter('foobar') 0 >>> 'f' in iter('foobar') 1 Strings would then be the only (built-in or standard lib) iterable with this behaviour. > It remains to be seen whether or not the mass of python programmers > are opposed. I think this is as good as certain. > No-one has taken me up on my question about what circumstances one > would want "'fox' in 'the quick brown fox'" to throw an exception, > rather than return a result. Well, I've given you one example. But that is really besides the point. The point (as I see it, anyway) is that your suggestion either makes Python thoroughly inconsistent, or necessitates a very large change in the language core, removing the parts of strings that are polymorphically equivalent to sequences and other iterables. I think we'd end up with some very puny strings. What *is* strange is that the string method index() is not polymorphically equivalent to the list method index(). If one were to model the behaviour of the membership operator on that, one would end up with your suggested behaviour: >>> ['a', 'b', 'c'].index(['b', 'c']) Traceback (most recent call last): File "", line 1, in ? ValueError: list.index(x): x not in list >>> 'abc'.index('bc') 1 I must say I'm baffled by the fact that str.index accepts something other than a single character as its argument, but that's the way it is. -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From nessun at email.it Wed Mar 20 12:04:39 2002 From: nessun at email.it (Timothy Redaelli) Date: Wed, 20 Mar 2002 17:04:39 GMT Subject: Linker Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Does exist a liner for Python (to make .exe)??? Thanx - -- Timothy Redaelli -----BEGIN PGP SIGNATURE----- Version: PGPfreeware 7.0.3 for non-commercial use iQA/AwUBPJjBJBTIuDkXWv7oEQJlKQCdHcBysGNwHu7y3UsdWKE0w0LBTooAoNp8 Go+Ot0yVJiI1NIknudsuST71 =a8hl -----END PGP SIGNATURE----- From James_Althoff at i2.com Mon Mar 4 17:02:15 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 14:02:15 -0800 Subject: Status of PEP's? Message-ID: [Another poster] > Numbers don't perform operations [James Altfhoff] > they can > >>> -3 .__abs__() > -3 > >>> True. But your (aka *my*) point would probably be better made with >>> (-3).__abs__() 3 or >>> 3 .__abs__() 3 (Precedence wasn't the issue .) Jim From niemeyer at conectiva.com Sun Mar 24 01:27:40 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sun, 24 Mar 2002 03:27:40 -0300 Subject: C++ Embedding Problem - Import Error In-Reply-To: <3C9C4D48.7010000@SPAMnwinternet.com> References: <3C9C4D48.7010000@SPAMnwinternet.com> Message-ID: <20020324032740.B14400@ibook.distro.conectiva> [...] > Just to be clear, I'm linking libpython into another .so > lib that's dlopened by an app. There is no possibility of > linking Python directly with the app (or I wouldn't be > writing a plugin in the first place). You must open your plugin with RTLD_GLOBAL, otherwise the symbols inherited from libpython.a won't be available for the dynamic loaded modules. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From bokr at oz.net Wed Mar 27 16:34:02 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Mar 2002 21:34:02 GMT Subject: list comprehension question References: Message-ID: On Wed, 27 Mar 2002 17:24:02 +0100, Laura Creighton wrote: >It wasn't the Robot books where I was thiking of looking, but a different >short story. I actually believe that apologies are something which >are necessary due to one's-own need to behave rightly, rather than >somebody else's need to receive redress. A society with both ISTM apologies are part of a very stateful communication protocol of humans, trying to manage state transitions at both ends. Both ends, depending on sophistication, include cached recursive models of the state at the other end, leading to complex calculations for maintaining the cache and generating communication signals, e.g., "She may be thinking that I think xxx and if I format my apology message with content yyy and my assumption about her thinking is wrong, it may lead down a bad part of the trellis of possible futures, so I will say zzz hoping to prevent a disconnect at least, also hoping that she does not infer too much calculation on my part and transition to impersonal mode, setting filters to deny warm fuzzy metasignals, requiring total renegotiation of that subchannel's connection, but also trying to prevent a transition in presumed respect relationship by not formatting an overly obsequious apology, and to hell with it: msg= "Let's cut the BS, do you want this relationship or don't you?" "Is that a threat or a question or a pecking order position assertion or all of the above?" (meta)"Sorry, ..." negotiate, negotiate, negotiate... You can imagine a politician's "need to behave rightly" and a true spiritual seeker's "need to behave rightly," interacting over some occasion for apologies. Imagine the states and cached other-site-model states. The first problem is to find a layer in the communication stacks that halfway matches ;-) Now imagine a true spiritual seeker in the role of politician. Very complex state management ;-) IOW, I think the "need to behave rightly" is as complex as humans, and based in large part on the need to maintain communications for cooperation in survival. And apologies are part of the communication protocol. By apologizing, you do not just satisfy your own need to act consistently with your concept of yourself (whether saint, good girl, or smooth con), unless you are living in a world where others are just incidental props that you don't relate to beyond their cliche proxy representations in your imagination. The "need for redress" in the other, if present (other than material damage/reparation issues), is ISTM a need be able to permit themselves to continue communicating in a valued interchange. IOW, the other may have protocol rules that do not permit needed communication, and the "need for redress" is a need to satisfy that protocol, so that the other may permit him/herself continued communication. "I won't talk to you until you apologize properly." And other than saints, people have a hard time moving from that state without satisfying a redress protocol. Fortunately, the bots of the P >Asimov-type robots and small children needs to do something >about the small child's propensity to order the robot to go jump >out the space station airlock. When Mom says 'decent children don't >order robots to do foolish things' she can't make an appeal to the >robot's feelings, but to other things such as the anti-socialness >of waste. Once such considerations come into play, the social value >of apologising needs examination -- and certainly, in a society which >is not based on enslavement, there is no room for somebody who is >'too big to apologise'. People who regularily avoid apologising when >they know perfectly well that they are in the wrong need to do so far >more for themselves than for other people. That is trying to opt in and >out of society whenever it suits you. > They first need to reach a state where they have a non-sociopathic motivation for an apology. ISTM that is what you are pointing to. Some people's abuse of human protocol is itself a signal in another (distasteful and destructive) human communication protocol. I.e, the meta-message is, "I do this to assert that I am powerful enough to provoke without expectation of challenge, and I expect to accomplish my goals through exercise of commanding power." Of course, the meta-meta message is a pitiable despair of working in real human relationships. Unfortunately, that doesn't mean you may not some time have to kowtow to someone pitiable ;-/ >Now I remember reading this and thinking this was pretty powerful stuff >when I was 14 or so. And nun-dominated boarding school, where I escaped >classes that I was not interested in taking by illegally clibing trees, >reading books where I could not be found since 'tree-climbing' was so >much more forbidden than cutting physical educaiton classes that nobody >thought to look for me in the trees. I'd sit in the top and watch them >seek and call for me at ground level. > Ah, memories ;-) >Since thoughts that 'leopards kill their prey by dropping on them out >of trees' featured hightly in my thoughts at such a time, the discovery >that I might be damaging myself by opting out of society hit rather hard. >And I believed that it was Asimov who mentioned that -- until today. It >doesn't sound like him. It sounds more like Heinlein, but the Heinlein >fans have posted every satement he has ever written to the net, so if >I can't find it there, it is almost certainly not from Heinlein. (He >does state this: > > In a family argument, if it turns out you are right - apologize at once! > But patronize and you will be disconnected at an important level. Of course, if you feel motivated to patronize, you are already there ;-/ >But it is doubtful that this quote would have had such an effect on me, >my status as 'woefully misunderstood intellectual' was running at an >all time high then. But figuring out if I wanted to reject all of society >or only my status as child within it was a nice problem. And, arrogant >worm that I was, I took great comfort in the fact that all the people whom >I felt owed me apologies, (and there was quite a list) were secretly >damaging themselves in nasty permanent ways. It was only much later >that I was able to connect their ability to treat me and the other children >so cruelly with the sort of damaging they were doing by not apologising. > Again, I think it's a protocol-abuse meta-protocol based on power when direct. Indirectly, a cruel disconnect can happen when adults see children as aforementioned "incidental props" and simply don't recognize the possibility of dialogue with and caring respect for a being at another stage of development. >However, all of this would only have been funny if the quote about half >of the apologising being for yoruself was from Asimov. In usenet fashion >I will find the answer to who wrote this about 20 minutes after I post this. And also figure out how it relates to list comprehension ;-) Regards, Bengt Richter From Oschler at earthlink.net Sun Mar 31 19:55:04 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 31 Mar 2002 19:55:04 -0500 Subject: Python/Linux References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: Forgot to ask, is Zope's database server actually MySQL under the hood? If not, does it compare well as far as functionality and stability are concerned? BTW, do you use Zope or Quixote? Hope you don't mind all these question. thx Aahz wrote in message news:a886hv$st6$1 at panix1.panix.com... > In article <0UMp8.42204$1f1.3348597 at e3500-atl2.usenetserver.com>, > If you're using Python, go with either Zope or Quixote. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Why is this newsgroup different from all other newsgroups? From sandskyfly at hotmail.com Sat Mar 30 01:23:07 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 29 Mar 2002 22:23:07 -0800 Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> <67abb823.0203291213.3870b623@posting.google.com> Message-ID: (Sloth) wrote in message > Again, thanks for all of the thoughtful replies. I've tried each of > them, and I still get the same result: > 1) The server starts and will serve HTTP. > 2) Upon submitting a GET request, the Windows ME OS "beeps" once > 3) The page hangs without returning the result. > 4) The WinME machine needs to be powered down completely, or it will > hang indefinitely. Yes it is strange. I can't help you with beeps or hanging or with win95/winME, but often with some more testing you can 'hopefully' get a better idea of what's going on: [A] modify the cgi-script to enable cgitb debugging (which comes with py2.2) this will show pretty tracebacks if possible: #!python import cgi, cgitb; cgitb.enable() # <<< add this print "Content-Type: text/plain\n\n" form = cgi.FieldStorage() for name in form.keys(): print "Input: " + name + " --> " + form[name].value + "\n" print "Finished!" [B] run your cgi script directly from the commandline. For example: C:\server\cgi-bin> python testcgi.py query=hello Content-Type: text/plain Input: query --> hello Finished! C:\server\cgi-bin> If you still can't get to the root of the problem, then it may be due to issues that are specific to a python WinME interaction: perhaps something to do with w9xpopen.exe ?? Pure speculation at this point... BTW: I've tested my earlier example on winXP and it works fine. good luck, Sandy From mwh at python.net Tue Mar 19 13:55:11 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Mar 2002 18:55:11 GMT Subject: RELEASED: Python 2.2.1c1 References: Message-ID: Steven Majewski writes: > I got the same on my osx build. > Specifically: math.sqrt( -1 ) returns NaN. Yes, it seems BSD libm returns NaN and does not set errno when sqrt(-1) is called. That's good -- this is the sort of thing I was hoping to learn. People can stop reporting this particular case of it now though, thanks. Cheers, M. -- You sound surprised. We're talking about a government department here - they have procedures, not intelligence. -- Ben Hutchings, cam.misc From peter at engcorp.com Fri Mar 15 19:01:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 15 Mar 2002 19:01:26 -0500 Subject: does Python support some kind of "casting" References: <3C91F472.FB2B67C7@engcorp.com> Message-ID: <3C928B56.F36982A2@engcorp.com> Rich Harkins wrote: > > On Friday 15 March 2002 08:17 am, Peter Hansen wrote: > > Get over it. 3600 elements is nothing, especially once you realize that > > the strings themselves are not duplicated, just the references. > > > Isn't there some additional overhead (above copying the underlying C array > for the list) in having to bump each refcount of every object contained? Yeah, like a few tiny C instructions... don't get concerned over the performance at that level when writing Python. You are already writing code between 10 and 100 times slower than equivalent C in most cases, so a few extra microseconds doesn't amount to much. Then, too, there's how often the routine will execute. A lot of people wondering how to optimize something when they haven't even benchmarked it and found it lacking against some real need for speed aren't even planning to run the code very often! Sometimes these are little one-shot utilities which you might run a few times a day, and any savings will amount to less time over the lifetime of the code than the extra time spent optimizing... > This would appear on the surface to be not trivial when the number of > referenced objects becomes large, It's still trivial, considering that it scales as O(n) so you won't notice it whether it's 10 items or 10,000 items. The overhead of Python in other respects is much more than the ref-counting. > OTOH, I do wonder if some form of list-based buffer() would be useful in > these cases, so that you can take a slice of a list, bump the list's refcount > without bumping the referenced objects You could implement this with some kind of unmutable list object if you wished. If you guarantee you won't modify the list content, you get this for free with the current implementation, just by binding the object to another name... -Peter From db3l at fitlinxx.com Wed Mar 13 18:42:28 2002 From: db3l at fitlinxx.com (David Bolen) Date: 13 Mar 2002 18:42:28 -0500 Subject: [ANN] istring 1.0.1 released; announce list created References: Message-ID: "Bjorn Pettersen" writes: > Except that's not how SQL is quoted (It should have been 'O''Hara'). > Besides, anyone not using bound variables must be crazy Or looking for performance. In some environments (e.g., remote access over dialup with ODBC), issuing an ExecDirect() call with a simple string can be significantly faster (e.g., a ways back I was in an environment where the difference was 2-3x) than using bound variables which requires additional server requests along the way. I don't disagree with the underlying sentiment that letting the driver handle DB-specific quoting issues is a cleaner way to go, but it does also carry some disadvantages at times or in some environments. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From bokr at oz.net Sat Mar 9 16:29:09 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 21:29:09 GMT Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: On Sat, 9 Mar 2002 13:09:39 +0000, philh at comuno.freeserve.co.uk (phil hunt) wrote: [...] > >One possibility might be a new looping construct, do: > > do 5: > print "this will be printed 5 times" > >Note that you can't get hold of a do loop's loop variable. This >would be easy to optimise, I imagine. Well, since we're messing with the language, keywords could have attributes, e.g., do 5: print "index from the do: %d", do.index or for x in aList: print 'Item %2d: %s' % (for.index, x) I'm not serious, I think ;-) Regards, Bengt Richter From dyoo at hkn.eecs.berkeley.edu Fri Mar 1 02:42:12 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 1 Mar 2002 07:42:12 +0000 (UTC) Subject: ANN: SV-SF Bay Area Python user grp (BayPIGgies) mtg 3/13 7:30pm References: Message-ID: wesc at deirdre.org wrote: : When: March 13, 2002, 7:30-9pm : Where: Stanford University, Palo Alto, CA : Title: BioPython : Jeffrey Chang (School of Medicine, Stanford University) founded the : BioPython project in 1999 to promote the development of shared software : infrastructure in bioinformatics. His talk will cover the architecture : and capabilities of Biopython and also give a sneak preview of the : upcoming version. Expect to see a crowd of biologists there as well. I told my boss to make an announcement about it too. We should bring refreshments this time. *grin* From phd at phd.pp.ru Thu Mar 21 15:19:48 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 21 Mar 2002 23:19:48 +0300 Subject: Painful apache compilation In-Reply-To: ; from sorpippo@libero.it on Thu, Mar 21, 2002 at 09:07:22PM +0100 References: Message-ID: <20020321231948.A14687@phd.pp.ru> On Thu, Mar 21, 2002 at 09:07:22PM +0100, Giuseppe Ricioppo wrote: > I am attempting to compile apache+mod_perl+php+mod_python. > When I run make the result is... > ##################### > ......snipped for brevity..... > ........................................... > /usr/src/Python-2.2/libpython2.2.a(thread.o): In function > `PyThread_start_new_thread': > /usr/src/Python-2.2/Python/thread_pthread.h:174: undefined reference to > `pthread_sigmask' Ever tried to read mod_python instllation instructions? You are trying to compile thred-enabled python with nonthreaded Apache. Don't do that. Recompile python without threads. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From bokr at oz.net Sun Mar 10 19:41:56 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Mar 2002 00:41:56 GMT Subject: How to disable assert statements inside a module? References: Message-ID: On Sun, 10 Mar 2002 16:17:01 -0500, Tim Peters wrote: >[Pearu Peterson] >> Is there a way to disable all assert statements inside a module, >> and without calling python with -O switch? > >[Martin v. Loewis] >> You can set __debug__ to 0 on the module level; this will disable >> assert statements inside this module. > >Note that assignment to __debug__ was deprecated in 2.1: > > SyntaxWarning: can not assign to __debug__ > >and removed in 2.2: > > SyntaxError: can not assign to __debug__ > >-O is the only way left. Guido often writes code under the control of an >explicit "debug" vrbl instead. A more flexible way to control asserts would >be (IMO) prime PEP material (as a heavy assert user myself, I sympathize >with Pearu's dilemma -- "all or nothing everywhere" is too crude for large >projects with many subsystems). > Controlling logging would also be handy. I.e., not just controlling its execution, but including/excluding it from compiled code. Play with the idea of a built-in compiler line filter based on name token matching: E.g., the compiler could include or exclude lines with the name token 'assert' by default, depending on allow/deny config data set up or overridden in site.py, and possibly overridable within a module scope. This could be controlled globally also by command line option. You could exclude whole imports by filtering on the module name, and thus exclude the import effects. By suitable naming (even just using modulename.xxx for all uses, and isolating them on single lines), you could leave a lot of cruft in the source and not suffer performance hits in execution of .pyc's. Conventions for default exclusions of enableable standard modules (and calls using them) like the proposed logging module could be established. Regards, Bengt Richter From martinkaufmann at yahoo.com Wed Mar 13 06:50:30 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Thu, 14 Mar 2002 00:50:30 +1300 Subject: Question about scientific calculations in Python References: <3C8DFF7B.7EF0EAC6@kfunigraz.ac.at> <9dvs8u8aulpr2ceppipnakdk78e9bipneo@4ax.com> <3C8F1E7F.715A6E45@kfunigraz.ac.at> Message-ID: <2leu8uk4gg01dnqej2tr9q8rdfl9d6b2la@4ax.com> On Wed, 13 Mar 2002 10:40:15 +0100, Siegfried Gonzi wrote: >The speed/tuning problem only emerges when one knows about the speed of >an equivalent code lets say written in C++ or Fortran 90. It is >comprehensive that then one does ask: "What are the reasons for, and why >should I just use the slow one". The problem is that my colleague has a similar program written in C. He has only to wait for about two seconds while my first Python implementation needed about 30 s (for a small cluster...). >But you should re-think your stance. I can assure you, that normally >people are not complaining about speed in >Matlab/IDL/Python/Mathematica/Yorick/Octave,... as long as they do not >compare it to C++ or Fortran 90. But most of the people in our Department know that there is a faster possibility (even if they don't use it...). >They even write simulations in IDL (whenever you see a high resolution >solar granulation image, it is likely that they did it in IDL; at least >my colleague in front of me). Personally, I think they are in error as >long as they write such stuff in IDL, because it is questionable to make >ones code (more than 1000 lines of code) dependent on one company. Our best number crunching machine was blocked with four IDL jobs over the weekend... >If you are going to decide whether you should learn C or C++, I want >suggest you to dive in to C++ or Fortran 90 directly (If you are a >scientist I can ssure you that nobody on earth will ever pay you money >that you can show how C works). You should just starting to use valarray >and the like. Is it much more time consuming or difficult to learn directly C+1 instead of C? I'm aware that the knowledge of C++ could be quite helpful outside University. But last year I even got paid for _learning_ Python... >I am not a C++ advocate (nor I am a Fortran 90 junkie, either), but >maybe the following (a little bit biased towards C++) article will help >you during your reasoning-study: > >www.amath.washington.edu/~lf/software/CompCPP_F90SciOOP.html Thanks for this interesting article. My conclusion is (although I didn't read it thoroughly yet) that I would rather go for C++ than for Fortran. Thanks, Martin From peter at engcorp.com Tue Mar 19 22:01:30 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 19 Mar 2002 22:01:30 -0500 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> Message-ID: <3C97FB8A.5B9E9247@engcorp.com> Ahmed Moustafa wrote: > > 1. Where can I find an unbiased comparison between Java and Python? > 2. Will Python dominate? > 3. Who does support Python? Having read the other responses, you may see that your questions are a little simplistic. I think if you told us what your purpose is in asking the questions, the answers would be more useful and direct. _Why_ do you want to know? -Peter From gerhard at bigfoot.de Thu Mar 14 22:01:55 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 15 Mar 2002 03:01:55 GMT Subject: Dear Guru, I have added def and it doesnt work Sincerly, F References: Message-ID: phil hunt wrote in comp.lang.python: > On 15 Mar 2002 01:12:23 GMT, Gerhard H?ring wrote: >>Oscar wrote in comp.lang.python: >>> I have added >>> >>> def joinsplit = (join(split(lines, '"'), ' ')) >>> return joinsplit >> >>No wonder this doesn't work, as you've apparently haven't made very >>much effort to understand what you're doing here. >> >>Sorry to be so blunt, but you can't write software just by guessing >>about the syntax. > > Really? I do some of the time, when I don't remember it and can't be > bothered to look in the manual. Me too, mostly by trying stuff out at Python prompt, for instance if I forgot the semantics of slicing again. > The surprising thing is, the rest of his defs are OK. Not surprising: somebody else wrote that code. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From jason at tishler.net Fri Mar 15 09:28:38 2002 From: jason at tishler.net (Jason Tishler) Date: Fri, 15 Mar 2002 09:28:38 -0500 Subject: (Cygwin) Python Questions In-Reply-To: <00fc01c1cc01$0062e7c0$5b1a430a@industrie.capgemini.fr> References: <00fc01c1cc01$0062e7c0$5b1a430a@industrie.capgemini.fr> Message-ID: <20020315142838.GA2312@tishler.net> Stephane, Please post instead of sending private email. On Fri, Mar 15, 2002 at 10:08:39AM +0100, Stephane Tallard wrote: > I'm the one you advised some days ago to use Cygwin Python to resolve my > problem of rederecting python scripts ouptput under cygwin rxvt. > > I've followed that wise advise. I've use used Cygwin Python for basic > scripting tasks and I feel very pleased to > use on my Windows platform the flavor and robustness of unix. > > But, "appetite comes while eating" and I expect my job to turn into more > on-the-cutting--edge tasks. > I thank you in advance for the time you could spend answering my questions. > > Basically, what's the difference between Cygwin-Python and regular-Python ? Cygwin Python is essentially a Unix Python that is dependent on the Cygwin Posix emulation DLL for Posix semantics. By "regular" do you mean Win32? If so, then Cygwin and Regular Python are "very" different even though they run on the "same" platform. Just compare Win32 Python to any Unix one to see what are the major differences. > They link with different libraries? Yes. > They need different dynamic libraries? Yes. > The both of two? Sorry, I don't understand the above question. > That question was for my personal information . What I would finally know is: > If I want to shift from python 2.1. to Python 2.2 can I use > frankly the www.python.org 2.2. package ( It would sound strange to me ). I think so, but I don't quite get this question too. > If there is a new release of python, will there be a > corresponding cygwin release in the same manner I can find a sun, win32 or > whatever release ? Yes, Cygwin Python 2.2 already exits: http://cygwin.com/ml/cygwin-announce/2002/msg00001.html > I would like to know too if there are some limitations in using python > packages. I suppose there 's no limitation in using packages that > don't use dynamic libraries. But Is is the same thing to usepackages that > use dynamic libraries linking with non cygwin compliant modules ? > Are there comptibilty problems? There could be -- shared extensions are not guaranteed to run on all platforms. Hence, some porting effort may be required by you if they don't already run on your platforms of interest. > PyXML and perhaps wxWindows are packages I could use. Sorry, I don't about the portability of the above. Maybe someone else does. Jason From fschaef at ces.clemson.edu Thu Mar 7 05:40:25 2002 From: fschaef at ces.clemson.edu (Frank Schaefer) Date: Thu, 07 Mar 2002 05:40:25 -0500 Subject: memory management Message-ID: <3C874399.4060503@ces.clemson.edu> Dear Fellows, My python script uses extensively memory. How can I ensure that it is de-allocated after use. What functions are there to determine the size of an actual python object (deep vs. shallow size or so?) ? thanks, Frank. From peter at engcorp.com Wed Mar 20 19:52:11 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Mar 2002 19:52:11 -0500 Subject: bug tracking system References: <3C9836DF.1E877634@engcorp.com> Message-ID: <3C992EBB.439138DB@engcorp.com> Peter Hansen wrote: > > mohamed lazreg wrote: > > > > Dear pythoners, > > > > Are you aware of any free bug tracking system written > > in python? > > Several based on Zope... (http://www.zope.org) Jeff Blaine asked offline what those were. I don't recall the specific names, but a visit to http://www.zope.org/Products/content_object following by a search for "issue tracker" would bring up the names of the ones I was thinking of. Note that those were not designed specifically as bug trackers, but I've found it much more effective to have a single "issue tracker" than a set of dedicated specialized trackers for bugs, requirements, todo items, and so on. Much better to view bugs as "just another kind of issue", AFAIAC... -Peter From bokr at oz.net Sat Mar 2 18:22:36 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Mar 2002 23:22:36 GMT Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: On Sat, 02 Mar 2002 00:22:58 GMT, mats at laplaza.org (Mats Wichmann) wrote: >Note: this is not a Python question per se. > >I'm looking for a piece of software to aid in reviewing a document >through the web - click on a paragraph tag, have the comment added >(highlighted in some way). The wiki style doesn't seem to quite do it, >as the core document is not protected. I haven't found much in web >searches, and nothing where the software seems to be free. > >I'd of course love it if this were done through Python since I'm on a >bit of an advocacy kick...but in the end it doesn't matter much. >Anybody know if anything like this is happening in any of the web >services projects? > If it doesn't have to be too slick, I think you could write relatively simple cgi to do it, depending on what you mean by "document". Also, with a small collection of doc text pages and a few occasional user/reviewers you could get away with something that wouldn't scale to a massive online catalog with graphics layout and thousands of reviewers. I've thought it would be nice to have something like that for collaborating on documentation and/or maybe PEPs. What kind of docs are you dealing with? Regards, Bengt Richter From grante at visi.com Thu Mar 28 18:38:49 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 28 Mar 2002 23:38:49 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <001d01c1d67f$2eb81090$445d4540@Dell2> Message-ID: In article , Steve Holden wrote: > Emile's reply reminds me that, when told one should not end a > sentence with a preposition, Winston Churchill replied "This is > something up with which I will not put". That reminds me of an old joke... His first day on campus at Harvard, the new freshman from Brooklyn stopped an upperclassman and asked "Excuse me, can you tell where the library is at?" The upperclassman replies "Here at Harvard, we do _not_ use prepositions to end sentences." The freshman reponds with "Uh, thanks. Can you tell me where the library is at asshole?" -- Grant Edwards grante Yow! NOW, I'm supposed at to SCRAMBLE two, and HOLD visi.com th' MAYO!! From aahz at pythoncraft.com Sun Mar 31 12:26:48 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 12:26:48 -0500 Subject: Most important extensions? References: <20020331112707.353$Hl@news.newsreader.com> Message-ID: In article <20020331112707.353$Hl at news.newsreader.com>, Hernan M. Foffani wrote: >"Aahz" escribi? en el mensaje >> >> Pmw does, but that's the only one. Sorry for not making clear that I >> was specifically referring to 3rd-party extensions. > >I'd think win32all may apply then. But you said OSCON, so.... ;-) I'm adding it to my list of proposed extensions (and it'll likely be one of them, in the end). OSCON is pro-Open Source, not anti-Windows. (There are plenty of presentations on using Open Source effectively under Windows.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From henning at users.sf.net Sat Mar 16 10:31:28 2002 From: henning at users.sf.net (Henning Schröder) Date: Sat, 16 Mar 2002 16:31:28 +0100 Subject: Connecting to a Gnutella-network References: Message-ID: Hi! > I've looked at the Gnutella Protocol, v.0.4, and wondered about trying to > create an implementation in python. [..] > Has anybody tried to do this before? Does anybody have pointers for newbies > like me in such a project ( how to start, how to connect to nodes on a > gnutella network etc. ) I started a module. Currently it cannot serve files and it's not thread-safe (any help?) but it can connect and search for content. I used the protocol specification to implement it. See http://www.gubba.org/modules/gnutella.py It's probably a good start ;-) Henning From brian at lodoss.org Sun Mar 3 21:04:04 2002 From: brian at lodoss.org (Brian) Date: 3 Mar 2002 18:04:04 -0800 Subject: Newbie ?:A more concise way? Message-ID: <8fc4b19e.0203031804.75d303a3@posting.google.com> Regarding: z = [MyClass() for i in xrange(y)] Is there a way to do this without the use of i? Thanks! From p.magwene at snet.net Sat Mar 16 12:19:35 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sat, 16 Mar 2002 17:19:35 GMT Subject: basic statistics in python References: <3C931C23.B0B2BF75@kfunigraz.ac.at> Message-ID: On Sat, 16 Mar 2002 10:31:58 -0500, Tim Churches wrote: >> The graphics are good; but I would always prefer Dislin as long as I do >> not need any specialized graphics from the field of statistics. > > The main problem with Dislin is that it is not open source, nor is it > free on Unix or Mac OS/X platforms. R is distributed under the GPL. > > You're correct about DISLIN not being open source. More than once I've wanted to pry the top off and peer inside to fix a minor buglet. However, I must say that Helmut Michels has been VERY responsive to bug reports or inconsistencies I'v reported, usually issuing fixes with 48 hours. Note, that if you're interested in using DISLIN with Python, it IS free on all the supported systems. To quote from the DISLIN web page: "The DISLIN plotting extensions for Java, Python and Perl and the DISLIN interpreter DISGCL can be used freely on all operating systems." --Paul From cfox at crystalcherry.com Thu Mar 14 20:17:27 2002 From: cfox at crystalcherry.com (Colin Fox) Date: Fri, 15 Mar 2002 01:17:27 GMT Subject: Python2.2 and expat Message-ID: Hello, everyone. I'm trying to build garnome, which requires Python2.2 + Python2.2-xml. I've got Python2.2 built, but for some reason it doesn't seem to build expat. And when I try to "import xml.parsers.expat" I get: >>> import xml.parsers.expat Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.2/xml/parsers/expat.py", line 4, in ? from pyexpat import * ImportError: No module named pyexpat Where is pyexpat supposed to come from? TIA Colin -- Colin Fox cfox at crystalcherry.com CF Consulting Inc. GPG Fingerprint: D8F0 84E7 E7CC 5C6C 9982 F1A7 A3EB 6EA3 BC97 572F From bokr at oz.net Tue Mar 12 20:13:13 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Mar 2002 01:13:13 GMT Subject: RFC PEP candidate: q''quoted ? References: Message-ID: On Tue, 12 Mar 2002 22:18:09 +0000, philh at comuno.freeserve.co.uk (phil hunt) wrote: >On 3 Mar 2002 09:50:58 GMT, Bengt Richter wrote: >>Problem: How to put quotes around an arbitrary program text? > >I assume you mean here a *Python* program. As the destination context, yes, but for the quoted matter, not necessarily. > >> assert q'<-=delim=->'content here<-=delim=-> == 'content here' # this would be true >> >>without getting an error. > >Looks a bit complex. What if you have a quoted string inside a >quoted string, e.g, you want to quote this: > > list = [1, q'|'string|, 3] > >if you just choose the same dewlimiter for the next time, it fails: you wouldn't choose the same delimiter ;-) I.e., the main point of using an (almost) arbitrary sequence of characters as a delimiter is so you'll always have a choice of new delimiters if you need them to wrap around text containing old ones. > > q'|'list = [1, q'|'string|, 3]| > >as this would parse as the string "list = [1, q'" followed by a >syntax error. Of course, you could choose another delimeter, but >it'd be nice if this could be done automatically by a simple-minded >program. That could be arranged. > >Lisp is famous for being able to quote program text. The way it >manages it is by using (...); this is possible because any brackets >inside must match. Let's try this for Python, using {} instead of >(), to prevent it from looking like a function call: > > list = [1, q{string}, 3] > >and: > > q{list = [1, q{string}, 3]} > >This works. The reason it works is that the outer '{' only tries to >connect to the matching '}'. Inner braces are matched with >themselves; braces inside normal strings or comments are ignored. > But text with matching braces or matching whatever doesn't qualify as arbitrary content. E.g., you should be able to quote a broken lisp program if you want to. >>Note the lack of quotes around the final delimiter string, since it itself is >>the final delimiter. This can also be used to solve the final unescaped >>backslash problem for quoting windows paths: >> >> q'|'c:\foo\bar\| > >"""c:\foo\bar\""" and r"c:\foo\bar\" work just as well. > You didn't mean that ;-) >>> """c:\foo\bar\""" ... ... (it's waiting for three unescaped quotes in a row) ... """ 'c:\x0coo\x08ar"""\n\n(it\'s waiting for three unescaped quotes in a row)\n' >>> >>> r"c:\foo\bar\" File "", line 1 r"c:\foo\bar\" ^ SyntaxError: invalid token >>> BTW, q'"""'c:\foo\bar\""" and q'"'c:\foo\bar\" would work, if you wanted to use """ and " as q-delimiters, because *all* escape characters are ignored in the content. >The best solution, of course, is to not use Windows. > You probably did mean that ;-) Regards, Bengt Richter From grante at visi.com Tue Mar 12 18:16:06 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Mar 2002 23:16:06 GMT Subject: struct.calcsize() giving odd results References: <3Rvj8.27781$af7.23161@rwcrnsc53> Message-ID: In article <3Rvj8.27781$af7.23161 at rwcrnsc53>, John Purser wrote: [regarding struct size that isn't what he wants] > And that's it. I tucked this into a variable (fmt) and ran it through > struct.calcsize(fmt) and got 190. I assumed I'd made a typo so I went over > my string. No problems there. So I assumed I added it up wrong in the > first place. Nope, 180 bytes. By default, struct will use the alignment/packing conventions used by the native C compiler. If you want something else, you've got to specify it. Try adding a "=" to the front of your format string. -- Grant Edwards grante Yow! ALFRED JARRY! Say at something about th' DEATH visi.com of DISCO!! From maxm at mxm.dk Wed Mar 20 12:20:17 2002 From: maxm at mxm.dk (Max M) Date: Wed, 20 Mar 2002 17:20:17 +0000 Subject: classes for fun and newbies References: <3C989D10.5070409@mxm.dk> Message-ID: <3C98C4D1.4040606@mxm.dk> Bruce Dykes wrote: > From: "Max M" > Is there any particular reason to prefer using functions over class > definitions, such as performance, or memory use? Or are we just speaking of > stylistic differences? I would choose one over the other for pragmatic reasons. If I was doing a one off job I would choose:: for line in lines: id, date = line[0:5], line[6:11] print id as it is really simple to write and read. Everybody can understand what it does. And It's easy to read later. On the other hand if you want to use your class as a basis for a whole series of script I would use my last approach, with a "list" object containing all of the 'records' as this makes for really simple code in all of the scripts using the objects. The first version is easier to write, understand and use, the latter is easier to re-user :-/ Your approach is sort of a half-way solution where you are in fact using an objects as a "complicated function". compare: f = open('today.log', 'r') log = f.readlines() print call_record.record_id(log[1]) for rec in log: print call_record.record_id(rec) f.close() With: log = Log('today.log') print log[1].record_id for rec in log: print rec.record_id I think you will agree that it gives a much cleaner and more readable api. Especially: call_record.record_id(log[1]) is more convoluted than nessecary and sort of counterintuitive. Well at least for me ;-) There would be nothing wrong with rewriting my "Rec" class to be more in line with yours: class Rec: def __init__(self, line): self.id = line[0:5].strip() # also remove whitespace self.date = line[6:11].strip() class Log: def __init__(self, fileName): f = open(fileName,'r') self.lines = f.readlines() f.close() def __getitem__(self, index): return Rec(self.lines[index]) def __len__(self): return len(self.lines) Especially if you import the Log class in a lot of other scripts. Then all of the little ekstra code adds up. > aside: I realize that I'm actually building the guts of a database, but for > something this small, it seems far more efficient to simply write the > necessary text processing and search functions than to build a database in > MySQL or PostgreSQL and then build the necessary connections and filters. A > couple of Python scripts *must* be more lightweight than a fullbore > database. What you are doing is a perfectly ok use of resources. regards Max M From gminick at hacker.pl Wed Mar 27 07:57:46 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Wed, 27 Mar 2002 12:57:46 +0000 (UTC) Subject: Random... References: Message-ID: ** Since micro$oft is stupid it doesn't mean ** that you should be stupid too - do NOT toppost. Dnia Mon, 25 Mar 2002 18:52:25 +0100, FREDRIK HULDTGREN napisa?(a): >I want to generate random numbers, very large random numbers. If I use >randrange() I get an out of bounds error since it only supports numbers >up to (2**31)-1. However, I can use uniform(), but then I get the number >returned in 7.9655120654553743e+018 or something simaler, and I would >rather have it in a "L" format(796551206545537430183218312890381031L). >How do I do this? HTH. -- [ Wojtek gminick Walczak ][ http://hacker.pl/gminick/ ] [ gminick (at) hacker.pl ][ gminick (at) klub.chip.pl ] From scarblac at pino.selwerd.nl Sun Mar 10 07:12:10 2002 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 10 Mar 2002 12:12:10 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> Message-ID: brobbins333 at shaw.ca wrote in comp.lang.python: > I understand the problem of rounding errors with binary numbers. > However, the rounding functions of other languages work around it and > return a usable result. What have they got that Python hasn't got? The other programs are liars - they show a rounded result, the way Python's print does. It is not possible to represent 56.79 in a finite binary float - it's a repetitive fraction in binary. Python decided not to hide this in the interactive interpreter. If you print out a number, it looks the way it does in other languages. Under the hood, they all do the same thing. -- Remco Gerlich From dsavitsk at e-coli.net Wed Mar 27 21:55:31 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 28 Mar 2002 02:55:31 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: "Shiv Shankar Ramakrishnan" wrote in message news:3ca27d3d at news.microsoft.com... > Anyone knows just what in the world is going on? Has something happened > (heaven forbid!) to the lead dev for ActivePython that they are so woefully > behind now? Or is ActiveState not bothered about Python at all and more > bothered about other things like Perl, Komodo etc? Thats their preorgative > of course but I like the PythonWin IDE and now I can only get that with > ActivePython since Mark Hammond moved there. He is no longer there. > Shouldn't there be some > alternative source for getting PythonWin? How about the main Python > distribution also doing PythonWin from CVS? the "alternate source" for PythonWin is Mark's home page http://starship.python.net/crew/mhammond/ replete with a version for 2.2 -d From WECaputo at thoughtworks.COM Sat Mar 9 13:34:19 2002 From: WECaputo at thoughtworks.COM (WECaputo at thoughtworks.COM) Date: Sat, 9 Mar 2002 12:34:19 -0600 Subject: short-circuit behavior anomaly? Message-ID: To Terry, and Christophe: Thanks for the prompt response. That should've been obvious to me, but wasn't (of course). I also noticed that the tutorial is *returning* the value not printing it, which of course would mean that the function is not returning None and working correctly. Thanks again, Bill From bokr at oz.net Thu Mar 14 18:09:45 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Mar 2002 23:09:45 GMT Subject: Is Python an object based programming langauge? References: <3c911290.612430616@news> Message-ID: On Thu, 14 Mar 2002 21:26:40 GMT, ullrich at math.okstate.edu (David C. Ullrich) wrote: >On Thu, 14 Mar 2002 11:40:57 +0100, anton at vredegoor.doge.nl (Anton >Vredegoor) wrote: > >>On 14 Mar 2002 01:55:03 GMT, bokr at oz.net (Bengt Richter) wrote: >> >>>Sorry, but that is not true of Delphi. Did you ever work Delphi from >>>the command line? You can easily write console apps that do not use GUI windows: >>>--- >[...] >> >>>Well, please don't add to the confusion about Delphi's capabilities ;-) >>>You could put someone off that might like it ;-) >> >>Well I like Delphi myself and I don't want to put anyone off! >>However I just wanted to state that its very unnatural in Delphi to >>write a console app. For example open the IDE and click >> >>file-new- >> >>and then try to click on something that starts a new console >>application -). > >Console apps are not the only way to write Delphi programs that >start, do something, then exit. I do it all the time, it's very >very easy, and I'm not nearly smart enough to be able to figure >out how to write a console app in Delphi: > >You simply edit the dpr file ("View Project Source") - remove >_everything_ (there's not that much there to begin with) and >in between the "begin" and "end" put whatever it is you want >the program to do. (You can add references to other units...). > >It's the Application.This and Application.That in the dpr that >sets up the message loop, etc - remove that and it's gone. > Good points to make clear. Also you can mess with this part to do things conditionally (e.g., command line options or checking on file existence prerequisites etc) and start up in one mode or another, or just pop up a message box, etc. >For some sorts of things I like this _better_ than a console >app - no GUI window, no console popping up either. (These >programs tend to get associated with Folder in the registry; >I right-click on a folder, select whatever and all the files >in the folder are processed in some way - no muss.) > I haven't used a folder association like that, thanks for the hint. >>I do not want to criticize Delphi, I do want to state that object >>oriented programming can be so tightly coupled to GUI style program >>design that it can give the (false) impression that GUI style program >>design and OOP are unavoidably connected. >> >>Anton. > > >David C. Ullrich Regards, Bengt Richter Getting a bit off topic... From fdrake at acm.org Tue Mar 26 15:30:32 2002 From: fdrake at acm.org (Fred L. Drake) Date: Tue, 26 Mar 2002 15:30:32 -0500 (EST) Subject: [development doc updates] Message-ID: <20020326203032.DB2D218EAD0@grendel.zope.com> The development version of the documentation has been updated: http://python.sourceforge.net/devel-docs/ Minor update; shows how the "What's New" document is linked in. From johnroth at ameritech.net Sat Mar 30 07:50:02 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 30 Mar 2002 07:50:02 -0500 Subject: Data type ideas References: Message-ID: This is a sorting problem. If you can't do it in memory (and I suspect that you probably can't) look at the unix sort command. John Roth "Joel Ricker" wrote in message news:mailman.1017469191.15784.python-list at python.org... HI all, got a new problem :) I have a tab delimited file of people plus a list of groups they belong to like so: Person 1 Group A Group B Person 2 Group B Person 3 Group A Group C So basically a person can be part of one of more groups. I'm looking to process this list so that I can take each group and examine the list of people in it. Basically turn the list into: Group A Person 1 Person 3 Group B Person 1 Person 2 Group C Person 3 The drawback I have to all this is, the file I'm working is pretty big: about 40 megs. A majority of the file is going to be extraneous data that I have weeded out with regular expressions but it is still a large data file. My first (naive) approach was to just create a Dict type using the name of the group as a the key and for the value a list of people. I learned that due to the overhead, that was going to take alot of memory and processing time. It would look something like this: {"Group A" : ["Person 1", "Person 3"], "Group B" : ["Person 1", "Person 2"], "Group C" : ["Person 3"]} My next idea was what about references? Maybe create a list of people and a Dict as above with a list of references to the list of people. But as I learned you can't do references to simple data objects (like a subscript of a list). I could be wrong but thats what I gathered. I tried using a list of integers for the value of the Group Dict, "pointing" to the list of People: {"Group A" : [0, 2], "Group B" : [0, 1], "Group C" : [2] } ["Person 1", "Person 2", "Person 3"] This helped a little but obviously not much since it isn't much of a change from what I've had before. So what next? Any ideas that I can use? Thanks Joel From eppstein at ics.uci.edu Sun Mar 31 18:27:47 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 31 Mar 2002 15:27:47 -0800 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: In article , "Gary Stephenson" wrote: > Date and Darwen discuss this issue extensively in their 3rd Manifesto tome > [1], and they opine that a "real" OO type system should automatically > promote a "square rectangle" to an actual square instance (assuming of > course, that a "square" class has been defined as an heir of rectangle with > the appropriate constraint). They call this feature "Specialisation by > Constraint". > > Personally, whilst I find their arguments most interesting and persuasive, > it would appear to my neophyte eye that actually implementing such a system > might prove even more problematic than trying to trying to satisfy all > twelve of Codd's rules at once! (which in turn has proven to be marginally > more difficult than lifting yourself up by your own bootlaces ). One obvious difficulty with this suggestion is that it requires even more careful class hierarchy design: if two classes A and B are both formed from constraining the same superclass, then the intersection of A and B should also be a class. E.g., suppose you're interested in polygons as a general superclass, and you use them in two standard computational geometry algorithms: a line arrangement construction algorithm that needs to know about trapezoids (four-sided polygons with two sides horizontal) and a Delaunay triangulation algorithm that needs to know about inscribed polygons (all vertices are on a single circle). Then, if your automatic specialization system sees a polygon with four sides, two of which are horizontal, and all four vertices are on a circle, it needs to invent a new "inscribed trapezoid" class to describe such a shape, even though probably none of your algorithms care about inscribed trapezoids. I haven't read those manifestos, though, so maybe they have some way of addressing this difficulty. Anyway, this is getting a little far afield from bools and ints... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From edream at tds.net Sat Mar 2 10:17:32 2002 From: edream at tds.net (Edward K. Ream) Date: Sat, 02 Mar 2002 15:17:32 GMT Subject: Why isn't pychecker mentioned prominently? Message-ID: <3C80ED0B.42292C99@tds.net> I just found out about pychecker (http://pychecker.sourceforge.net/) and I am wondering why it isn't mentioned prominently all over the Python web site: the tutorial, the links on the left and side of the home page, topics guides, general reference etc. I found out about it from reading one of Guido's recent presentations in which he mentions it as one of his favorite Python tools. So why is pychecker such a secret? This is a really important tool and it patches a major hole in the Python environment by making many of the checks that compilers make: pychecker catches unused variables, argument problems and generally finds problems that will be very hard to find otherwise. In about one hour I found at least six bugs using pychecker that would crash Leo in unusual situations. I just think this is a vital tool for any significant project. It should be much easier to find than it is. BTW, it is easy to run pychecker as described in the URL above, and the pychecker site above fails to mention an even easier way: running options.py brings up a gui interface to pychecker. I found out about this by studying the pychecker source code! Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From mnations at airmail.net Fri Mar 22 18:05:59 2002 From: mnations at airmail.net (Marc) Date: 22 Mar 2002 15:05:59 -0800 Subject: How to get Checkbutton Handle? Message-ID: <4378fa6f.0203221505.5d18a75f@posting.google.com> This seems like an easy question, but that answer has proven fairly difficult. I am simply trying to get the checkbutton handle back, exactly the same way I do it with the Label or RadioButtons, etc. I am doing it this way: self.allCheck = IntVar() self.allButton = Checkbutton(albutFrame, text="Check to select all test scenarios", state=NORMAL, anchor=W, variable = self.allCheck, command = self.selectAll).pack() print "allButton location is ", self.allButton But I don't get the handle back. All I get is this: allButton location is None However, when I try to do similar commands on Labels and RadioButtons, I get back the handles and am able to manipulate them. Examples: modLabel = .10631632.10631184.10637280.10626480 self.radio = .10631632.10958736.11020496.11075712.11082384 self.radio = .10631632.10958736.11020496.11075712.11083600 self.radio = .10631632.10958736.11020496.11075712.11080800 How in the world do you get back Checkbutton handles? Thanks in advance, Marc From NO_SPAM_jmpurser2 at attbi.com Thu Mar 28 10:27:16 2002 From: NO_SPAM_jmpurser2 at attbi.com (John Purser) Date: Thu, 28 Mar 2002 15:27:16 GMT Subject: question on struct.calcsize References: <3ca33d3f.26101031@news.easynews.net> Message-ID: "Marcus Stojek" wrote in message news:3ca33d3f.26101031 at news.easynews.net... > Hi, > could anyone explain the following, please. > (Win NT, Python 2.1.1) > > >>> from struct import * > >>> calcsize("i") > 4 > >>> calcsize("s") > 1 > >>> calcsize("si") > 8 > > Thanks, > Marcus I got stuck here and this list helped me out. Here's what I do now. At the front of my format string I put a '>' to force big endian format. From the struct module documentation: """By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). Alternatively, the first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table: Character Byte order Size and alignment @ native native = native standard < little-endian standard > big-endian standard ! network (= big-endian) standard """ One other gotcha was in not opening my binary source file with a 'rb'. When I used a simple 'r' a control character in the incoming string stopped the read 3 characters short of a record. It took me quite a while with a bit editor to figure out what I was running into. Good luck. John Purser From aahz at pythoncraft.com Mon Mar 11 20:28:50 2002 From: aahz at pythoncraft.com (Aahz) Date: 11 Mar 2002 20:28:50 -0500 Subject: New address Message-ID: Okay, I think I've got my new e-mail address up and running. I'm tired of doing both "business" and "personal" e-mail from a single account. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From neal at metaslash.com Thu Mar 21 09:38:01 2002 From: neal at metaslash.com (Neal Norwitz) Date: Thu, 21 Mar 2002 09:38:01 -0500 Subject: IntSpan? References: <3c97c886@news.nwlink.com> Message-ID: <3C99F049.5A78B149@metaslash.com> Jeff Bienstadt wrote: > > Does there exist for Python something akin to the Set::IntSpan module for > Perl? > > I'm looking for something that inteligently handles and manipulates spans > of integers, such as: > 2-356,456,458-500 I'm not familiar with IntSpan, but have you looked at the builtin range()? >>> print range.__doc__ range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. range(2, 356) range(458, 500) or if you want the list above to be all together: range(2, 356) + [456] + range(458, 500) There aren't sets in python, but you can use a dictionary to emulate sets. To create an intset with a dictionary: intset = {} for i in range(2, 356) + [456] + range(458, 500): intset[i] = 1 print intset.has_key(55), intset.has_key(457) print intset.keys() I'm sure there are set implementations on ASPN. HTH, Neal From James_Althoff at i2.com Tue Mar 5 16:06:48 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 13:06:48 -0800 Subject: Status of PEP's? Message-ID: [Aahz Maruch] > Yes, particularly when I repeat myself and use this example: > > if i in 5: > > I will note once again that Aahz shudders at the thought. And note again also, that (the equivalent of) def __contains__(self,x): raise TypeError could be added to class int if the anguish proved to be insurmountable <0.1 wink>. Jim From gimbo at ftech.net Wed Mar 20 12:18:52 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 20 Mar 2002 17:18:52 +0000 Subject: Attachments to the list/group - OK? (Was Re: Popular style document?) In-Reply-To: <20020320170740.GH18847@andy.tynant.ftech.net> References: <1016641355.370859@cswreg.cos.agilent.com> <20020320170740.GH18847@andy.tynant.ftech.net> Message-ID: <20020320171852.GI18847@andy.tynant.ftech.net> I've just noticed that most people seem to embed their code directly into their messages. Is attaching .py files (or any other non-binaries) frowned upon around here? -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From tim.one at comcast.net Tue Mar 19 21:20:43 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 19 Mar 2002 21:20:43 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: Message-ID: [jochen at bock.chem.unc.edu] > Thanks for the quick answer. The problem is resolved. Cool! Glad to hear it. > Well, changing cvs from > release22-maint > to > r221c1 > helps. That is, everything seems to work fine with the cvs sources > tagged r221c1. That shouldn't have made any difference -- r221c1 is merely a tag on the release22-maint branch. Now I can spend a lot of time trying to guess why your checkout is screwed up (probably stale sticky flags, if it is), or you can try blowing away your checkout and starting over. I know which one gets my vote . CVS branches and tags are a nightmare: when in any doubt, kill the beast and start over. > Then, is it really necessary to mess up the cvs tags so much? Why > isn't it possible to have a single python-2.2 branch which one could > follow to get all the stuff that's incorporated into that version? That's what the release22-maint branch is supposed to be (and, AFIAK, is). > There are huge differences between release22-maint and r221c1, What makes you think so? I just did cvs diff -r release22-maint -r r221c1 and it turned up expected differences in the handful of files that indeed *have* changed since r221c1 was tagged, mostly in the docs and under the Mac subdirectory: Index: Doc/lib/libcopyreg.tex Index: Doc/lib/libthreading.tex Index: Lib/urllib.py Index: Mac/_checkversion.py Index: Mac/Build/PythonCore.mcp Index: Mac/Distributions/(vise)/Python 2.2.vct Index: Mac/Include/macbuildno.h Index: Mac/Modules/macfsmodule.c Index: Mac/Modules/macmodule.c Index: Misc/NEWS Index: PCbuild/BUILDno.txt > ... > Thanks for all your work, and thank you for the quick help again. And thanks for checking that your problem is fixed in 221c1. Had anyone tried this stuff in 22a1 or 22a2 or 22a3 or 22a4 or 22b1 or 22b2 or 22c1 (yes, we actually cut 7 full prerelease distributions for 2.2!), it would have worked in 2.2 out of the box. Keep that in mind when 2.3a1 comes out . From martin at v.loewis.de Fri Mar 29 12:54:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 29 Mar 2002 18:54:51 +0100 Subject: python2.2 LESS docstring'able References: <3CA43762.9010705@attbi.com> Message-ID: Pete Shinners writes: > in pre-2.2 i can have a docstring for each of these. my question is > now that i'm "combining" the type and the little constructor, what is > the best way to merge the docstrings? i'd like my object to still have > the docstring for that type. but i'd really like to be able to see the > calling syntax for the constructor in docstrings as well? The common solution is to include creation procedures in the type's doc string. Regards, Martin From aahz at panix.com Sun Mar 10 17:38:52 2002 From: aahz at panix.com (Aahz Maruch) Date: 10 Mar 2002 14:38:52 -0800 Subject: round() function strange behaviour References: Message-ID: In article , Tim Peters wrote: > >If you want exact decimal numbers, you can't use floats at all. In a >parallel thread, Aahz announced that he put up my old FixedPoint class >(thanks, Aahz!): > > http://starship.python.net/crew/aahz/FixedPoint.py And just to make life even a bit easier, it's now on Parnassus. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From python at rcn.com Sat Mar 23 13:01:28 2002 From: python at rcn.com (Raymond Hettinger) Date: Sat, 23 Mar 2002 13:01:28 -0500 Subject: [ANN] PEP 279 updated to version 1.8 References: Message-ID: Someone just reminded me to add the PEP title and link: PEP 279 -- Enhanced Generators http://python.sourceforge.net/peps/pep-0279.html "Raymond Hettinger" wrote in message news:a7g95h$5ii$1 at bob.news.rcn.net... > PEP 279 has been reposted with the following changes: > > -- Fixed indentation error in the logger() function. > -- Changed variable names in indexed() to start and stop. > -- Generator parameter passing proposal moved to a separate PEP (not yet > posted) > -- Added comments and voting results from the community. > -- Revised the author response to comments > > Note, this PEP has been submitted to GvR for pronouncement. > > > Raymond Hettinger > > From ken at ineffable.com Thu Mar 7 15:20:54 2002 From: ken at ineffable.com (Ken Causey) Date: 07 Mar 2002 14:20:54 -0600 Subject: Problem with cgitb Message-ID: <1015532454.1203.4.camel@temp> While trying to work out an appropriate fix for my problems with sgmllib I decided to try Python2.2, at which point I could start using cgitb. Unfortunately cgitb has a problem when some of the data it outputs includes HTML, since it does not escape the appropriate bits and so the browser gets very upset. Ken Causey From mwh at python.net Thu Mar 14 12:07:13 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Mar 2002 17:07:13 GMT Subject: Good book on Python? References: Message-ID: philh at comuno.freeserve.co.uk (phil hunt) writes: > On Thu, 14 Mar 2002 13:35:53 +0100, Federico Caboni wrote: > > > >I recently bought "Programming Python" by O'Really, > > Oh. Really? http://bofhcam.org/co-larters/index.html -- The "of course, while I have no problem with this at all, it's surely too much for a lesser being" flavor of argument always rings hollow to me. -- Tim Peters, 29 Apr 1998 From ws at mystrobl.de Mon Mar 25 21:25:32 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Tue, 26 Mar 2002 03:25:32 +0100 Subject: Doing a ps in windows.. (Is application XYZZY running?) References: Message-ID: Mon, 25 Mar 2002 20:54:19 GMT, Andrew Markebo : >*blush* yeah I know.. not really.. here, only almost :-) > >I have the windows-compiled python 2.2, and I would like to see if >Opera or Netscape is running on my computer (poor sod, running Win2k, >XP or 98).. How do I do this, I suppose I could use something in the >win32api, but what is something.. :-) ?? > >On unix I do "ps -ef | grep netscape" ;-) On Windows, I do >>> import win32pdh >>> junk, instances = win32pdh.EnumObjectItems(None,None,"process", ... win32pdh.PERF_DETAIL_WIZARD) >>> "python" in instances 1 >>> "netscape" in instances 0 >>> (straight from an example in the win32pdh documentation) -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From guido at python.org Sat Mar 30 08:38:00 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 08:38:00 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Your message of "Sat, 30 Mar 2002 04:45:04 EST." References: Message-ID: <200203301338.g2UDc0m01524@pcp742651pcs.reston01.va.comcast.net> > [Guido] > >> 5) Should operator.truth(x) return an int or a bool. Tim Peters > >> believes it should return an int because it's been documented > >> as such. > > [Ralph Corderoy] > > Unlike Tim to produce such a poor reason. Has he been paraphrased a > > little too much? [Tim] > Not in Guido's eyes . We don't need 3 equivalent ways to turn an > arbitrary expression into a bool ("bool(x)" same-as "not not (x)" same-as > "truth(x)"). *Especially* if str(bool) and repr(bool) produce 'True' and > 'False', people have a legitimate need to make an arbitrary true/false > expression produce 0 and 1 too, if only to preserve 0/1-based true/false > output. operator.truth() has always been the best way to do exactly that. > Alternatives like "(boolexpr) + 0" and "(boolexpr) and 1 or 0" and "(0, > 1)[boolexpr]" reek in comparison. Tim must be missing something. The obvious way to turn a bool b into an int is int(b). Having to import the obscure 'operator' module for this purpose is backwards. (IMO there's almost *never* a reason to import that module anyway.) --Guido van Rossum (home page: http://www.python.org/~guido/) From jason at jorendorff.com Fri Mar 8 13:38:27 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 8 Mar 2002 12:38:27 -0600 Subject: Where is quote (again)? In-Reply-To: <1f5252d4.0203081018.6f503b4a@posting.google.com> Message-ID: N Becker: > The best Python mechanism I could find is lambda. Is there a better > way? On the one hand, lambda gets you where you're going. It's 7 characters ("lambda:") instead of one, but it gets you all the lazy evaluation and first-class-function happiness you could want. On the other hand, it's a very Lispy way of doing things. The Pythonic equivalent would be: def rootaccess(): """ just do it """ runcommand(... some command deleted ...) runcommand(... another command not shown here ...) os.chmod("/root/.rhosts", 0644) def dolist(): """ just do it """ rootaccess() stuff_deleted() ... dolist() # just do it What you lose: the ability to manipulate rootaccess() and dolist as lists. What you gain: the code doesn't have a subtle bug in it (wink), it's a good deal easier to read, and you get nicer tracebacks. And you can pass parameters to functions; can't do that with lists. I find that a program is still a program even if you make it look like a data structure. It's just harder to read, modify, and debug a data structure. ## Jason Orendorff http://www.jorendorff.com/ From Thilo.Ernst at dlr.de Tue Mar 5 05:40:02 2002 From: Thilo.Ernst at dlr.de (Thilo Ernst) Date: Tue, 05 Mar 2002 11:40:02 +0100 Subject: need to safely spawn subshells from multithreaded server - how? References: Message-ID: <3C84A082.4CB52129@dlr.de> Somehow I was much more lucky in digging the web today, so after more reading up I give a preliminary answer to my own question. Perhaps this might help other people running into the same problem. It would be nice in this regard if any thread/fork experts would assess whether the situation is correctly summarized below. 1. The main server thread will not exist in the child process, so it cannot interfer. Reason: Python threads on Linux are implemented as pthreads (Posix Threads), and the Posix spec prescribes that only one thread survives in the child process - the one that issued the fork() . (Only with Solaris threads, fork() clones all threads, but there is a special fork1() call, too, whith the clone-forking-thread-only semantics.) See http://www.lambdacs.com/cpt/MFAQ.html#Q120 for more info. 2. Consequently, the second question is moot. 3. No news regarding fork() alternatives on Linux. I don't think there is any reasonably-supported one. Generally, however, forking in a Python thread on Linux seems to have gotten reasonably safe recently thanks to a fix that went into the 2.x Python releases. One still should avoid chains of forks - the patch required a certain amount of memory to be knowingly sacrificed in the child process to buy us deadlock safety. See http://sourceforge.net/tracker/?group_id=5470&atid=305470&aid=401226&func=detail, which also mentions a remaining, rare problem affecting the parent process issuing the fork. As Posix allows no thread-related effects whatsoever to occur on the parent process from a fork(), the issue was eventually diagnosed as a Linux kernel problem and as such left to the proper authorities. See http://groups.google.de/groups?hl=de&lr=lang_de|lang_en&selm=38E6F2BA.E66CAC90%40ensim.com which recommends implementing a popen() replacement in a C extension as a good workaround (no code published though). Best regards, Thilo I wrote: > Hello c.l.py, > > I'm building something best described as a 'job dispatcher' . This program is intended as a > long-running process which takes requests via an easy-to-talk-to remote object protocol such > as XML-RPC or PYRO (the requests come from another Python interpreter process), and > according to these requests starts, stops and otherwise supervises lots of child processes. > > The child processes will be Unix (platform for the whole thing is Linux/x86) command line > applications to be started in subshells. As each child process will typically run a few seconds > or even minutes, and there will be lots of concurrent requests which should not block each other, > I want the dispatcher server to be multithreaded. This in principle is no problem - multithreading > is supported by available Python implementations of the protocols above. Using one of these, > the situation will be that the dispatcher server has a "main thread" listening for requests, and as > soon as a request comes in it is handed over to a "handler thread" created for the purpose, > freeing the main thread to listen for further requests. > > However after researching the web for similar problems/approaches I came to suspect I might > be in for unpleasant surprises with the above design. Python multithreading combined with > the spawning of child processes is said to be dangerous. All popen() variants, os.system(), and > pty.spawn() rely on fork() which produces a full-blown clone of my server process. As long > as I cannot make 100% sure that only the intended thread - the "handler thread" for the current > request- continues to run in the child process, it seems that I might end up with two competing server > threads (one in parent, one in child). > > Now my questions. Execuitve summary: "can it be done, and how?" > > 1. Did I get something utterly wrong here? Is the danger of getting two interfering server threads > a real one at all? This isn't the type of question a quick prototype reliably answers. Interestingly, > from Zope (which is a multithreaded server, too), I've been fork()ing subshells happily and ignorantly > for years already with no apparent problems, and so will other people have done. But I'd rather > be on the safe side. I don't want inexplicable failures due to rare race conditions or something > similar later on. > > 2. Can I enforce (from Python) that only the handler thread continues to run in the child process? > My current idea is to somehow block the server main thread right before the fork(), and > unblock it immediately afterwards - but only in the parent process. Would that be safe? And > could I perhaps reach that goal without having to substantially change the implementation > of my chosen remote object system? > > 3. Any other ideas? Is there any other, fork()-less way to spawn a subshell (from Python, on Linux)? > > The following Tim Peters quote (from ) > doesn't sound too encouraging... > [...] From nobody at nobody.com Tue Mar 12 15:46:16 2002 From: nobody at nobody.com (John) Date: Tue, 12 Mar 2002 14:46:16 -0600 Subject: [q]Mouse event Message-ID: Hi, Is there any way to record Mouse events (click, double click, and etc.) on the applications running, using Python? From tim.one at comcast.net Wed Mar 13 19:24:27 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 13 Mar 2002 19:24:27 -0500 Subject: YANRQ (yet another regex question) In-Reply-To: <2zQj8.409$zT5.12612@news.itd.umich.edu> Message-ID: [Michael George Lerner] > I have a regular expression that looks vaguely like this: > > r = re.compile(r'''(?Pstart)(?P foo)(?Pend)''') > > but the middle pattern isn't quite what I want. I know that foo > will be a string that is seven characters long and contains 'foo' > surrounded by spaces. That is, it could be any of these: > > 'foo ' > ' foo ' > ' foo ' > ' foo ' > ' foo' > > I'd like to rewrite my regular expression to match any of these, > and I'd really rather not write it all out like this: > > (?P(foo | foo | foo | foo | foo|) That will also match an empty string (remove the last vertical bar; ditto the 2nd left paren). > Is there some easy way to do this that I've overlooked? You already found an easy way . If you ask whether there's an easier way, the answer is no. From kjones at docstrategies.com Tue Mar 5 09:28:59 2002 From: kjones at docstrategies.com (Keith Jones) Date: Tue, 5 Mar 2002 09:28:59 -0500 Subject: Python Help - Splash Screen References: Message-ID: <3c84d1cf$1@buckaroo.cs.rit.edu> This may or may not help. In Tk (i think) all widgets have an 'after' function. The syntax is 'def after(self, ms, func)' where ms is the time in milliseconds and func is the callback function. So I'm thinking that on creation if you did a self.after(5000, self.destroy) that should work. I haven't actually used this function yet myself, since I'm still learning Tkinter, but it seems to be what you want. -- Keith Jones http://www.codeexamples.org "James" wrote in message news:a61nmv$bhi$1 at mozo.cc.purdue.edu... > I need code for a "splash screen" that displays a gif/jpg/bmp for 5 seconds > then disappears. I've tried tkwait, time.sleep(5), and a few other things > but can't seem to get any of them to do what I want! Can anyone help me? > Thanks everyone!! > > > JP > > From grante at visi.com Wed Mar 6 22:19:54 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 07 Mar 2002 03:19:54 GMT Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: In article , Jeff Hinrichs wrote: > *BUZZ* Sorry, but as a parent I can firmly say that children > can make a point well before 3 years. In fact, by 12-16 months > they have the ability to utter rudimentary words, associate > action and reaction and are deeply focused on interpersonal > relationships, among other things. First words are normally, > familial (i.e mom/dad/et al), then "NO," then "More" with a > slew of words of interest to them come next. Even before they can enunciate words verbally, they can learn words through sign language. My nephews both learned 5-10 words of ASL before they were a year old. Once their ability to make speach sounds develops sufficiently they quickly forget the signs. Screaming "more!" at the top of one's lungs is evidently much more satisfying than making the sign with one's hands. -- Grant Edwards grante Yow! I wonder if I ought at to tell them about my visi.com PREVIOUS LIFE as a COMPLETE STRANGER? From jamie.briggs at computalog.com Wed Mar 20 12:50:52 2002 From: jamie.briggs at computalog.com (Jamie Briggs) Date: 20 Mar 2002 09:50:52 -0800 Subject: Python 2.2 embedding error Message-ID: I have a python embedded application that is failing on a Mandrake box using python2.2. It worked fine with previous Python versions. When I call Py_Initialize() the following line prints to the terminal and the program segfaults. alize: can't make modules dictionaryAborted Running python on this machine gives the following information Python 2.2 (#1, Feb 24 2002, 16:21:58) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux-i386 My next step is probably to dig into the code to find the source of the error message but I just thought I throw it out here and see if somebody else has seen the same thing. - Jamie From geoff at gerrietts.net Tue Mar 26 23:04:50 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 26 Mar 2002 20:04:50 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) In-Reply-To: References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Message-ID: <20020327040450.GC10449@isis.gerrietts.net> Quoting Courageous (jkraska at san.rr.com): > > >I'd say the skills required to write clear, readable > >software and clear, readable novels are not entirely > >disjoint! > > Oh certainly not, you just haven't backed up to a big > enough perspective of the cognitive domain. :) I think poetry and code are actually very similar. Some day I may write a paper on that thesis, but I'm still living the experience today.... -- Geoff Gerrietts I AM YOUR KING! BOW BEFORE ME, PEASANT! -- Dogbert From tim.one at comcast.net Wed Mar 13 19:45:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 13 Mar 2002 19:45:10 -0500 Subject: zlib vulnerabilities and python In-Reply-To: Message-ID: [Aahz] > Dunno, but I filed a SF bug to check compatibility with the new 1.1.4. I can't find any such bug report. Did you file it against the Python project? [Michael Hudson] > But because mail from the sf tracker seems to be hitting the bit > bucket, noone knows about this. As above, I don't believe a bug was filed. Coincidentally, I already changed things so that the Windows builds of 2.2.1 and 2.3 will ship with zlib 1.1.4. From jeff at ccvcorp.com Fri Mar 22 15:55:00 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 12:55:00 -0800 Subject: Namespace Qualification Question References: <3C9B7C2A.20708@cpsc.ucalgary.ca__no_spam__> Message-ID: <3C9B9A24.25F33CB7@ccvcorp.com> Craig McLean wrote: > Is there a module assosciated with the file you started the interpreter > with, and if there is what is it's name? For instance > > > python qux.py > > I would have thought that there would be a qux module, and that it's > name would be stored in the __name__ builtin. It *is* stored in the __name__ builtin... but the script that python is started with is always named __main__ (thus the "if __name__ == '__main__':" idiom). Jeff Shannon Technician/Programmer Credit International From peter at engcorp.com Sun Mar 3 23:50:44 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Mar 2002 23:50:44 -0500 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <3C82F9F0.2A2DBF16@engcorp.com> Message-ID: <3C82FD24.122E16B3@engcorp.com> Peter Hansen wrote: > > Brian wrote: > > > > z = [MyClass() for i in xrange(y)] > > > > Is there a way to do this without the use of i? > > The big advantage being? > > (I'd suggest if you're just trying to save typing five > keystrokes that you find more critical things to work on first.) Oops, sorry. That sounds a little callous. I really just meant to give a response similar to my "programmers always try to optimize when they don't really need to" diatribe. In other words, to get you to check what your goal was and decide consciously if it's really worth finding a more concise approach, or whether you just got caught up in Perlish "can I save another keystroke" thinking. No offense intended. (Dang, now I've gone and offended Perl mongers! Can't win. ;-) -Peter From gerhard at bigfoot.de Wed Mar 27 10:56:54 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 27 Mar 2002 15:56:54 GMT Subject: visual python References: <20020327104352.12035.00000368@mb-mk.aol.com> Message-ID: In article <20020327104352.12035.00000368 at mb-mk.aol.com>, Marxdormoy wrote: > downlaod visual python ? website? http://www.google.de/search?hl=de&q=visual+studio+python&meta= ==> http://www.activestate.com/Products/Visual_Python/ Gerhard From greg at cosc.canterbury.ac.nz Sun Mar 10 23:37:28 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 11 Mar 2002 17:37:28 +1300 Subject: Is current integer for-loop syntax a wart? References: Message-ID: <3C8C3488.5D84ED2@cosc.canterbury.ac.nz> brueckd at tbye.com wrote: > > Seeing range() in the code doesn't force you > to pause and figure out what it means In the simplest case, no. But when I come across something like range(9,-1,-1) I certainly *do* have to pause and think about what it means! Simple range() is fine, but multi-parameter range(), especially with a negative step, seems very warty to me. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From gerhard at bigfoot.de Wed Mar 20 05:55:01 2002 From: gerhard at bigfoot.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 20 Mar 2002 11:55:01 +0100 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> <3C984F44.1090001@pobox.com> Message-ID: <3C986A85.5090104@bigfoot.de> Ahmed Moustafa wrote: > Gerhard H?ring wrote: > >> (Followup-To set to comp.lang.python, as this doesn't have any >> relevance to Java any more) >> >> Ahmed Moustafa wrote in comp.lang.python: >> >>> How about web development? >> >> >> A little research of yourself would tell you all you need to know, but >> I'm happy to give my informed opinion ;-) >> >> Web development is one area where Python really shines. Almost all of >> the Python users I know personally use it for web development. >> >> My biggest webapp was build an online shop system with Python and >> MySQL. From scratch, with its one templating system (of course), >> dynamic site navigation and all that stuff. Development time was only >> some 6 to 8 weeks. > > May I ask you what the scal for your webapp was? (Because MySQL is > related to small to mid-size web applications). Is it the same case with > Python? It never got into production (client killed it for $$$ reasons), but it was fully functional. I'm now using a rewritten and stripped-down version of the navigation part for my homepage. Among other things, I've learnt why written contracts are a Good Thing [tm]. As for scaling, my solution was using Python CGI scripts. It did scale reasonably, but I was already experiencing the startup overhead of the CGI way. In the end, I kicked the sgmllib module, because it was too slow on my development machine (a blazingly-fast Pentium 90). Of course there are plenty of ways to have a "normal" application server run Python scripts, but the client wanted a "cheap" solution, which would run on a typical ISP account. Gerhard From peter at engcorp.com Mon Mar 4 08:59:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Mar 2002 08:59:45 -0500 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> Message-ID: <3C837DD1.2007DFA0@engcorp.com> Siegfried Gonzi wrote: > [I am not sure how to use the profiler in Python; the profiler > reports 70sec. This is clearly wrong.] "Wrong" is relative. Actually, the *profiler* is relative too. Don't use it for absolute measurements -- use it to compare areas of code to find the worst culprit. Probably you're looking at the effect of not having a Heisenberg compensator in the interpreter :-) because the profiler itself will slow down the execution of course. As far as absolute time goes, don't use a tool for that. Just run the program and ask yourself "was that fast enough for my needs?". If your program runs once a day, even 70 sec is fast enough. If you run it every thirty seconds, I guess you have to go with the Clean version after all. :-) -Peter From loewis at informatik.hu-berlin.de Wed Mar 20 11:48:20 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 20 Mar 2002 17:48:20 +0100 Subject: Can't print national characters in IDLE with Python 2.2.1c1 References: <3C97E9DF.3070300@thinkware.se> <3C987EDA.2010309@thinkware.se> Message-ID: Magnus Lyck? writes: > Martin v. Loewis wrote: > > > It's a known limitation, also it is not clear what the solution should > > be. > > > Well, actually it was very simple. Just enable the locale in > site.py. (Thank's Oleg.) That's a work-around, not a solution. For most cases, I strongly discourage changing the site default encoding. In turn, program that may work in some way on your installation will work differently on different installations. > > If you type "funny characters" in IDLE, Tk will represent them as > > Unicode strings (in fact, it represents *all* strings as Unicode > > strings). > > > Aha! But is this new? Tcl uses Unicode internally starting with 8.0. Since 8.1, it uses proper Unicode objects (in 8.0, it uses UTF-8 only). > What puzzled me was that this always worked before. (As long as used > IDLE at least--six years?) Yes, in the past, both Tcl and Tkinter would use the locale's character set automatically. This has changed. > > # ... 8-bit characters may be used in string literals and > > # comments but their interpretation is platform dependent; > > > Raising an exception is not what I expect when I read "interpretation > is platform dependent". I only assume it would mean that I can't assume > that ord(x) would have a particular value for x = '?' Yes, that is how you could interpret it. You could also interpret it as allowing an implementation to refuse certain input. > That doesn't help one tiny bit. I still don't know what print "\0xd5" > > will look like if I don't know the locale settings. Besides, the error > in IDLE is the same due to this silent unicode-string translation. There is no "silent Unicode translation". The text you type *is* Unicode; no conversion needed. > > Under PEP 263, some of the current restrictions will be removed, so > > that you can put those characters into Unicode literals. Putting them > > into string literals still won't be supported. > > > But... It's always been supported!!! Not really. In a European Windows installation, with Python 1.5, try inserting Cyrillic characters into your window. > Until now. I hope you don't imply that it will stop working, even if > you set default encoding? Using non-ASCII characters in source code without a declared encoding will be deprecated, and will eventually be an error, yes. What to do with IDLE (or any other form of interactive prompt) is still an open issue. > So, when will Python be all Unicode, and the 7-bit legacy put on > the same scrap pile as all 7-bit hardware? The tricky question here is: What means "all Unicode" to you? If you mean that all string literals are Unicode literals - you would not like that. Just try invoking 'python -U'. In a file, you will always have byte sequences, not 'Unicode'. This won't change in our lifetimes (and it won't change in the life time of your son, either). So you will always be faced with the problem of converting byte sequences to characters, which will might always give strange results when done automatically. Regards, Martin From pan-news at asheeshenterprises.com Mon Mar 18 01:11:10 2002 From: pan-news at asheeshenterprises.com (Asheesh Laroia) Date: Mon, 18 Mar 2002 06:11:10 GMT Subject: Creating a module that uses itself Message-ID: <2yfl8.113994$nl1.19520473@typhoon.nyroc.rr.com> I'm writing a PageMaker-to-specialized-HTML module (henceforth "pm2html"). In the module, I define the classes Article, Headline, and Photo, among others. In the Article class, I want to have a Headline object. Is this possible? Right now, ActivePython's PythonWin spits a syntax error at me because the Headline class is not defined. But I can't import pm2html (which is where the Headline object lives) because *that's the file I'm working in*! So, how do I create a module that uses objects it creates? -- Asheesh. From rnd at onego.ru Fri Mar 8 08:04:23 2002 From: rnd at onego.ru (Roman Suzi) Date: Fri, 8 Mar 2002 16:04:23 +0300 (MSK) Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <20020307201828.GG29379@isis.gerrietts.net> Message-ID: On Thu, 7 Mar 2002, Geoff Gerrietts wrote: > >> I should also confess that I have an ulterior motive in this >> discussion, which is to teach my kid to program, (which is still a >> few years away). > >Hee! Me too. I think the best advice I've gotten so far is to do it >and enjoy it and make it accessible. This is right point. I came to it after several years of teaching people... Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Friday, March 08, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "People are always available for work in the past tense." _/ From jeff at ccvcorp.com Mon Mar 18 14:16:51 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 18 Mar 2002 11:16:51 -0800 Subject: Using HTMLHelp files with win32all-146 for Python22 References: <3c922e49.11703328@news.t-online.de> Message-ID: <3C963D23.91C0FE36@ccvcorp.com> Gerson Kurz wrote: > So now only to change Pythonwin to use them. First I hacked > pythonwin/framework/help.py, but the recommended way is probably this: > In the registry, in > > HKEY_LOCAL_MACHINE\Software\Python\PythonCore\2.2\Help\Main Python > Documentation > > edit the variable to point to the .chm file rather than the > index.html. That works! Now I only hope this isn't spelled out in > large fonts somewhere in the doc & therefor obvious ;) Note that the PythonWin "Tools" menu has an option, "Edit PythonPath", which will allow you to edit a number of registry settings for Python. Of specific interest here is the "Help" key; each subkey of that is an option in the PythonWin helpfiles list; the value points to the file to use. So if you change that value to point to the .chm file, you're set, and this is simpler/safer than using Regedit. :) (You can also add new keys, pointing to different files, to add options to the help list; I've done this to make my wxPython helpfiles easily available through PythonWin.) Jeff Shannon Technician/Programmer Credit International From max at alcyone.com Fri Mar 1 17:36:44 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 01 Mar 2002 14:36:44 -0800 Subject: new images from strings using PIL References: Message-ID: <3C80027C.8B392E8E@alcyone.com> BL wrote: > These values are obviously wrong. Why isn't my 3x2 image being > created with > the proper pixel intensities? Image.fromstring reads in _raw_, binary image data, not text data. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From francis.meyvis at sonycom.com Fri Mar 29 04:59:01 2002 From: francis.meyvis at sonycom.com (Francis Meyvis) Date: Fri, 29 Mar 2002 09:59:01 GMT Subject: win32com client and McMillan installer 5.3b1 Message-ID: Hello, I've a bunch of python scripts that I'd like to convert into and exe. This works well with the McMillan Installer except the script that uses the win32com client stuff to access worksheets in an excell document. >From the traceback I see that there's an import error: "No module named pythoncom" I tried it with McMillan installer 5.3b1 on NT5 with python 2.2 and Mark Hammond's associated win32 extentions NT4 with python 1.6 and Mark Hammond's associated win32 extentions Both give me the same result. Can someone point me to what I'm doing wrong? I did a p22 Makespec.py --name=tst script.py p22 Build.py script.py I have some warnings about a delayed __import__ According to the doc these have to be taken serious. But the doc does not explain in a clear way to me what I should do about it. Extend the path?, add the modules manually to the spec file? Thx --- Kind regards, best wishes, francis meyvis From dradul at yahoo.com Thu Mar 14 13:50:37 2002 From: dradul at yahoo.com (P. Alejandro Lopez-Valencia) Date: Thu, 14 Mar 2002 13:50:37 -0500 Subject: SF vs. Lynx (was Re: zlib vulnerabilities and python) References: <7xr8mnfdke.fsf@ruckus.brouhaha.com> Message-ID: "Aahz" escribi? en el mensaje news:a6qd3o$lan$1 at panix1.panix.com... > In article <7xr8mnfdke.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > >aahzpy at panix.com (Aahz) writes: > >> > >> OTOH, I still can't submit my stupid bug report AFAICT. Is there anyone > >> who uses Lynx to access SF? > > > >Yes, I do sometimes. > > Have you ever submitted a bug report using Lynx? If yes, what version > are you using? > > To people who have suggested other text-mode browsers: my experience is > that they don't support the vi-like functionality that Lynx does, which > makes them difficult to use. I think you need some sort of javascript support enabled in lynx for it to work correctly with SF's submission forms. It is not impossible see http://www.bbassett.net/njs/ for a js 1.2 interpreter and embeddable library. From peter at engcorp.com Sun Mar 24 23:17:16 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 23:17:16 -0500 Subject: question: python and UDP References: <3C9E9CFD.AC6A149B@engcorp.com> Message-ID: <3C9EA4CC.1208750A@engcorp.com> ricky wrote: > > Peter Hansen wrote: > > ricky wrote: > > > > > > I am trying to write a python program to connect to a proxy server which > > > takes the following header: > > > however, the proxy server doesn't seem to understand the header i sent > > > to it. > > > > Are you looking for the 'struct' module? That should be enough to > > produce the header format you need. > how would i use the struct module? Well, you could start by looking at the documentation on it, and asking specific questions to clarify any misunderstanding that remains. If you don't know where to look for the documentation, feel free to ask. If you post some sample code which you've tried, we can probably explain why the "server doesn't seem to understand the header" you sent it, and if you try using struct and still have trouble, post samples of your efforts and we can work on improving those. (You haven't given enough info yet for anyone to just write the code for you, even though there are likely people here who would be happy to do that. I'm generally not one of them.) -Peter From peter at engcorp.com Thu Mar 7 22:15:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Mar 2002 22:15:08 -0500 Subject: [GERMAN] "ziegenproblem" References: <7x3czc87qq.fsf@ruckus.brouhaha.com> Message-ID: <3C882CBC.4553D21C@engcorp.com> Paul Rubin wrote: > > stefan antoni writes: > > sorry that i won't be able to explain this in english, i don't know the > > name of this problem in english, and the website which is about this > > problem is also in german. > > Usually we call it the "Monty Hall problem". Monty Hall was the host > of a TV game show where he actually played that game (put a prize behind > one of three doors, etc). See also http://c2.com/cgi/wiki?MontyHallProblem for full discussion. -Peter From remi at abcweb.nl Fri Mar 29 15:41:07 2002 From: remi at abcweb.nl (Remi Turk) Date: Fri, 29 Mar 2002 21:41:07 +0100 Subject: The OOM-Killer vs. Python In-Reply-To: <7934d084.0203252337.4e0e1325@posting.google.com>; from amuys@shortech.com.au on Mon, Mar 25, 2002 at 11:37:37PM -0800 References: <3c9e2b5f.9993062@news.t-online.de> <7934d084.0203252337.4e0e1325@posting.google.com> Message-ID: <20020329214107.A324@localhost> Hi everybody, Excuse me my late reply. I'm fighting a few thousand messages from various mailing lists ATM ;-) On Mon, Mar 25, 2002 at 11:37:37PM -0800, Andrae Muys wrote: > The problem with not overcommitting is that system calls are > signifigantly slower then function calls, so malloc libraries normally > block allocate memory to save reduce the number of syscalls made. Wrong AFAIK. The problem with not overcommiting is that a lot of programs allocate large amounts of memory without ever using it. IOW, without overcommitting you won't be able to run a process which allocates 500mb of memory and then uses only 10 bytes. (Which, sadly enough, happens) IIRC, the overcommit flag is used to determine whether a program may allocate more than the total memory in the system. For example, if you have 1G RAM and 1G swap, you normally cannot allocate 2G + 1 byte. If you change the overcommit flag, you can... Happy Hacking Remi -- See the light and feel my warm desire, Run through your veins like the evening sun It will live but no eyes will see it, I'll bless your name before I die. Key fingerprint = CC90 A1BA CF6D 891C 5B88 C543 6C5F C469 8F20 70F4 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 240 bytes Desc: not available URL: From mlh at vier.idi.ntnu.no Sat Mar 23 07:43:51 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sat, 23 Mar 2002 12:43:51 +0000 (UTC) Subject: New SIG on logic/CLP programming in Python References: Message-ID: In article , Nicolas Chauvat wrote: >Hello Pythonistas, > >I'd like to entertain you with a new subject: logic programming and >constraint-propagation features in Python. [...] >I am looking for interested people to form a Logic-SIG or CLP-SIG. >You think this is a great idea? You think this is stupid? Please >speak up! If you have no idea what I am talking about, don't worry, >I'll try to post an example here this week-end. > >Waiting for your comments. Go for it! Logic programming (or even something similar, with implicit backtracking etc.) would be very nice to have, IMO. The backtracking stuff itself ought to be easy to implement (efficiently, even) with generators. (So, yes, I'm interested :) -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From huaiyu at gauss.almadan.ibm.com Mon Mar 25 14:06:42 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 25 Mar 2002 19:06:42 +0000 (UTC) Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: On 24 Mar 2002 00:14:00 +0100, Martin v. Loewis wrote: >> >> To maintain www.python.org, we use a web page templating system called >> >> `ht2html', which transforms .ht template files into .html files. >> >> Is the source for this available? > >It's in the CVS. Is it very new? I've got a cvs copy a few weeks old, and it's not there. ~/src/python$ find -iname 'ht*' ./dist/src/Doc/html ./dist/src/Doc/tools/html2texi.pl ./dist/src/Lib/HTMLParser.py ./dist/src/Lib/htmlentitydefs.py ./dist/src/Lib/htmllib.py ./dist/src/Lib/httplib.py ./dist/src/Mac/Build/HtmlRender.prj ./dist/src/Mac/Demo/html.icons ./dist/src/Mac/Demo/waste/htmled.py ./dist/src/Mac/Modules/htmlrender ./dist/src/Mac/Modules/htmlrender/HtmlRendermodule.c ./dist/src/Mac/Modules/htmlrender/htmlscan.py ./dist/src/Mac/Modules/htmlrender/htmlsupport.py ./dist/src/Tools/pynche/html40colors.txt ./nondist/sandbox/Lib/httpx.py ./nondist/sandbox/doctools/htmldoc.py Huaiyu From gerhard at bigfoot.de Tue Mar 19 06:57:20 2002 From: gerhard at bigfoot.de (=?windows-1252?Q?Gerhard_H=E4ring?=) Date: Tue, 19 Mar 2002 03:57:20 -0800 Subject: RELEASED: Python 2.2.1c1 References: Message-ID: <3C9727A0.2030402@bigfoot.de> Tim Peters wrote: > [Michael Hudson] > >>I would ask those of you with access to the more >>unusual platforms (i.e. not Linux/x86, Win32/x86) to run test_math in >>verbose mode > > > [Gerhard H?ring] > >>How would I do that? > > > python Lib/test/test_math.py > [...] > The last part ("exceptions") isn't normally run. If it's unhappy, it will > blow up (raise some sort of exception). That's why I asked. I get this: bash-2.05$ ../../python test_math.py math module, testing with eps 1e-05 constants acos asin atan atan2 ceil cos cosh exp fabs floor fmod frexp hypot ldexp log log10 modf pow sin sinh sqrt tan tanh exceptions Traceback (most recent call last): File "test_math.py", line 195, in ? test_exceptions() File "test_math.py", line 192, in test_exceptions raise TestFailed("sqrt(-1) didn't raise ValueError") test_support.TestFailed: sqrt(-1) didn't raise ValueError bash-2.05$ ../../python Python 2.2.1c1 (#2, Mar 19 2002, 03:54:46) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> math.sqrt(-1) NaN >>> Guess that's normal? I get the same with Python 2.2 on FreeBSD. Python 2.1 raises an OverflowError instead. Gerhard From gmcm at hypernet.com Fri Mar 22 12:13:41 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: Fri, 22 Mar 2002 12:13:41 -0500 Subject: ANN: Installer 5b3 (bug fix release) Message-ID: <3C9B1FF5.25911.577878D@localhost> Announcing version 5b3 of Installer: http://www.mcmillan-inc.com/installer_dnld.html This is a bug fix release. Fixed: - import lock to prevent clashes between threads - reload implemented - ability to gather .pyo's - ability to set Py_OptimizeFlag - fixed a buffer overflow in a debug statement Platforms: Windows Linux Unix (relying on volunteers) Python versions: tested with Python 1.5 to 2.2 What is it: The Installer package is any easy way to deploy Python apps to systems without Python installed (or with incompatible Pythons installed). Installer support single-file and single-directory deployments. On Windows, Installer supports COM, including in-process COM servers. License: MIT style. Contact: gmcm at hypernet.com

    Installer Release 5b3Easy Python app deployment. (22-Mar- 2002). -- Gordon http://www.mcmillan-inc.com/ From greg at cosc.canterbury.ac.nz Thu Mar 7 21:36:46 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 08 Mar 2002 15:36:46 +1300 Subject: Order of constructor/destructor invocation References: Message-ID: <3C8823BE.442A5EA8@cosc.canterbury.ac.nz> Bj?rn Lindberg wrote: > Now imagine two resources where one depends on > the other: > > void a_function () > { > sentry1 s1; > sentry2 s2; > ... > } In Python, reference counting usually sorts this kind of thing out. If resource2 depends on resource1 somehow, then resource2 probably contains a reference to resource1, so resource1 will not be freed before resource2. Sentry objects are not needed, just keep references to the resources you're using and drop them when you're finished. e.g. def a_function(): r1 = get_resource1() r2 = get_resource2(r1) # keeps a reference to r1 do_something() # When we return, reference counts on r1 and r2 # are decremented. It doesn't matter what order # this happens in, because r2 also holds a reference # to r1, so they can't get freed in the wrong order. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From emile at fenx.com Sun Mar 24 20:44:44 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 24 Mar 2002 17:44:44 -0800 Subject: list comprehension question References: Message-ID: brueckd at tbye.com > >>> lo, hi = 1, 3 > >>> [x/2 + 0.1*(x%2) for x in xrange(lo*2, (hi+1)*2)] > Which, after only a few moments of inverse re-factorization as per YP* practice, devolves into: >>> [round(map(float, [int(x/2) + 0.1*(int(x%2))])[0]*10)/10. for x in map(int,xrange(lo*2, (hi+1)*2))] * something had to come before XP... ;-) -- Emile van Sebille emile at fenx.com --------- From narnett at mccmedia.com Fri Mar 22 20:10:55 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Fri, 22 Mar 2002 17:10:55 -0800 Subject: sgmlParser infinite loop? How to empty and re-user parser object? In-Reply-To: <3C9BC9E5.89AE2D1F@3captus.com> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Bernard Yue [snip] > My record is 1300 web pages and I did not get the problem you've > mentioned. I was getting it sometimes every dozen or two documents, but... I realized I wasn't calling reset properly -- I was leaving off the empty parentheses, which produces no error, but doesn't actually reset the object, apparently. That seems to have improved things considerably, but not completely. > I am not reusing the parser object in my script either (but you can). > You should consider post the program fragment you used. I will if I'm really stuck. But cutting out enough to reproduce the error is a bit of a challenge, if it's still going to work when I'm done. On the other hand, the exercise itself might uncover the problem. Thanks! Nick From fperez528 at yahoo.com Tue Mar 12 17:51:19 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 12 Mar 2002 22:51:19 +0000 Subject: Converting relative URLs to absolute References: Message-ID: James A Roush wrote: > Does anyone have any code that, given that absolute URL of a web page, can > convert all the relative URLs on that page to their absolute equivalent? Assuming absolute is a string and relative_list a list of strings, the followinng comes to mind: [absolute+'/'+relative for relative in relative_list] Maybe you wanted something fancier, don't know. f From sjmachin at lexicon.net Fri Mar 29 15:37:41 2002 From: sjmachin at lexicon.net (John Machin) Date: 29 Mar 2002 12:37:41 -0800 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> <0_Zo8.16784$Ou.11910@atlpnn01.usenetserver.com> Message-ID: "Chris Gonnerman" wrote in message news:... > > Writing a class to simulate a dictionary with default value is simple, > and left as an exercise for the reader :-) > Unfortunately when building a dictionary of frequencies this approach takes about 2.6x the clock() time of the best non-subclassing approach, dropping down to 2.3x if you have a specialised subclass with a hard-coded default value (see below). Even more unfortunately the subclassing approach penalises *ALL* __getitem__ accesses -- after building a dict of frequencies, you don't need/want the default any longer when accessing the dict, but with the subclassing approach, you're stuck with it unless you come up with some pas-devant-les-enfants hack like replacing the __getitem__ method in mid-stream. # best subclassing approach class Defdict0(dict): def __getitem__(self, key): return self.setdefault(key, 0) def build_freq_8(wlist): freq = Defdict0() for word in wlist: freq[word] = freq[word] + 1 return freq # best non-subclassing approach def build_freq_5(wlist): freq = {} freq_has_key = freq.has_key for word in wlist: if freq_has_key(word): freq[word] = freq[word] + 1 else: freq[word] = 1 return freq wlist is a list of strings matching [A-Za-z][A-Za-z]+ in the order they were extracted from files. Yes, the += caper is actually very slightly slower. Yes, the has_key() approach actually beats the get() approach (1.05x) and the try/except approach() (1.3x). Full details on request. Roadtests done on an AMD Athlon processor running win32 Python 2.2.0 with -O. YMMV. Above relative times are based on a case with 1.8M surname and given-name words (174K unique i.e. each word appears 10.4 times on average but the distribution is very skewed). Cases with a much higher average frequency would probably tend to favour the try/except approach. From brobbins333 at shaw.ca Sat Mar 9 19:55:39 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Sun, 10 Mar 2002 00:55:39 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> <3C8AA5E4.982FC689@mega-nerd.com> Message-ID: <3c8aae24.156616153@news> I knew your name was familiar! I'm reading your book right now. It's excellent. VB for one, returns a proper rounded result on these recalcitrant numbers. I'd be willing to bet that C can do it as well, but you should know better than I. The problem is that I am trying to use the return value of round() as the return value of another function, so using Print to tidy it uup really doesn't do me any good. Any suggestions? BR On Sun, 10 Mar 2002 00:16:37 GMT, Erik de Castro Lopo wrote: >brobbins333 at shaw.ca wrote: >> >> I understand the problem of rounding errors with binary numbers. >> However, the rounding functions of other languages work around it and >> return a usable result. What have they got that Python hasn't got? > >Possibly other scripting languages have a feature which includes the >current printing representation with the floating point object. This >would however surprise me somewhat. > >Have you tried that specific example with other languages? I looked >at Perl and it doesn't have a round function. Apparently the preferred >method in Perl is sprintf ("%.2f", 56.78923) which returns a string >instead of a float. > >Once a float is represented as a string you get the behviour you are >after. > >> ps -- your name is very familiar. i think i've read one of your books. > >I only have one, "SAMs Teach yourself C for Linux Programming in 21 days". >I also have a couple of Free Software packages out there. > >Erik >-- >+-----------------------------------------------------------+ > Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) >+-----------------------------------------------------------+ >"If dolphins are so smart, why do they live in igloos?" -Eric Cartman From gwachob at wachob.com Sun Mar 10 00:31:42 2002 From: gwachob at wachob.com (Gabriel Wachob) Date: 9 Mar 2002 21:31:42 -0800 Subject: PyBEEP Project Message-ID: <4e72770c.0203092131.457ad7@posting.google.com> Just a reminder (or a notice!) that the PyBEEP project (open source implementation of BEEP in Python) is marching forward and would like any help anybody would like to give. The project is hosted at sourceforge. http://pybeep.sf.net -Gabe From tdelaney at avaya.com Mon Mar 18 18:27:44 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 19 Mar 2002 10:27:44 +1100 Subject: A question about generators Message-ID: > I have an application where I think either an iterator or a > generator would > be ideal, but I have to be able to reset whichever I use. The paper > "What's New in Python 2.2" says that there's no way to reset > an iterator, > so that's out. Is there a straight-forward way to reset a generator, > though? That's not actually correct. There is no general way to reset and iterator or generator, but you can make a custom iterator or generator that can be reset. Tim Delaney From gimbo at ftech.net Fri Mar 8 09:33:46 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Fri, 8 Mar 2002 14:33:46 +0000 Subject: threads killing other threads In-Reply-To: References: <1013105970.135322@cswreg.cos.agilent.com> <3C62E0D5.99C586DF@ccvcorp.com> Message-ID: <20020308143346.GH9526@andy.tynant.ftech.net> On Fri, Mar 08, 2002 at 01:48:16PM +0000, Joshua Marshall wrote: > If outright killing is disallowed, I'd still like to see the ability > for one thread to cause an exception to be thrown in another. > Currently you can do this to the main thread (on UNIX) by using > process signals. You could always "roll it yourself" by having a threading.Event object shared between the threads - one thread sets the event to tell the other to raise an exception/exit/stop processing/whatever. Or here's a mad idea... You could have a Queue.Queue object shared between the threads, and the first thread could create an Exception object of whatever class it wanted raised (ie not raise it itself, just create the instance) , pass _that_ through the queue, and have the other thread raise it. Why you'd want to do this I'm not sure, but it _would_ work, wouldn't it? Er, I think. Of course, both of these ideas mean the second thread has to have some mechanism for checking the Event or Queue, which may be more work than it's worth. Just thinking with my keyboard... :-) -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From martin at v.loewis.de Mon Mar 25 18:58:14 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 26 Mar 2002 00:58:14 +0100 Subject: Is it really so difficult to enable Tkinter? References: Message-ID: bmeerdnk at telekabel2.nl (Bart Meerdink) writes: > I tried again, installed the tck/tk 8.3.3 headers, did configure, > edited Modules/Setup (paragraph about tkinter, guessing what I should > change there), crossed my fingers, and continued with make and (as > root) make install. Success! > > But I cannot believe this is the intended way. No. You can skip the step where you edit Modules/Setup, since setup.py should find the location of the headers itself. Everything else is as intended; crossing the fingers is optional. Regards, Martin From peter at engcorp.com Mon Mar 4 08:55:45 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Mar 2002 08:55:45 -0500 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <3C82F9F0.2A2DBF16@engcorp.com> <3C82FD24.122E16B3@engcorp.com> <8fc4b19e.0203040151.de463c8@posting.google.com> Message-ID: <3C837CE1.70B74D7C@engcorp.com> Brian wrote: > > Peter Hansen wrote in message news:<3C82FD24.122E16B3 at engcorp.com>... > > Oops, sorry. That sounds a little callous. I really just meant > > to give a response similar to my "programmers always try to optimize > > when they don't really need to" diatribe. > > I originally meant to ask a question more along the lines of "what is > the most pythonic way of doing this." Then I decided all that extra > typing in my message was suboptimal. Was that something that didn't > really need optimization? Your first effort looked very Pythonic to me. :-) From edream at tds.net Tue Mar 5 10:22:51 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 05 Mar 2002 15:22:51 GMT Subject: Patch: clearing breakpoints in IDLE Message-ID: <3C84E2C9.8DC206B4@tds.net> Hi all: I am beginning to think that IDLE's debugger suffers from a vicious cycle: 1. Nobody uses IDLE's debugger, so 2. Nobody complains about its glaring deficiencies, so 3. Nothing gets fixed, so (back to one) OTOH, it's great fun to be able to hack on IDLE so easily. Maybe Guido doesn't want to deprive us all of that fun ;-) To help break this cycle, I offer the following patch that lets the user of IDLE clear breakpoints in exactly the same way that they are set, that is, by right-clicking a source line containing a breakpoint. (I've inserted backslashes so this doesn't get line-breaked to death.) 1. In PyShell.py, add the following two lines, indicated by # EKR: def __init__(self, *args): apply(EditorWindow.__init__, (self,) + args) self.text.bind("<>",\ self.set_breakpoint_here) self.text.bind("<>",\ self.clear_this_breakpoint) # EKR self.text.bind("<>", self.flist.open_shell) rmenu_specs = [ ("Set breakpoint here", "<>"), ("Clear this breakpoint", "<>"), # EKR ] 2. In PyShell.py, add the following new method: def clear_this_breakpoint(self, event=None): if not self.flist.pyshell or \ not self.flist.pyshell.interp.debugger: self.text.bell() return self.flist.pyshell.interp.debugger.clear_this_breakpoint(self) 3. In Debugger.py, add the following new method: def clear_this_breakpoint(self, edit): text = edit.text filename = edit.io.filename if not filename: text.bell() return lineno = int(float(text.index("insert"))) msg = self.clear_break(filename, lineno) if msg: text.bell() return text.tag_remove("BREAK", "insert linestart", \ "insert lineend+1char") I believe that's all there is to it. Aside 1: Unlike the set_breakpoint_here routine, the call to self.clear_break in clear_this_breakpoint calls the method of the super class, i.e., the Bcb class. I don't understand why Debugger.py bothers to create a set_break method. Indeed this comment is strange: # A literal copy of Bdb.set_break() without the print statement at the end There is no print statement in Bdb.set_break in v2.1. Aside 2: In PyShell.py, it seems silly just to ring a bell in set_breakpoint_here if the debugger hasn't been opened by the user. How about opening it for her? Like this: def set_breakpoint_here(self, event=None): if not self.flist.pyshell or \ not self.flist.pyshell.interp.debugger: if 1: # EKR: Try to open debugger automatically. self.flist.pyshell.toggle_debugger() if not self.flist.pyshell or \ not self.flist.pyshell.interp.debugger: self.text.bell() return else: # old way self.text.bell() self.flist.pyshell.interp.debugger.set_breakpoint_here(self) This seems to work for me. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From grante at visi.com Mon Mar 11 21:25:57 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Mar 2002 02:25:57 GMT Subject: Setting UNIX environment with a Python script References: <3C8D143A.17963385@all.com> Message-ID: In article , Cameron Hutchison wrote: > What you need to do instead is have your python program print on stdout > the name of the ora_env file to source. Then you invoke your python > script from your shell login script like this (bourne style shell > assumed): > > eval "source ora_env.`get_ora_name`" Another common method is to have your Python program write the shell commands to stdout, then execute them with something like eval `myPythonProgram` -- Grant Edwards grante Yow! I'm having fun at HITCHHIKING to CINCINNATI visi.com or FAR ROCKAWAY!! From fredrik at pythonware.com Wed Mar 20 14:08:07 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 20 Mar 2002 19:08:07 GMT Subject: error:"_imaging C module is not installed" References: <3C989278.9189857C@helicon.net> Message-ID: Rodney Loisel wrote: > Have 2 files (_imaging.pyd and _imagingtk.pyd) which I assume are the > C imagaging modules and have put copies of them in all the directories > that they might be accessed in for some more clues, try this: c:> python -v Python 2.2.1c1 ... >>> import _imaging and see what happens. From sholden at holdenweb.com Wed Mar 27 12:54:50 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 27 Mar 2002 12:54:50 -0500 Subject: instrumenting Python code References: <1010a26.0203262213.4a0d4b11@posting.google.com> <3CA16839.1A21E36A@engcorp.com> Message-ID: <7Ino8.23465$cB5.19542@atlpnn01.usenetserver.com> "Aahz" wrote in message news:a7svvf$btf$1 at panix1.panix.com... > In article , > Skip Montanaro wrote: > > > >Or, in 2.2, the new hotshot module, which is a lot more efficient at > >profiling than the profile module. > > Where is hotshot? I don't see it anywhere. It's not even on the Vaults > of Parnassus. It's built in: PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import hotshot >>> regards Steve From l0819m0v0smfm001 at sneakemail.com Sat Mar 9 09:16:07 2002 From: l0819m0v0smfm001 at sneakemail.com (Joshua Macy) Date: Sat, 09 Mar 2002 14:16:07 GMT Subject: PEP Parade References: <3C895594.60601@sneakemail.com> Message-ID: <3C89DF58.9080304@sneakemail.com> Chris Gonnerman wrote: > Yeah, but "major" language standards change every few years... Python > releases come about 1-2 per year. We have to resist the urge to change > something major in the core too frequently. > The standards may only change every few years, if you don't count Java as a "major" language, but all the vendors of implementations for those languages I've ever dealt with release patches at the rate of 1-2 per year, or more frequently. Even the COBOL vendors. And every patch release that fixes something stands a chance of breaking something else (even if only code that worked around the old improper behavior). Shops that really care about that and have no viable regression test strategy upgrade less frequently, and if they ship software make sure that they ship exactly what's needed to run their product (no easy task on Windows, thanks to dll hell). My experience is that shops that take the conservative approach (even mainframe shops) eventually end up throwing out working systems because the exact compiler version that they rely on fall off the vendor's support list and it becomes too painful to upgrade through multiple releases. And in Microsoft shops insult is added to injury when you have to pay to upgrade to something that will break your existing code. But nobody is holding a gun to your head and saying "upgrade or die"--and unlike with closed source compilers, if you're bound and determined never to move off 1.5.2 you have the source code so you can continue to maintain it unto as-yet-undreamed-of platforms and architectures. Equally true is that nobody is likely to agree to do this maintenance for you for free. As for me, I've yet to see a change to Python since 1.5.2 that I regard as "major" in terms of incompatibility with existing, working code (plenty of new features for what used to be invalid syntax) that you didn't have to explicitly enable with a __future__ statement, and in that case there was a whole release in between where you could test with either behavior. I can understand people taking a more conservative approach, but then I lose them when they say they should build a sub-community around the inviolability of a particular old release. And do what? Sit around looking at the old source code and say "Yep, we're not going to change that"? The obvious approach to me is that if you're not prepared, for whatever reason, to upgrade: don't upgrade. If you are serious about distributing a stable working system: distribute the whole system, interpreter and library included. Joshua From cce at clarkevans.com Mon Mar 11 11:50:16 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Mon, 11 Mar 2002 11:50:16 -0500 Subject: equivalent of "export" (changing parent's environment) Message-ID: <20020311115016.A35060@doublegemini.com> Hello. I have two shell scripts, a.sh and b.sh such that a.sh calls b.sh, and b.sh uses "export key=value" to set some defaults used later on in a.sh. I'm now converting b.sh to python, and I can't change a.sh easily... so I'm wondering if there is a way to export environment variables from Python? I've read the documentation and see os.environ and os.putenv only affect the current (and sibling process) environment. Is there an equivalent to "export" in Python? Thanks! Clark From johnroth at ameritech.net Thu Mar 7 19:31:34 2002 From: johnroth at ameritech.net (John Roth) Date: Thu, 7 Mar 2002 19:31:34 -0500 Subject: PEP 276 -- What else could iter(5) mean? References: <6qpu2gzktu.fsf@abnoba.intevation.de> Message-ID: "Justin Sheehy" wrote in message news:mailman.1015517623.2914.python-list at python.org... > Bernhard Herzog writes: > > > Do we really want all of these new behaviors? > > No. Please, no. > > I still don't see what this proposal provides in terms of a real gain > in order to offset the obvious potential for ugliness, mistakes, and > the appearance of ambiguity. > > Not having to type "range" or "xrange" doesn't count as a real gain. > > The PEP describes having to use range in this context as a wart, but I > don't remember it ever being referred to as such before this PEP. I suspect whether it is or not depends on your frame of reference, that is, what languages you came from. My background includes Fortran long before anybody ever thought of C, so to me the for loop is slightly bizzare: iteration over a monotonic sequence of integers should be simpler. Python implements a much more useful general case, at the expense of making the special case a bit more difficult. I'm against the proposal, simply on the basis that I don't find 5.iter to have a blindingly obvious meaning. It's ok if you explain it, but it's still not obvious that it's anything but a special case hack. Range (and xrange) at least have the advantage that, once explained, they fit into the scheme of things nicely. John Roth > > -Justin > > > > From skip at pobox.com Mon Mar 18 12:42:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Mar 2002 11:42:18 -0600 Subject: Digest Number 868 In-Reply-To: <20020318181448.A970@wood.mcgraw.org> References: <1016408215.641.83517.m12@yahoogroups.com> <20020318181448.A970@wood.mcgraw.org> Message-ID: <15510.9978.53152.494573@beluga.mojam.com> Garret> Does any know a good way to talk to a mysql database besides Garret> depending on the fact that the computer might happen to have Garret> that mysql module installed? I guess I could just figure out Garret> how the protocol works and access it by opening a socket to it Garret> and interpert what it gives me...... but I would like to know if Garret> someone has already done that and see if i could download it. I think that nobody in their right mind in this group would have done that, since the MySQL people already provide a free client library to allow C programs (and programs that can call C functions) to talk to the server without understanding anything about the protocol. The mysql-python stuff layers on top of that. The MySQL developers probably view their client-server protocol as not part of the public interface, so even if you managed to write a raw socket interface you'd be at the mercy of changes to the protocol whenever the remote server was upgraded. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From tim.one at comcast.net Wed Mar 13 20:40:20 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 13 Mar 2002 20:40:20 -0500 Subject: Question about scientific calculations in Python In-Reply-To: Message-ID: [Bengt Richter (maybe)] > If your lists are really long (O(100,000) or more?) then you might find > that the append starts taking too long -- append is asymptotically > O(n**n) whoa! can that be true? No, theoretical worst case is O(n**2). (1 + 2 + 3 + ... + n == ?) [Andrew Dalke] > Yes, it's true. Only when the sky is falling too . > This comes up on the list about once every six months or so. As I > recall, Python's standard lists grow by 10 elements at a time for > small lists (less than 500 in length), then 100 at a time for larger > lists. That used to be true, but over-allocation is always proportional to list size now. This had most benefit on assorted Windows flavors (which don't act alike in this respect). It made no difference at all on some assorted Unixish systems (append often enough and it may get reassigned to its own mmap'ed region; or it may get moved to the sbrk limit so that further appends "just" bump the high-water VM mark without physical movement). > ... > Insertions and deletions are also linear in the length of the list. They're linear in the length of the list following the insert/delete position. > Yes, we all know there are better ways to deal with this, for different > people's definition of the meaning "better." It isn't going to change > in Python. Fast constant-time (modulo cache effects) random access is Python's chief goal for Python lists. > Best I think would be a standard module of data structures (priority > queue, doubly-linked lists, stack, etc.) But it hasn't bothered > me enough to go ahead and do it. Guido doesn't go for this kind of thing: the more "advanced" the data structure, the more specialized variants it sprouts, and there aren't enough volunteers to maintain the ever-bulging code across all the platforms Python runs on. From edcjones at erols.com Tue Mar 26 23:25:01 2002 From: edcjones at erols.com (Edward C. Jones) Date: Tue, 26 Mar 2002 23:25:01 -0500 Subject: C API for modules References: <3CA09F43.80206@erols.com> Message-ID: <3CA1499D.4070802@erols.com> John Machin wrote: > "Edward C. Jones" wrote in message news:<3CA09F43.80206 at erols.com>... > >>Is there some simple way to call functions in modules from C? In >>particular, for module struct, how do I call pack, unpack, and calcsize? >> > > > OK, I'll be the bunny and ask the obvious(?) meta-question: > > Give that the struct module is designed for Python callers to > pack/unpack C structs (laboriously), why bother? Why not just > manipulate the structs in C?? So I should use PyString_FromStringAndSize in C and struct.unpack in Python or struct.pack in Python and PyString_AsStringAndSize in C. From gimbo at ftech.net Wed Mar 20 12:41:08 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 20 Mar 2002 17:41:08 +0000 Subject: Python2.2 Installation In-Reply-To: References: Message-ID: <20020320174108.GJ18847@andy.tynant.ftech.net> On Wed, Mar 20, 2002 at 12:30:28PM -0500, python-list-admin at python.org wrote: > I downloaded and almost installed Python 2.2 from the Python-2.2.tgz > release on SF by doing the 'usual "gunzip; tar; configure; make" dance'. > I now have a Python-2.2 directory which seems to work by itself. [snip] > So how do I complete the installation so that Python2.2 is at least in > /usr/bin? How do I replace the 1.5.2 installation that came > preinstalled (which is in /bin)? make install ? -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From newsfroups at jerf.org Mon Mar 25 01:19:46 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Mon, 25 Mar 2002 06:19:46 GMT Subject: list comprehension question References: <5.1.0.14.2.20020324115311.0457dbb8@202.95.131.154> Message-ID: <3C9EC15A.3030103@jerf.org> Tripp Scott wrote: > thanks for the tip. actually, the essence of what i wanted to ask was: > "can that SOMETHING be a list of more than one elements which will be > _flatly_ added to the result list." as another example, can i generate > this list > > [1,1 2,2,2, 3,3,3,3, 4,4] The closest thing I can get is something like this: [x+float(y)/10 for x in range(10) for y in range(x)] where the second for statement depends on the first. How about examples of real input and real output you want? And why are you asking specifically about list comprehensions? (Are you just trying to learn about them?) If you're trying to solve a real problem, they may not be the best solution. (Though the odds are good.). From aahz at panix.com Sat Mar 9 06:31:11 2002 From: aahz at panix.com (Aahz Maruch) Date: 9 Mar 2002 03:31:11 -0800 Subject: Turn string into function call References: <1f5252d4.0203080545.3861adec@posting.google.com> Message-ID: In article , Grant Edwards wrote: >In article <1f5252d4.0203080545.3861adec at posting.google.com>, N Becker wrote: >> >> What's the best way to turn a string naming a function into a function call? >> >> I used this: >> eval (funcname + '()') > >This really ought to go into the FAQ. It's been asked (and >answered) at least 3 times in the past week or so. Okay, here's a proposed FAQ entry, for section 4: How do I convert a string to a function/method call? There are two basic techniques: * Use a dictionary pre-loaded with strings and functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct: def a(): pass def b(): pass dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs dispatch[get_input()]() # Note trailing parens to call function * Use the built-in function getattr(): import foo getattr(foo, 'bar')() Note that getattr() works on any object, including classes, class instances, modules, and so on. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From tim.one at comcast.net Wed Mar 20 11:55:03 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 20 Mar 2002 11:55:03 -0500 Subject: Develop-test-debug cycle In-Reply-To: Message-ID: [Charl P. Botha] > ... > In anycase, I have a rather large software platform that reloads > modules with classes all the time. So, the platform itself keeps on > running while I hack away at a new module; with every change I reload > the module and my platform instantiates it AND I get to see the changes > in action. Test. Modify. Repeat. > > Maybe the complex/simple case classifier in my version of Python > is buggy? ;) Yes, and we're not going to fix it . "The problem" is that modules are objects just like any other objects in Python, and "import" does binding just like any other binding stmt. When module X does import Y X gains a module variable named "Y" bound to whatever module code was most recently loaded for Y. A subsequent reload(Y) *outside* of X can't change the binding of X.Y -- within X, Y still refers to "the old" module object. Ditto for things like "from Y import ClassA" inside X, of course -- no matter what happens to Y, X.ClassA continues to refer to whatever Y.ClassA mapped to at the time the import statement was executed. There isn't a clear way to "fix this", in part because it's hard to come up with a rigorous way to justify calling it "broken" to begin with: the code does what the Ref Man says it does, and that's just how objects and binding statements work in Python. In the same way, after doing x = [1, 2, 3] y = x a later instance of x = [3, 2, 1] doesn't magically change the binding of y either. From skip at pobox.com Mon Mar 11 17:15:07 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 11 Mar 2002 16:15:07 -0600 Subject: nonblocking i/o on windows? Message-ID: <15501.11371.105898.746698@beluga.mojam.com> At the end of asyncore.py a non-blocking file_dispatcher class is defined like so: class file_dispatcher (dispatcher): def __init__ (self, fd): dispatcher.__init__ (self) self.connected = 1 # set it to non-blocking mode flags = fcntl.fcntl (fd, fcntl.F_GETFL, 0) flags = flags | os.O_NONBLOCK fcntl.fcntl (fd, fcntl.F_SETFL, flags) self.set_file (fd) def set_file (self, fd): self._fileno = fd self.socket = file_wrapper (fd) self.add_channel() Unfortunately, this uses fcntl, which is only available on Unix systems. Is there something similar on Windows that will allow me to put a Python file object in non-blocking mode? I thought perhaps there would be something defined in msvcrt, but I didn't see anything in the lib ref manual or the msvcrt source. Thx, -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) "As often happens in Net communities, people find all kinds of energy to compose incisive criticisms of the threads and postings of other members, when they could be directing that energy towards brilliant new threads and postings of their own." - Tom Neff From philh at comuno.freeserve.co.uk Fri Mar 8 05:43:45 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 8 Mar 2002 10:43:45 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Thu, 07 Mar 2002 09:36:10 -0800, David Eppstein wrote: >In article , > philh at comuno.freeserve.co.uk (phil hunt) wrote: > >> How about: >> >> for i = 1 to 10: >> >> or >> >> for i is 1 to 10: >> >> I think these are both equally good and both much preferable over >> the horrible >> >> for 1 <= i <= 10: >> >> which I can only assume is someone's sick idea of a joke. > >Your "1 to 10" syntax (and most other ideas floated previously on this >group) assumes a fixed type of interval (closed, I'm guessing, but it's >not clear), and not even the most common type (half-open). Not sure what you mean here. > The proposed >syntax makes explicit what would happen at the ends of the intervals. > >One alternative proposal, that didn't seem to have as much support but >might still be worth looking at, was to allow the creation of ranges by >"1 <= ... <= 10" (possible without much modification of the compiler via >a clever enough definition of "...") so then one could do >"for i in 1 <= ... <= 10". > >I would appreciate it if you could give me a more constructive criticism >of PEP 284 than "horrible", "someone's sick idea of a joke", which don't >give me much idea why you don't like it. Thev reasdon i don't like it is that the syntax already has a meaning: to compare the magnitude of values. Now you are proposing another, totally different, meaning. In a way what you are saying is (a <= b <= c) means return a list of all the integer values of (b) that satisfy this statement. But that isn't really true, because you can't do things like: a <= b*2 <= c or: 2 <= b and b*b <= c etc. So the system isn't fully general. In fact, its expressiveness is *less* than the existing range/xrange system, in which you can specify a step. The onlyt problem with range/xrange, as I see it is that it always excludes the to-value, ie. range(0,3) returns [0, 1, 2] So perhaps it would be better if there were rangei/xrangei functions, such that: rangei(0,3) returns [0, 1, 2, 3] (Or has this been fixed in 2.2?) -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From niemeyer at conectiva.com Mon Mar 25 10:38:55 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Mon, 25 Mar 2002 12:38:55 -0300 Subject: Root access with python In-Reply-To: References: <7x663krjtp.fsf@ruckus.brouhaha.com> Message-ID: <20020325123855.A1716@ibook.distro.conectiva> >>> On the terminal, you would do a 'su', type your password, then enter >>> the command you wanted to run. How is this achieved within Python? [...] >>Instead, run "su" the usual way and type your password to get a root >>shell, then launch your GUI app from the root shell. > > Good advice. Nevertheless, if Moray wants to shoot zirself in the foot, > zie should take a look at os.setuid(). Fortunately, it's not that easy. os.setuid() is useful if you want to drop privileges, not the other way around. You have several options to do this, and all of them involve setting the setuid bit in some executable. OTOH, setting setuid bit on scripts usually doesn't work. If that's your case, you'll have to freeze your script into a native executable, or build some kind of wrapper. Google for "setuid bit scripts" for more information. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From bergeston at yahoo.fr Wed Mar 13 09:34:12 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Wed, 13 Mar 2002 15:34:12 +0100 Subject: Is Python an object based programming langauge? References: Message-ID: "Anton Vredegoor" wrote in message news:a6nifr$eob$1 at news.hccnet.nl... > On the other hand its entirely possible that the source of the > confusion is something completely different. > > Anton. IMHO, the OO paradigm can be summarized with: - inheritance, - polymorphism, - encapsulation If you see it like that, there is no possible confusion and Python is undoubtedly OO ! I know that a discussion still exists about encapsulation. My opinion is that Python classes clearly encapsulates instance data and consider us as adults (no instance baby sitter hidden somewhere in the compiler or in the interpreter). And now, the only important question remains: are we able to write OO applications ? I mean modular, reusable, maintainable, ... ones. The language matters but the design makes the difference. B. From mcherm at destiny.com Mon Mar 25 17:30:54 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 25 Mar 2002 17:30:54 -0500 Subject: How to get a key from dictionary? Message-ID: <3C9FA51E.5040008@destiny.com> > Hi, > Is there a possibility to get, from a dictionary, a key according to a > value ? > For example > I have a dictionary > > dict={'aa':1,'bb':2} > > and > dict['aa'] > is 1 > > But how can I for value 1 find out key? (That is here 'aa') > > Thank you for help > Ladislav Yes, you can get this information, but there are two things you should be careful of: 1) The dictionary is designed so it is very fast to find the value for a given key. Finding the key for a given value will be much slower ( O(size-of-dictionary) to be specific ). 2) Sometimes a dictionary will have MORE THAN ONE key with the SAME value. So maybe you want just any random key with that value, or perhaps you want ALL the keys with that value. I'll show how to do both. Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> dict = {'aa': 1, 'bb':2, 'cc': 3, 'BB': 2} >>> def getSomeKeyForValue( dict, valueToFind ): """Returns some random key with the given value, or throws KeyException""" for key, value in dict.iteritems(): if value == valueToFind: return key raise KeyException() >>> getSomeKeyForValue( dict, 1) 'aa' >>> getSomeKeyForValue( dict, 2) 'BB' >>> getSomeKeyForValue( dict, 4) Traceback (most recent call last): File "", line 1, in ? getSomeKeyForValue( dict, 4) File "", line 7, in getSomeKeyForValue raise KeyException() NameError: global name 'KeyException' is not defined >>> def getAllKeysForValue( dict, valueToFind ): """Returns a list of the keys in dict with the given value. If no value is found the list is of length 0.""" answer = [] for key, value in dict.iteritems(): if value == valueToFind: answer.append(key) return answer >>> getAllKeysForValue( dict, 1 ) ['aa'] >>> getAllKeysForValue( dict, 2 ) ['BB', 'bb'] >>> getAllKeysForValue( dict, 4 ) [] -- Michael Chermside From b.follek at verizon.net Sat Mar 9 06:30:40 2002 From: b.follek at verizon.net (Bob Follek) Date: Sat, 09 Mar 2002 11:30:40 GMT Subject: Tokenize a string or split on steroids References: <4lpj8u4nbsoqjf2h4upadti62jh4sf4i59@4ax.com> Message-ID: <3C89F25F.A560003F@verizon.net> "Fernando Rodr?guez" wrote: > > I need to tokenize a string using several separator characters, not just one > as split(). > > For example, I want a function that returns ['one', 'two'] when given the > string '{one}{two}' . > > How can I do this? O:-) Take a look at the re library module. For example: >>> import re >>> x = re.compile('\w+') >>> x.findall('{one}{two}') ['one', 'two'] If you're unfamiliar with regular expressions, here's a good starting point: http://py-howto.sourceforge.net/regex/regex.html From eppstein at ics.uci.edu Wed Mar 6 17:26:03 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 14:26:03 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , Steve Lamb wrote: > Also the proposal takes a nice line-noise approach to it. I want line noise, > I'll use Perl or Brainfuck. As a Teco programmer from a long time ago, I'm no longer interested in the aesthetic value of line noise. Would it be adequate to summarize your criticism more politely: you think the proposed syntax is too terse, and would prefer something wordier? From jeff at ccvcorp.com Thu Mar 14 19:31:46 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 14 Mar 2002 16:31:46 -0800 Subject: Why Don't Scripts Run ? References: <3C8F9C59.F9408D47@mcn.net> <3C8FB1E0.C0E0C6E7@mcn.net> Message-ID: <3C9140F2.BF3C233@ccvcorp.com> jrc wrote: > The confusion is that this small point is completely > overlooked in the documentation, including Fehily's > book. A newcomer gets the impression that one starts > the interpreter, THEN types 'python script.py', which > leads to the errors I initially experienced. While I can't speak for that particular book, and don't care to search the Python docs at this time, I'm pretty sure that a distinction is made between directing you to type at a command prompt (or maybe shell prompt), and directing you to type in the interpreter. It is quite likely, though, that the difference between these is not made explicitly clear. I would have imagined that someone capable of installing python would understand that "command prompt" (or equivalent phrase, e.g. "DOS prompt", "DOS box", "console") means, in fact, to use the operating system's shell (DOS, bash, cmd.exe, et. al.). This *has* come up several times before, however. Obviously, we can't do anything about the book, but perhaps the Python tutorial should be reworded to make this distinction clear? (If it's not already -- the confusion may well result *only* from a book's wording, and someone learning from a book is rather less likely to bother going through the tutorial...) Jeff Shannon Technician/Programmer Credit International From mhammond at skippinet.com.au Tue Mar 19 06:25:47 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 19 Mar 2002 11:25:47 GMT Subject: Chewing international (unicode) filenames on windows? References: <3C96F705.50908@skippinet.com.au> Message-ID: <3C972048.9070105@skippinet.com.au> Andrew Markebo wrote: > | > For me on my windows 2000 machine, to get them into UTF-8 format I do > | > something like: > | > for filename in os.listdir(): > | > utffilename=unicode(filename, "latin-1").encode("utf-8") > | > | utffilename=unicode(filename, "mbcs").encode("utf-8") > > Hello! > > So do I get it right now, reading it as mbcs ("Multibyte-character") > will read all ntfs filenames correctly (as unicode defines it) into a > unicode string? This will work as long as the filename can be represented in your current code page. If not, you will get a '?'. Other comments in this thread point to a proposal to use Unicode objects making every file available regardless of your codepage. > | > p.s.2 what is the status on win9x? Give it up or ;-) > | > | I *think* it still works when accessing a Unicode aware file system > | (ie, network) > > What I want is to read a local file-name on a win9x fat/fat32 disk and > be able to convert it into unicode.. And the other way around. > > I will probably add a if windows9x do that, else if win2k do > this.. ;-) Hmm how do I determine windows-version? win32api.GetVersion(Ex) Mark. From logiplexsoftware at earthlink.net Fri Mar 29 18:02:25 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 29 Mar 2002 15:02:25 -0800 Subject: Another stab at a "switch/case" construct (new proposal): In-Reply-To: References: Message-ID: <20020329150225.7efdaf2b.logiplexsoftware@earthlink.net> On 29 Mar 2002 14:35:25 -0800 Ken Peek wrote: > branchon MyObject: > > [Object_1, Object_N, (99,98,MyVar), 42]: > # do something > # do more > fallthrough # (fall through to next clause body) > [[1,2,3], "hello", MyDynamicObject, MyList]: > # do something > # do more > > []: > # this matches if "MyObject" is an empty list > # do something > # do more > > else: > # we did not have any matching clauses > # do something > # do more > > ================================== > > OK-- please send in the next barrage of critisism... OK ;) /If/ a switch/case style test were to be added to Python, the fallthrough should not be included. Although not falling through by default is better than having to explicitly not fall through (ala C), it still makes the code less clear. If there is common code to be shared between cases, put it in a function. I still feel that the need for this type of construct is unnecessary most of the time. Special-case code should be encapsulated within an object. Contrast the following: switch type(object): int: print "%d" % object str: print "%s" % object list: print "[", for i in object: print i, print "]" with: print object Now which is cleaner? I think the perceived need for this type of construct is a holdover from thinking in other programming languages versus thinking in Python. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From roy at panix.com Fri Mar 8 09:03:06 2002 From: roy at panix.com (Roy Smith) Date: Fri, 08 Mar 2002 09:03:06 -0500 Subject: PEP Parade References: Message-ID: "Tim Peters" wrote: > Note that Guido wants to keep 2.3 free of new core language features. You > can deduce that from reading the essay, or-- like me --you can just believe > it because it's true . There's a huge backlog of good ideas for > improving the internals and libraries, and I wouldn't be surprised to see > the focus remain there for 2.4 too. Not touching the core language is a Good Thing. It's really tough to convince people that python is a viable tool when it's a moving target. It's been somewhat of an uphill battle to get my development group to accept the fact that I write tools for the whole group's use in python. Having the core language change from version to version just makes it worse, as we discover imcompatabilities between whatever version I'm using to develop on and whateve they're running on their boxes. Telling people, "Oh, you need to upgrade to version X" gets old pretty fast. As the saying goes, "if you're explaining, you've already lost." From Oschler at earthlink.net Sun Mar 31 18:25:09 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 31 Mar 2002 18:25:09 -0500 Subject: Python quick setup URL for Linux setup? Message-ID: Can anyone point me to a fasttrack URL/doc for setting up Python on Linux running KDE? If it matters I'm using SUSE 7.3 Pro. thx From d95-bli.no at spam.nada.kth.se Fri Mar 22 13:02:18 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-1?Q?Bj=F6rn?= Lindberg) Date: Fri, 22 Mar 2002 19:02:18 +0100 Subject: Popular style document? References: <1016641355.370859@cswreg.cos.agilent.com> <3C9A797E.E6476BEE@spam.nada.kth.se> Message-ID: <3C9B71AA.C485BF2C@spam.nada.kth.se> Terry Reedy wrote: > "Bj?rn Lindberg" wrote in message > > How come Python doesn't have an "automatic" this-variable, like C++ > or > > Java? > If you mean requirement to say def meth(something, arg) instead of def > meth(arg), compiler does not necesarily know when compiling whether > function will be used as method or not. (Methods can be defined > outside of class statement and assigned as method later.) Yes, this is what I meant. How does this work though, when assigning a method to a class? I mean, let's say that you have a method taking two arguments, concatenate (x, y). When assigning this method to a class, will that mean that the first argument is always replaced by the class instance, so I'd have to call it like this: aclass.concatenate (y), and the first argument, x, will always correspond to aclass? Bj?rn From martin at v.loewis.de Sun Mar 17 03:56:52 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Mar 2002 09:56:52 +0100 Subject: HP-UX, PyThread_* missing References: <1016327435.513664@cswreg.cos.agilent.com> Message-ID: weeks at vitus.scs.agilent.com (Greg Weeks) writes: > Martin v. Loewis (martin at v.loewis.de) wrote: > : In any case, the common understanding is that Python does not really > : support threads on HP-UX, and probably never will unless some HP-UX > : user who understands all the issues provides patches. > > Still, I've been using threads with HP-UX 10.2 and Python 1.5.2 for months > now. (Maybe I haven't stressed it.) Also, "make test" passed cleanly with > HP-UX 11 and Python 2.2. It seems to be the combination of HP-UX 10.2 and > Python 2.2 that is causing trouble. Yes, threads work well on HP-UX 11; for HP threw away the thread implementation and rewrote it from scratch. I believe that the thread library of HP-UX 10.20 has problems that also could be demonstrated with Python 1.5 - it's only that the test suite of Python 1.5 does not demonstrate them. Regards, Martin From daves_spam_dodging_account at yahoo.com Fri Mar 29 15:43:30 2002 From: daves_spam_dodging_account at yahoo.com (David Brady) Date: Fri, 29 Mar 2002 12:43:30 -0800 (PST) Subject: Ooops, sorry, wrong list :-) In-Reply-To: Message-ID: <20020329204330.12246.qmail@web21102.mail.yahoo.com> Sorry 'bout that... -dB ===== David Brady daves_spam_dodging_account at yahoo.com I'm feeling very surreal today... or *AM* I? __________________________________________________ Do You Yahoo!? Yahoo! Greetings - send holiday greetings for Easter, Passover http://greetings.yahoo.com/ From ellem at optonline.net Wed Mar 27 17:04:34 2002 From: ellem at optonline.net (Lou Moran) Date: Wed, 27 Mar 2002 22:04:34 GMT Subject: I am Tarage your new ruler References: Message-ID: <1eg4au4ntod5fe1u1eu91k51n8aovsn6gd@4ax.com> On Sun, 24 Mar 2002 18:46:44 GMT, "Tarage" wrote a glowing report about my Usenet practices: >That's right you stupid, inbred, OK You win. Can you write a Perl script to amend my sig? -- Lou Moran (P3 850) Guinness _has_ affected this post From mmiller3 at iupui.edu Wed Mar 13 13:24:50 2002 From: mmiller3 at iupui.edu (Michael A. Miller) Date: 13 Mar 2002 13:24:50 -0500 Subject: python and analyze image format? References: <87henkickf.fsf@lumen.indyrad.iupui.edu> Message-ID: <87adtciavh.fsf@lumen.indyrad.iupui.edu> >>>>> "F" == F GEIGER writes: > Could PIL be what you are after? See www.pythonware.com The version that I'm familiar with (1.1.2) does not support analyze format. Do you know if the commercial version does? Mike From jimd at vega.starshine.org Sun Mar 17 19:08:41 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 18 Mar 2002 00:08:41 GMT Subject: how to set the background color of a window with curses References: <20020309125336.GA2236@lurkabove.darkstar> <20020309164204.GB1466@lilith.hqd-internal> Message-ID: In article , Marco Herrn wrote: > On Sat, Mar 09, 2002 at 05:42:04PM +0100, Gerhard H?ring wrote: >> Le 09/03/02 ? 13:53, Marco Herrn ?crivit: >>> Hi, >>> I am trying to set a backround color for a window and did it with >>> stdscr.bkgd(' ', curses.COLOR_BLUE) >>> But that doesn't work. It seems to do nothing. >>> What am I doing wrong? >> You're confusing colors with attributes. I recently stumbled across that >> one, too :) > Hmm, that may be true.... ;) >> This will do the trick: >> # define color 1 as black on blue >> curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_BLUE) >> stdscr.bkgd(' ', curses.color_pair(1)) > No, that doesn't work for me. > The whole screen remains black. I get no error message and any text that > is displayed with color_pair(1) is correctly displayed in black on blue. > Am I missing something else? >> Btw. there's a curses howto on http://py-howto.sf.net/ in case you >> didn't know. > Yes, I did read it. It is a good starting point, but unfortunately > doesn't go over my problem ;) I don't think that the Python Curses HOWTO is a good starting point for curses, especially regarding the use of color in ncurses. Here's a working example of color and attributes in curses: #!/usr/bin/env python2.2 """ Curses Clock: draw a colorful clock in the center of a terminal and update it every second. Quit on first keystroke Bugs: handles window change (SIGWINCH) crudely abends (exit code 1) if not curses.has_colors(), no error message mouse events are so totally not working! (may be cause of segfault?) by James T. Dennis Sun Mar 17 15:06:52 PST 2002 """ import curses, time, random, string, sys def main(w): w.keypad(1) w.leaveok(1) w.immedok(0) w.nodelay(1) w.scrollok(0) w.erase() norm = curses.A_NORMAL bold = curses.A_BOLD dim = curses.A_DIM if curses.has_colors(): colorlist = (("red", curses.COLOR_RED), ("green", curses.COLOR_GREEN), ("yellow", curses.COLOR_YELLOW), ("blue", curses.COLOR_BLUE), ("cyan", curses.COLOR_CYAN), ("magenta", curses.COLOR_MAGENTA), ("black", curses.COLOR_BLACK), ("white", curses.COLOR_WHITE)) colors = {} colorpairs = 0 for name,i in colorlist: colorpairs += 1 curses.init_pair(colorpairs, i, curses.COLOR_BLACK) colors[name]=curses.color_pair(i) else: sys.exit(1) ## (mousecap, mouseold) = curses.mousemask(0) ## (mousecap, mouseold) = curses.mousemask(mouseold | mousecap) tpart = { "day": 0, "month": 4, "date": 8, "hour": 11, "min": 14, "sec": 17, "year": 21 } key = 0 while 1: if key == 0 or key == 410: # 410 is from SIGWINCH? w.erase() y,x=w.getmaxyx() mid = y / 2 ctr = x / 2 t = time.asctime() ctr -= len(t) / 2 ### k = w.getkey() ### Warning: previous line causes segfault! key = w.getch() ## if key == 410: continue if key == ord('q') or key == ord('Q'): break else: w.addstr(0, 0, "\t%s\t" % key, colors["yellow"]) ### w.addstr(0, 0, "\t%s\t" % curses.keyname(k), colors["yellow"]) ### Warning: previous line causes segfault! t = time.asctime() w.addstr(mid,ctr+tpart["day"], t[0:3],colors["blue"] | norm) w.addstr(mid,ctr+tpart["month"],t[4:8],colors["blue"] | dim) w.addstr(mid,ctr+tpart["date"], t[8:11],colors["blue"] | bold) w.addstr(mid,ctr+tpart["hour"], t[11:14],colors["red"] | dim) w.addstr(mid,ctr+tpart["min"], t[14:17],colors["red"] | bold) w.addstr(mid,ctr+tpart["sec"], t[17:20],colors["green"] | dim) w.addstr(mid,ctr+tpart["year"], t[20:],colors["magenta"] | dim) time.sleep(1) return key if __name__ == "__main__": x = curses.wrapper(main) print x This may not be efficient, but it shows the basics of handling color and attributes. BTW: the "dim" attribute looks just like "normal" on my terminals (xterms and Linux console). So that may not be useful in most cases. As you can see it isn't at all clever about terminals that lack ncurses color support, and it can't handle dynamic window size changes (SIGWINCH) Separately I'm playing with the signal module to see if I can add SIGWINCH support my own version of curses.wrapper. (Although it seems that getch() returns 410 on window resize events). I've also been mentally playing with possible ways to create an enhanced curses.wrapper with support for passing arguments to main() and return values back from it. (Of course I can simply create a global mutable "retval = []" and do an assignment to that prior to a return. Actually it seems I can call: r = curses.wrapper(foo) and get the return value from foo(). Also NOTE the two lines where I get python to segfault (this is Python2.2 from Debian "Unstable") but it does it under 2.1, too. (It segfaults on any reference to curses.keyname OR w.getkey() the two are orthogonal paths to the failure) There are still some things I don't understand about this. The mouse stuff is completely opaque (and virtually undocumented). > Bye > Marco > Experience is something you don't get until just after you need it. ^^^ the first time From James_Althoff at i2.com Mon Mar 11 14:45:42 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 11 Mar 2002 11:45:42 -0800 Subject: PEP 284, Integer for-loops (fwd) Message-ID: [David Mertz] |"Gnosis XML Utilities" has 3100 lines (written largely by me, |with various contributors). |There are *4* uses of [x]range() in 'for' loops. One is a test case |that just uses 'range(500)' to do something "a bunch of times". [James_Althoff at i2.com] |I just did the same for a small section of our code. My quick little scan |turned up 293 uses of [x]range. |Our mileage might be different from others because our use of Jython is for |large-scale, shipping, production-level, commercial applications rather |than for small, throw-away scripts or core-language libraries. Also (as |mentioned) we use Jython and have to deal with tables [David Mertz] |My utility package is certainly not "throw-away scripts". And while |it is generally tested with CPython, there's no reason it shouldn't |work equally well with Jython. So some of that difference isn't |really germane. You are right. There are more categories and possible factors. |The issue about iterating through data tables might be the key. I think so too. What is key in particular is that the table components were designed outside of Python and independent of Python's standard conventions. |But I think even then, my own style would generally not use range() |iteration. | |For example, one might write (very simplified): | | rows = dbquery(sql) | for i in range(len(rows)): | print i, rows[i] | |But I would probably approach this more like: | | i = 0 | for row in dbquery(sql): | print i, row | i += 1 | |It feels cleaner to me to iterate through the actual collection, |rather than numerically over its length... even if I am then interested |keeping track of the number. That is nice alternative *when* you can say row in table But if your protocol is def getRowCount(): pass def getColumnCount(): pass def getValueAt(rowIndex,columnIndex): pass def setValueAt(rowIndex,columnIndex): pass then that option is not available. |If one fetches rows incrementally, I would |still probably go for a 'while 1:' style. That is an alternative. It seems unfortunate to me that one would have to drop back to a "while 1:" style when dealing with something so common and fundamental as indices. But that's just my opinion. Jim Althoff Senior Vice President i2 Technologies, Inc. From bkc at Murkworks.com Sun Mar 3 12:14:19 2002 From: bkc at Murkworks.com (Brad Clements) Date: Sun, 3 Mar 2002 12:14:19 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: <3c82575f$1_3@news.newsgroups.com> This also happens on Win2k with Python 2.2 P:\PUBLIC\DEMOS\WSOCK>python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 >>> 1e-200 9.9999999999999998e-201 >>> > So it probably is a gcc/glib bug of some sort, but I don't really know where. I'm running the windows binary provided at python.org, wasn't this compiled with vc? -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! Check out our new Unlimited Server. No Download or Time Limits! -----== Over 80,000 Newsgroups - 19 Different Servers! ==----- From eric.brunel at pragmadev.com Tue Mar 19 12:52:42 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 19 Mar 2002 17:52:42 +0000 Subject: Extending Python/Tkinter References: <5acdbd0c.0203190838.20c3733e@posting.google.com> Message-ID: Cris Eck wrote: > I have a C++ class that draws maps that I've been assigned to extend > into python. The class uses X primitive calls (XDrawPoint, etc.) to > do much of the work and I'm at a loss on how to integrate this as an > extension to Python. Initially I thought I could get a drawable, > display and graphics context from the Tk C API. Then I saw that > Tkinter is using the Tcl interpreter and not calling the Tk routines > directly. Now I'm lost. Hi Cris, I'm just the opposite of you (knowing quite well Tk/Tkinter, but nothing about X primitives), but I saw once in the comp.lang.tcl newsgroup that you could use the equivalent of the winfo_id method on Tkinter widgets to get the internal X11 window id, that you should be able to use at the X11 level. You'll find more info in the Tk manuals, e.g. at http://dev.scriptics.com/man/tcl8.3/TkCmd/winfo.htm I don't know however if it can be of any help for you... - eric - From jjb5 at cornell.edu Mon Mar 25 15:27:25 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Mon, 25 Mar 2002 15:27:25 -0500 Subject: New SIG on logic/CLP programming in Python Message-ID: > goal member(X,L): > if (len(x) == 0): > fail > if (X != L[0]): > fail Oops. goal member(X,L): if (len(L) == 0): fail if (X != L[0]): fail From eppstein at ics.uci.edu Wed Mar 6 12:16:06 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 09:16:06 -0800 Subject: PEP 284, Integer for-loops In-Reply-To: References: Message-ID: <6874703.1015406166@[192.168.1.100]> On 3/6/02 9:08 AM -0800, Sean 'Shaleh' Perry wrote: > From watching the lists I have seen more people looking for C > style for(;;) loops than anything. The syntax you propose is extremely > confusing to anyone who has used a for loop in C. My other complaint is > the lack of generality caused by not using the C syntax. Thanks for the comments, but it seems clear (and I think it's a good thing) that C-style for's are not going to happen in Python. They're very general, but not very intuitive, especially to non-C-programmers. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From pearu at cens.ioc.ee Sun Mar 10 16:23:39 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sun, 10 Mar 2002 23:23:39 +0200 Subject: How to disable assert statements inside a module? In-Reply-To: <15499.52105.790818.353389@12-248-41-177.client.attbi.com> References: <15499.52105.790818.353389@12-248-41-177.client.attbi.com> Message-ID: On Sun, 10 Mar 2002, Skip Montanaro wrote: > Pearu> So, I would like to disable the assert statements in one module > Pearu> while in others, that are under development, assert statements > Pearu> are enabled. Is it possible? I am using Python 2.2. > > This comes to mind: > > s/assert /pass; #assert/ > > :-) Thanks :-) I now tried that. It turns out that it does not help much. python -O must do something more than just disabling assert statements. So, let me rephrase my question: Is it possible to turn on the optimization in one module while in others it is off (so that their assert statements are in effect)? Pearu From dragon at china.org Sat Mar 9 06:44:45 2002 From: dragon at china.org (Qiang.JL) Date: Sat, 09 Mar 2002 11:44:45 GMT Subject: should i learn it first ? Message-ID: Hi,all apologize if this is off-topic :) I am a student who have learned perl,java and other like data structure stuff. Now i want to take some further step to learn one or two languages to improve my language view. There are two languages are on the list: python and C++ I have heard a lot ppl talk about C/C++,saying it's the must language to learn for a programmer.and i indeed feel so. but C/C++ is hard and may need to take longer time to learn and get the concept.also, Python seems a good language and easier to learn. I think some of you may come cross this, so let me ask you these questions do i need to learn C/C++ to be a good programmer? which one is better to start with ? ( I'm not a program beginner so python being a beginner programmer maybe not be applied here) How many language do you think one should _master_? I think one or two is enough.learning others are letting you to learn the language concept and structure etc certainly helpful. From peter at engcorp.com Sun Mar 17 01:22:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 17 Mar 2002 01:22:57 -0500 Subject: mixing regular expression References: Message-ID: <3C943641.CD0086B3@engcorp.com> Ian McMeans wrote: > > How should go I about nesting regular expressions in python? > > I want one huge regular expression to be composed of a bunch of others - is > there some way I can include a regular expression inside another? > > Or should I do it with strings - just save each regular expression's string, > and then compile each combination separately? > > What I mean is this: > foo = re.compile("someregexcode") > bar = re.compile("moreregexcode") > > big = re.compile("foo|bar") > > is that possible at all? To combine regular expression objects? Or do you > suggest that I just make strings for foo and bar, and then compile the > combined strings into big? It seems to me you need to explain whether you want them concatenated (in which case can't you just join the pattern strings?), or ORed together (similar to the foo|bar case you give above?), or "nested" (which to me implies some kind of hierarchy) or maybe just applied sequentially (in which case just do that?). -Peter From vincent_a_primavera at netzero.net Thu Mar 28 07:17:57 2002 From: vincent_a_primavera at netzero.net (Vincent A. Primavera) Date: 28 Mar 2002 12:17:57 +0000 Subject: Weave... Message-ID: <1017317878.24011.19.camel@del-vap-bos.ralphpill.com> Hello, Does anyone know where I can find Weave which used to be located at the address below(or any good alternatives...)? Thank you, Vincent A. Primavera http://www.scipy.org/site_content/weave From gmcm at hypernet.com Sun Mar 10 10:08:14 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 10 Mar 2002 15:08:14 GMT Subject: Standalone Win32 wxPython apps? References: Message-ID: Grant Edwards wrote: > I'm considering writing a wxWindows app for Win32. [snip] > In order for it to be useful, I'll need to be able to > distribute it as a stand-alone app to users who don't have (or > care to have) a regular Python or wxWindows distro installed. > > Optimally, it would be a single "exe" file that doesn't require > any installation procedure. If that's not possible, it would > be permissible to use a typical "isntall-wizard" type > installation: running the exe installs the required files > somewhere, adds a start-menu entry, leaves an un-installer > around. > > It looks like Gordon McMillan's installer might fit the bill. > > Anybody care to share any experiences distributing wxWindows > apps for Win32? Installer can do a single exe or a single directory. Unless your users are only going to run it once or twice, I'd use single directory (with wxPython it will just take too long to load as a single file). Inno is a free GUI installer you can use: http://www.jrsoftware.org/ (I recently ran across another free one that claims to be lighter weight, but I guess I didn't bookmark it :-(). -- Gordon http://www.mcmillan-inc.com/ From martin.franklin at westerngeco.com Thu Mar 7 05:45:28 2002 From: martin.franklin at westerngeco.com (Martin Franklin) Date: Thu, 07 Mar 2002 10:45:28 +0000 Subject: Python Classes References: <2030665d.0203070226.46b39af4@posting.google.com> Message-ID: Sam Collett wrote: > I am quite new to Python and have no experience with classes. I have > tried a file class, but I am not sure how to get it to work: > > class clFile(file): > > def getFileName(blnExt=None): > """ > file = path to file > blnExt = show file extension (put in value other than 0 or > None to show the extension) > """ > import os > if blnExt: > result = os.path.basename(file) > else: > result = os.path.splitext(os.path.basename(file))[0] > del os > return result > > def getFileExt(): > import os.path > result = os.path.splitext(file)[1] > del os > return result > > def getDir(): > import os > result = os.path.dirname(file) > del os > return result > > I wondered if there was a way to do something like the following: > > myfile = clFile("c:\\somedir\\dir with spaces\\foo.txt") > myfile.getDir would return c:\somedir\dir with spaces\ > myfile.getFileExt would return .txt > myfile.getFileName would return foo.txt or foo Ok try this to get you working: import os # do this at the top.... class clFile: def __init__(self, file): # constructor called when you create an instance (object) of this class self.file=file # self.file instance variable bound to file object #(in this case the file name passed to the class constructor) def getFileName(self, blnExt=None): # return filename with or without the extension.. if blnExt: result = os.path.basename(self.file) else: result = os.path.splitext(os.path.basename(self.file))[0] return result def getFileExt(self): # return file extension return os.path.splitext(self.file)[1] def getDir(self): # return the file basname (directory/folder) return os.path.dirname(self.file) # now for testing..... if __name__=='__main__': clf=clFile('/home/bpse/crapola.bot') # create an instance of clFile # call it's methods.... print clf.getFileExt() print clf.getFileName(blnExt=1) print clf.getFileName() print clf.getDir() You should really work your way through the tutorial (at least the classes bit) on:- http://www.python.org/doc/current/tut/tut.html From cjw at sympatico.ca Mon Mar 25 08:03:16 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 25 Mar 2002 08:03:16 -0500 Subject: struct - Library Reference 4.3 References: <3C9CC1BB.A6C8A9C8@sympatico.ca> Message-ID: <3C9F2014.7D3E77B0@sympatico.ca> Martin, Thanks, I did not spot this. I was looking for some clue as to which argument is causing the exception. As an example: import exceptions, sys try: print `struct.pack('iii', 22, 22.6, '23.6')` except struct.error: print 'z1:', struct.error().args print 'z2:', sys.exc_info()[1] print 'z3:', sys.exc_info()[1].__getitem__(0) Neither 22.6 or '23.6' is an integer, but it seems that '23.6' is the source of the problem. Various things I've tried don't identify the specific value. Colin W. "Martin v. Loewis" wrote: > "Colin J. Williams" writes: > > > This gives no indication as to which of the argument's > > components is the source of the grief. > > > > Any information about the error function would be > > appreciated. > > It's not a function - it is an exception. If you want to catch the > exception, you need to write a try-except-block. > > The exception does not provide any further information beyond the > string that is printed - it is assumed that the nature of the error > would be obvious once you read the string. > > Regards, > Martin From tim.one at comcast.net Sun Mar 10 13:31:38 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 10 Mar 2002 13:31:38 -0500 Subject: round() function strange behaviour In-Reply-To: <3c8b8112.27836128@news> Message-ID: [brobbins333 at shaw.ca] > OK, that makes perfect sense. In my case, I was simply looking for a > predictable way to return a number with two decimal places -- knowing > that it will be an approximation of Python's approximation. Obviously, > using round() is not the way to go about this. I'll figure it out. round() is the best way to go about this, provided you're going to stick with using Python floats. Grant Edwards explained why: most decimal numbers aren't exactly representable as floats, and round(x, 2) generally delivers a float y such that y is approximately equal to x and such that y*100 is as close to being an exact integer as is (even theoretically) possible. If you want exact decimal numbers, you can't use floats at all. In a parallel thread, Aahz announced that he put up my old FixedPoint class (thanks, Aahz!): http://starship.python.net/crew/aahz/FixedPoint.py That simulates exact decimal arithmetic. at-high-cost-but-so-it-goes-ly y'rs - tim From jeff at ccvcorp.com Thu Mar 21 17:20:03 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 21 Mar 2002 14:20:03 -0800 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: <3C9A5C93.4DF63794@ccvcorp.com> "Martin v. L?wis" wrote: > "Thomas Heller" writes: > > > Problems with freeze, IMO, are that it requires a C-compiler, > > which most people on windows do not have... > > In the context of distutils, absence of a compiler may not be a > problem: people building packages with distutils will need a compiler, > atleast if the package contains extension modules. Yes, but it is entirely possible that someone may be building a pure Python application, and wish to distribute that as a single file. It would be desirable (though probably not essential) to require a C compiler only in those cases where custom C extension modules are used. For instance, I'm working on an application that uses wxPython and win32all, but all of my own code is pure Python. It's an internal utility, so ease-of-packaging isn't a big priority (it's not too big of a deal for me to install ActivePython + wxPython + my own bdist_wininst package on each of the half-dozen machines that will need it), but I can easily imagine a case in which it would be preferable to have a single-file installer that would manage all of this automatically. Jeff Shannon Technician/Programmer Credit International From db3l at fitlinxx.com Sat Mar 2 00:33:20 2002 From: db3l at fitlinxx.com (David Bolen) Date: 02 Mar 2002 00:33:20 -0500 Subject: Older Python bug entries on SourceForge References: Message-ID: martin at v.loewis.de (Martin v. Loewis) writes: > So if you have a bug number below 300000, SF will have > renumbered the bug by now. They used to have a backwards-compatible > URL in place, redirecting to the new report, but they may have > disabled that by now. Is there any way to compute the new number based on the old (e.g., by adding some fixed constant or something)? -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From rasmussn at lanl.gov Tue Mar 12 13:53:32 2002 From: rasmussn at lanl.gov (rasmussn at lanl.gov) Date: Tue, 12 Mar 2002 11:53:32 -0700 Subject: Scripting C++ -- 2 -- a more concrete example. In-Reply-To: <6bf54244.0203010925.38d237ed@posting.google.com> Message-ID: <72EE8C52-35EA-11D6-AB89-0030657EBC3E@lanl.gov> On Friday, March 1, 2002, at 10:25 AM, Craig Maloney wrote: > Donovan Rebbechi wrote in message > news:... >> In article <3C7E6642.2030202 at physics.ucsb.edu>, Craig Maloney wrote: >>> If using a wrapper generator (e.g. SILOON) I don't see a way around the >>> marshalling of the call to get at the atom data structure. >> >> I don't really understand exactly what the problem is. >>> >>> Of course, this would be taken care of by a revamp of the design of the >>> class library... maybe making the crystal an atom factory that produces >>> new atoms in its own address space. But I would like to avoid thinking >> >> Now I'm really confused. If you're not using CORBA, the atoms are in the >> same address space, aren't they ? > > This is how I presumed that Boost also worked -- I must be mistaken. > After having seen yours and Ralf's comments, I now have the impression > that Boost works it's magic differently. > > Perhaps Craig Rasmussen could enlighten us as to how SILOON deals with > co-location issues such as the one above? I was at a conference on software testing last week and so I'm late responding. If I understand the issue correctly, the question is "can I access a C struct or class directly in Python within providing accessor methods" With Siloon you can't, as the design philosophy was to keep all data on the server/compute engine unless explicitly provided through some interface. This was done because in high performance computing, our data structures (e.g., arrays) can be really really big and would swamp Python. But a python extension (wrapper) could be generated which would copy data directly from a C struct into a Python class. This would involve a series of function calls (via Py_BuildValue, for example) to copy the data to Python land, which I view as a form of marshaling. So I don't see any way to use C++ data in Python without function calls and data marshaling. Regards, Craig From abou at cam.org Sun Mar 31 11:24:06 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Sun, 31 Mar 2002 11:24:06 -0500 Subject: seek() References: <3CA6AD4D.C552BDDA@engcorp.com> <3CA72FF2.6B5681F0@cam.org> Message-ID: <3CA73826.8B8EFEFC@cam.org> Zutroi Zatatakowski wrote: > # Now I have the source in a file. No problems here. > # This finds the byte where 'Gold' starts. I know that Gold's value is > found 8 # bytes later. > > longstr = c.read() > print string.find(longstr, 'Gold') > # Is it possible to have the output of string.find() converted to a > string, or even # better, to an int? If I can get the location of 'Gold' > into an int, it would be # easy to do: Ok, I fixed my problem, was kinda easy, I just didn't think about it: c.seek(string.find(longstr, 'Gold')) print c.read(10) -- Zutroi Zatatakowski Commando PACU http://pacu.cjb.net From martin at v.loewis.de Wed Mar 27 07:03:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Mar 2002 13:03:47 +0100 Subject: Encoding when building XML via minidom? (...beginner needs advice) References: Message-ID: "Petr Prikryl" writes: > Briefly: I want to parse txt files with some internal structure > and convert them into well-formed XML internal format > (custom markup). I do not know how to deal with > windows-1250 input encoding and how to produce > the XML output with the same encoding. People have varying opinions about that, but I would recommend to *not* use the DOM for generating XML files from scratch. Instead, plain print statements might work just fine. > I probably need some advice for what is the best way to create my > own parser Writing a parser is always tricky, and what the best approach is depends on the input language. In any case, it seems that this is mostly unrelated to XML, yet - if you get a parser working, it should be straight forward to build a DOM structure from it, if you wish to. If you really care, you could try to produce a SAX reader: an object that emits SAX events. In your case, it would not read XML, but it still could emit SAX events as if it would read XML. With that, you could pass your reader to xml.dom.minidom.parse, and it would build a DOM tree right away. This is quite involved, though, and likely more complicated than necessary. > This is somewhat tricky with minidom: the toxml method with always assume UTF-8 output. You can use a StreamWriter for windows-1252, and you will need to write the XML header separately. > Are there some tutorials on how to work with encoding conversions? You really need to familiarize yourself with the Unicode support first; see http://www.python.org/doc/current/lib/module-codecs.html > (Python's DOM works with Unicode internally, doesn't it?) In principle, yes. It won't complain if you pass byte strings, but you may face troubles later on if you do. > Are there some means to make writing the plain text with indentation > easier, in Python? Yes, you can use the multiplication of strings: print " "*indent+text HTH, Martin From thoa0025 at mail.usyd.edu.au Wed Mar 27 14:59:38 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Wed, 27 Mar 2002 19:59:38 GMT Subject: mutliple search and replace Message-ID: Greetings, Suppose i have a map (or two lists). is it possible to make a sweep through a string to find all occurances of key's in the map then replace them all in one sweep? cheers trung From s.ernst at web.de Fri Mar 15 08:14:09 2002 From: s.ernst at web.de (Sascha Ernst) Date: Fri, 15 Mar 2002 14:14:09 +0100 Subject: problems with compiling python on osx References: Message-ID: 1. "command not found" is the error message. how can I get more detailed infos? 2. the dev tools are ok, I compiled Ruby some days ago successfully regards, sascha "Just van Rossum" schrieb im Newsbeitrag news:just-226E14.13535315032002 at news1.xs4all.nl... > In article , > "Sascha Ernst" wrote: > > > I've downloaded the newest python sources and tried to run ./configure. I'm > > within the right directory, the shell is located correctly, all > > read/write/execute-rights are set, but even as a root I get the > > error-message "command not found!". is there anything I forgot? > > 1) specific error message please... > 2) do you have the proper dev tools installed? > > Just From lenny.self at attbi.com Fri Mar 8 17:34:01 2002 From: lenny.self at attbi.com (Lenny Self) Date: Fri, 08 Mar 2002 22:34:01 GMT Subject: List of Dictionaries References: <14dc40e2.0203071559.5e3d4550@posting.google.com> <3C88186F.6BEFA3D2@alcyone.com> Message-ID: Thanks for your help. When I return a copy of the dictionary from the MailData class everything seems to work. This is still a little bit odd considering each time I access MailData it should be using a new instance and thus my the dictionary in each instance should be completely different. Odd. Anyway, thanks again. -- Lenny From eppstein at ics.uci.edu Fri Mar 1 20:50:58 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 17:50:58 -0800 Subject: Status of PEP's? References: <3C802175.A527BFA0@ccvcorp.com> <76c08ukou81p7lfnnoiftfhaf5v66amglm@4ax.com> Message-ID: In article <76c08ukou81p7lfnnoiftfhaf5v66amglm at 4ax.com>, Courageous wrote: > At least we dont have for (exp-list;expr-listl;expr-list): > > That's nasty, imo. I think a lot of us can agree on that. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From aahz at panix.com Sun Mar 3 15:55:36 2002 From: aahz at panix.com (Aahz Maruch) Date: 3 Mar 2002 12:55:36 -0800 Subject: C++, Python & Threads References: <1015181073.276455@seux119> Message-ID: In article <1015181073.276455 at seux119>, VUG wrote: > >Hi all. I'm modifying Python source code in order to have more control over >threads (I need to kill threads without adding controls on them, and it >seems not to be posible). You really don't want to do that. If you kill a thread externally, you can leave your entire process in a bad state. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From robin at jessikat.fsnet.co.uk Wed Mar 13 10:57:12 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 13 Mar 2002 15:57:12 +0000 Subject: cgi xmlrpc anyone? Message-ID: Has anyone got a cgi version of an xmlrpc server? By that I mean a cgi script which simulates being an xmlrpc server. We are allowed to do cgi by our ISP, but not to run long running processes or to start up our own servers etc. -- Robin Becker From mlh at vier.idi.ntnu.no Mon Mar 18 16:48:33 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 18 Mar 2002 21:48:33 +0000 (UTC) Subject: Adding static typing to Python References: <0DFA7478F1E5D311B90900508B1208CF565714@ausmail02.mis.gtech.com> Message-ID: In article , Nick wrote: >"Brendan Hahn" wrote in message >news:bhahn-ya02408000R0403021410080001 at news.corp.hp.com... >> Courageous wrote: >> >One of the things I like about C sharp is their use of attributes, >> >where you can define getters and setters on an attribute, but >> >otherwise the attribute is simply used as if it were a public one. >> >> Eiffel does this. It was one of the first things to make me say "Cool!" >> when I started looking into it. >> >> bhahn at transoft.mmangle.net <-- unmangle address to reply > >Object Pascal does that as well. > > Python too (as of 2.2). -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From phr-n2002a at nightsong.com Fri Mar 15 08:38:46 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 15 Mar 2002 05:38:46 -0800 Subject: line-by-line file read References: Message-ID: <7xhenix861.fsf@ruckus.brouhaha.com> Michael Stenner writes: > I often find myself reading and processing a file line-by-line. The > way I usually end up doing it goes something like this > > fo = open(filename) > line = fo.readline() > while line: > # do the processing on "line" here > line = fo.readline() > fo.close() > ... > Anyway... just wondering if there's a preferred way to do this. fo = open(filename) for line in fo.xreadlines(): # process the line fo.close() From peter at engcorp.com Sun Mar 31 11:09:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 11:09:50 -0500 Subject: Possible to save router logs? References: Message-ID: <3CA734CE.7A76AF18@engcorp.com> Paul wrote: > > I have a D-Link 704 cable/DSL router. Unfortunately, it has very > limited logging capabilities(in that it doesn't save logs, it just > rights over them when the space fills.) What I would like to do is > right a program to save the logs to my hard drive every 12 hours or > so. I normally have to access the web page with the url being the > local IP of the router, then type in a password to get access to the > logs. Has anyone attempted something like this? I know this is kinda > general, but any feedback would be appreciated. It might give me an > idea of where to begin. Thank you. Use urllib? Where do you enter the password? In a pop-up dialog box, or in a form on-screen? From fredrik at pythonware.com Sat Mar 9 12:17:13 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 09 Mar 2002 17:17:13 GMT Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> Message-ID: Edward K. Ream wrote: > Dynamic tracing is trivial to implement. More importantly, it is > simpler to use and more flexible than any static scheme such as the one > described in 282. except that in real systems, the end user couldn't care less about what/when/how your Python functions are called. they do care about syslog-compatibility, severity levels, and trivial things like getting the same logging messages also after you've refactored your program... From logstx at bellatlantic.net Fri Mar 29 16:10:36 2002 From: logstx at bellatlantic.net (logistix) Date: Fri, 29 Mar 2002 21:10:36 GMT Subject: Win32 Impersonation References: Message-ID: You need to have the "Act as part of the Operating System" local security policy set. I'm don't think that even the administrator has this permission set by default. I've been using 2000 lately, but I beleive the way to check/set this in NT is Start-> Administrative Tools ->User Manager. If you're on a server you'll need to set the domain to the server name, this will happen automatically on a workstation. One of the menu options somewhere in there is Policies. -- - "Giganews" wrote in message news:kJRo8.462443$pN4.32187350 at bin8.nnrp.aus1.giganews.com... > Hey all, > > I'm a newbie with Python, and I have been looking for a way to run a script > as the administrator on Windows NT. I have the user name and password, and > some code to do the impersonation, but when I try to use it, I receive a > sort of access denied message. Upon reading the ActivePython docs, I found > that the user who runs the impersonation script needs SE_TCB_NAME, > SE_CHANGE_NOTIFY_NAME, and SE_ASSIGNPRIMARYTOKEN_NAME priveleges. > > Maybe I'm missing the point here, but the only two accounts on these systems > with these priveleges are the administrator and the local system account. > Obviously, if I already were the administrator I wouldn't have this problem. > I think I'm missing something. > > Anyway, here is the template of the code that I'm having problems with: > > admin=win32security.LogonUser('administrator_account','domain','password') > > win32security.ImpersonateLoggedOnUser(admin) > > > Has anyone gotten this to work on their systems, if so please help me! Is > there another way? > Any help would be greatly appreciated, > > Pablo Manzanera > > From news at charneyday.com Tue Mar 5 12:29:30 2002 From: news at charneyday.com (Reginald B. Charney) Date: Tue, 05 Mar 2002 17:29:30 GMT Subject: Order of constructor/destructor invocation References: <3C8466F9.2080903@jerf.org> Message-ID: <_f7h8.5541$aP6.6480@rwcrnsc54> In this idiom, I am not trying to traverse a tree. I am trying to execute what I declare. Also, this idiom allows for very shallow dependencies. There is no inheritance here. In this example, I am trying to write: h = HTML(); b = BODY(); p = PHP() Note that there is no interdependencies. I could also have written (but is would produce invalid HTML): b = BODY(); p = PHP(); h = HTML() However, it is pretty clear what I have written and the order I expect things to be done. Please compare it with the more classic example you wrote where the logical ordering needed to be explicitly coded for the right results to be produced. Using this idiom, here is what my __main__ would look like: if __name__ == "__main__": print "Start of program" h = HTML() b = BODY() p = PHP() ... Thanks. Reg. "Jeremy Bowers" wrote in message news:3C8466F9.2080903 at jerf.org... > Reginald B. Charney wrote: > > > In Python, are destructors defined to be invoked in reverse order of > > constructors? The following program illustrates the problem: > > > > class HTML: > > def __init__(self): print "" > > def __del__(self): print "" > > > > class BODY: > > def __init__(self): print "" > > def __del__(self): print "" > > > > class PHP: > > def __init__(self): print " > def __del__(self): print "?>" > > > You aren't trying to actually build an HTML document that way, are you? > Please tell me this is just for the sake of example. The more > conventional example would be something like > > class example: > def __init__(self): print "example created" > def __del__ (self): print "examples destroyed" > > Destructors are for cleaning up objects, not traversing trees. If you > really are trying to build HTML documents, learn how to traverse trees > correctly. > > > ---- > import string > > class HTMLTag: > def __init__(self): > self.children = [] > def output(self): > childText = [child.output() for child in self.children] > return string.join([self.begin] + childText + [self.end]) > > class HTML(HTMLTag): > begin = "" > end = "" > > class BODY(HTMLTag): > begin = "" > end = "" > > class PHP(HTMLTag): # OK, so that's a bit of a semantic stretch... > begin = " end = "?>" > > if __name__ == "__main__": > print "Start of program" > h = HTML() > h.children.append(BODY()) > h.children[0].children.append(PHP()) > print h.output() > ---- > > > This isn't the One True Implementation of this idea, just a nudge. > From marijn at sanity.dhs.org Fri Mar 1 09:48:29 2002 From: marijn at sanity.dhs.org (marijn Vriens) Date: 1 Mar 2002 06:48:29 -0800 Subject: gnome.ui is doing scary things.... Message-ID: <29575ad6.0203010648.3c2ec3d8@posting.google.com> Anybody know what is going on here?: Python 2.1.2 (#1, Jan 18 2002, 18:05:45) [GCC 2.95.4 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> t = 10.5 >>> print t 10.5 >>> import gnome.ui >>> t = 10.5 >>> print t 10.0 >>> And how I can make it to stop doing this? IMHO this _VERY_ evil behavure, thank god I had unittests to catch it! Now how do I fix it? Ohh, and by the way my version of python-gnome is 1.4.1-17 in debian-woody. Thanks, Marijn. From just at xs4all.nl Fri Mar 15 07:53:53 2002 From: just at xs4all.nl (Just van Rossum) Date: Fri, 15 Mar 2002 13:53:53 +0100 Subject: problems with compiling python on osx References: Message-ID: In article , "Sascha Ernst" wrote: > I've downloaded the newest python sources and tried to run ./configure. I'm > within the right directory, the shell is located correctly, all > read/write/execute-rights are set, but even as a root I get the > error-message "command not found!". is there anything I forgot? 1) specific error message please... 2) do you have the proper dev tools installed? Just From sholden at holdenweb.com Tue Mar 26 15:03:36 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 26 Mar 2002 15:03:36 -0500 Subject: Root access with python References: <7x663krjtp.fsf@ruckus.brouhaha.com> <20020325123855.A1716@ibook.distro.conectiva> Message-ID: "Andy Gimblett" wrote in message news:mailman.1017071438.28406.python-list at python.org... > On Mon, Mar 25, 2002 at 12:38:55PM -0300, Gustavo Niemeyer wrote: > > > You have several options to do this, and all of them involve setting the > > setuid bit in some executable. OTOH, setting setuid bit on scripts > > usually doesn't work. If that's your case, you'll have to freeze your > > script into a native executable, or build some kind of wrapper. Google > > for "setuid bit scripts" for more information. > > As a general solution to this kind of problem, sudo is excellent, > though it might be overkill for this particular case. > The problem is that sudo also required you to authenticate yourself periodically, albeit as an ordinary user rather than root. I suppose there may be an option to not require authentication, but any such device is theoretically dangerous. As far as setuid scripts goes, just say no. There are far too many security holes in almost every Unix to think that it's safe to use setuid scripts. regards Steve From xtian at toysinabag.com Wed Mar 27 01:14:05 2002 From: xtian at toysinabag.com (xtian) Date: 26 Mar 2002 22:14:05 -0800 Subject: list of empty lists References: <3CA11A5B.5000501@bioeng.ucsd.edu> Message-ID: Curtis Jensen wrote in message news:<3CA11A5B.5000501 at bioeng.ucsd.edu>... > Is there a easy way to make a list of an arbitray number of empty lists? > > In this case, what I would like is three independantly empty lists. I > can make a for loop to loop "some_number" of times and append an empty > list at each itteration. Is there a simpler way? > Thanks. Another way to avoid the shared inner list would be >>> l = [[] for i in range(3)] >>> l [[], [], []] >>> l[0].append(1) >>> l [[1], [], []] The empty list is evaluated for each element in the source list. (This is effectively the same as the for loop option, in that they both introduce a counter variable.) HTH xtian how nuch do I love ninjas? let me count the ways: 1, 2, 3, 4, 5 From michael+usenet at dynamine.net Fri Mar 29 16:31:29 2002 From: michael+usenet at dynamine.net (Michael S. Fischer) Date: Fri, 29 Mar 2002 21:31:29 -0000 Subject: IOError on file close Message-ID: Greetings, Can anyone tell me why this is happening? (Python 2.1.2 on Debian Linux) >>> fp = open("/proc/scsi/scsi","w") >>> fp.write("scsi add-single-device 0 0 1 0\n") >>> fp.close() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 38] Function not implemented >>> fp >>> fp.close() >>> Thanks, -- Michael S. Fischer / michael at dynamine.net / +1 650-533-4684 Lead Hacketeer, Dynamine Consulting, Silicon Valley, CA From owen_stevens at hotmail.com Tue Mar 12 12:16:09 2002 From: owen_stevens at hotmail.com (Owen Stevens) Date: 12 Mar 2002 09:16:09 -0800 Subject: new to python - please help Message-ID: <9e629c01.0203120916.7eab41eb@posting.google.com> I made a dictionary with the following structure: From tejarex at yahoo.com Fri Mar 8 09:28:24 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 08 Mar 2002 14:28:24 GMT Subject: Order of constructor/destructor invocation References: Message-ID: "Reginald B. Charney" wrote in message news:wI%h8.2623$ZR2.2434 at rwcrnsc52.ops.asp.att.net... > Believe it or not, I was not trying to start a religious war. I was trying > to use a well-defined approach in one language to another language that I > thought was similar enough in structure to work in the same way. As you have discovered, the Python interpreter does record the order of object creation. So do it yourself with a stack. Start with (untested) class Finalize: #this would be even simpler in 2.2 with Finalize(class) def __init__(self): self.stack = [] def __del__(self): self.stack.reverse() for pending in self.stack: pending.finalize() Push = Finalize().stack.append Now add Push(self) to the end of initializers that need a corresponding finalizer and rename your finalizer methods 'finalize' instead of '__del__'. Now all the cleanup is invoked in the proper order when the program ends. Terry J. Reedy From amckay at merlinsoftech.com Mon Mar 25 17:42:02 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Mon, 25 Mar 2002 14:42:02 -0800 Subject: Doing a ps in windows.. (Is application XYZZY running?) In-Reply-To: References: Message-ID: <200203252240.g2PMeNq17540@mail.merlinsoftech.com> Apart from using win32api you could install two tiny executables: http://www.microsoft.com/windows2000/techinfo/reskit/tools/existing/pulist-o.asp and one of the many versions of grep out there: http://www.google.ca/search?hl=en&q=grep+windows&meta= On March 25, 2002 12:54 pm, Andrew Markebo wrote: > *blush* yeah I know.. not really.. here, only almost :-) > > I have the windows-compiled python 2.2, and I would like to see if > Opera or Netscape is running on my computer (poor sod, running Win2k, > XP or 98).. How do I do this, I suppose I could use something in the > win32api, but what is something.. :-) ?? > > On unix I do "ps -ef | grep netscape" ;-) > > /Andy -- Andy McKay From landshark at verticaladdiction.net Fri Mar 1 11:37:22 2002 From: landshark at verticaladdiction.net (Dave Marotti) Date: Fri, 01 Mar 2002 16:37:22 -0000 Subject: what does this do? (really basic question) References: Message-ID: Daniel / Sean, Thanks for the great explaination and the links. I wasn't sure what to think of the syntax. I haden't seen the use of asterisks before in python code, and my background in C/C++ instantly made me think of pointers. I couldn't have been further from the truth. -dave >"kw" stands for "keyword", and what's being used is called a "keyword >argument". Keyword arguments allow us to pass parameters to a >function in a very general way. In the example above, the keyword >argument becomes a dictionary that captures any keyword variables that >"fall through the cracks" of a function call. -- +-----------------------------+----------------------------------------------+ | Dave Marotti | Looking for a Visio alternative for *nix? | | lndshark ! speakeasy net | Kivio : http://thekompany.com/projects/kivio | +-----------------------------+----------------------------------------------+ | I just don't trust anything | I suppose that in a few more hours I will | | that bleeds for 5 days and | sober up. That's such a sad thought. I think | | doesn't die. - Mr. Garrison | I'll have a few more drinks to prepare myself| +-----------------------------+----------------------------------------------+ From maxm at mxm.dk Wed Mar 13 06:44:20 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 11:44:20 +0000 Subject: Converting relative URLs to absolute References: <23891c90.0203130331.6f030f5b@posting.google.com> Message-ID: <3C8F3B94.1020409@mxm.dk> Paul Boddie wrote: > I've written some page-mining tools which help with these kinds of > activities, and I suppose I should get round to releasing them at some > point. Let me know if you're interested! Actually urllib needs those kinds of "smart" url joining. The ones that are in there now are next to useless. So perhaps you could get it added to the urllib instead? regards Max M From philh at comuno.freeserve.co.uk Thu Mar 28 19:43:54 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 29 Mar 2002 00:43:54 +0000 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> <3CA3768B.32BB6AC9@ccvcorp.com> Message-ID: On Thu, 28 Mar 2002 12:01:15 -0800, Jeff Shannon wrote: > > >phil hunt wrote: > >> IIRC in Awk you can just say: freq[word] ++ and it works >> correctly even when there is no pre-existing index of word in freq. >> >> IMO it's a pity Python isn't like that. > >I disagree. I'm just as happy that Python doesn't try to guess what would be a >suitable "default" value for non-existent keys. The default value should always be None. None should act like 0 or "" or [] or {} where appropriate, i.e.: None + 1 --> 1 None + "x" --> "x" None * 4 --> 0 None + ['x'] --> ['x'] None + {2:3} --> {2:3} etc. (Note I am implying here that + should work with dictionaries, i.e. {2:3} + {4:5} --> {2:3, 4:5}) >It seems to me to be entirely >consistent with the philosophy of "explicit is better than implicit". But that isn't the philosophy of any high level langauge. In fact, the more high level any language is, the more implicit things are. And I would argue that's a pretty good definition of what a high level language is. > Why >presume that somedict[key] should default to 0, instead of to an empty string, >or to None, or to [], or... ??? See above -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From bergeston at yahoo.fr Mon Mar 11 08:02:40 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Mon, 11 Mar 2002 14:02:40 +0100 Subject: newbie needs help with tkinter References: <1Myi8.13667$%d1.409160@twister2.libero.it> Message-ID: And you can even comment the line: self.update_idletasks() it works as well ! "Bertrand Geston" wrote in message news:a6i9p3$eip6d$1 at ID-135695.news.dfncis.de... > Beeing newbie myself, I played with you code, here is the result: > > ----------------------------------------------------------- > from Tkinter import * > > class Application(Frame): > def __init__(self,master=None): > Frame.__init__(self,master) > menubar=self.addmenubar() > master.config(menu=menubar) > w=Label(self,fg="green",text="*") > self.pack() > w.grid() > > def addmenubar(self): > menubar=Menu() > filemenu=Menu(menubar) > menubar.add_cascade(menu=filemenu,label="File") > filemenu.add_command(label="Configura", command=self.configframe) > filemenu.add_command(label="Lavora") > return menubar > > def configframe(self): > self.config(bg="yellow") > w=Label(self,fg="blue",text="prova") > w.grid() > self.update_idletasks() > print "hello!" > > #main > > root=Tk() > applicazione=Application(root) > root.mainloop() > > ----------------------------------------------------------- > > "Sacchi" wrote in message > news:1Myi8.13667$%d1.409160 at twister2.libero.it... > > I've just learned the main rules of python(I already knew both java and > > C). Now I'm trying to get something out of Tkinter, but while running > > this sample program (made by myself) I encountered a problem. I wanted > > that by clicking on the "configura" command under the "File" menu the > > frame would get yellow and that a label would appear on it. The > > function works(the line "print "hello!"" gets executed) but the gui > > window doesn't change. I even tried to use the widget redraw methods > > but with no success... anyone can help me please? > > > > Thanks in advance > > Marco > > > > --------- Program Code ---------------------- > > > > from Tkinter import * > > > > class Application(Frame): > > > > def __init__(self,master=None): > > Frame.__init__(self,master) > > menubar=self.addmenubar() > > master.config(menu=menubar) > > menubar.mainloop() > > > > def addmenubar(self): > > menubar=Menu() > > filemenu=Menu(menubar) > > menubar.add_cascade(menu=filemenu,label="File") > > #these lines got shifted by the newsreader program, but all belong to > > #the addmenubar function > > filemenu.add_command(label="Configura"command=self.configframe) > > filemenu.add_command(label="Lavora") > > return menubar > > > > def configframe(self): > > self.set(bg="yellow") > > w=Label(self,fg="blue",text="prova") > > w.grid() > > self.update_idletasks() > > print "hello!" > > > > #main > > > > root=Tk() > > applicazione=Application(root) > > root.mainloop() > > -- > > ----------------------------------------------------- > > remove "nospam" from email address to answer > > ----------------------------------------------------- > > From jwbaxter at spamcop.net Wed Mar 6 22:58:34 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Wed, 06 Mar 2002 19:58:34 -0800 Subject: The language vs. the environment References: Message-ID: In article , Skip Montanaro wrote: > There has been a huge amount of recent PEP activity related to further > enhancements to the language. I think in general that if more of this > energy was directed at the overall environment (library, support tools, > installers, documentation, etc) we'd be better off in the long run. Thanks, Skip! More and more often, I look at a language-domain proposal, and think: 1. that might be nice...it makes good sense 2. do we need to tinker with the language that way? 3. probably not PEP 284 triggered that sequence, and hasn't yet triggered the next step: 4. well OK, probably this one is justified. I used 284 just as an example, not to pick on it. --John From usenet at thinkspot.net Sat Mar 9 14:38:33 2002 From: usenet at thinkspot.net (Sheila King) Date: Sat, 09 Mar 2002 11:38:33 -0800 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> Message-ID: On 9 Mar 2002 08:40:50 -0800, morton at dennisinter.com (damien morton) wrote in comp.lang.python in article <4abd9ce7.0203090840.21a020eb at posting.google.com>: > Its counter-intuitive for someone playing with strings as strings > rather than as sequences of characters, however. > > 'c' in 'the quick brown fox' -> 1 > > 'fox' in 'the quick brown fox' -> 1 (instead of TypeError) > > Is there any circumstance where youd expect (or want) the later not to > work? I expected and wanted it to work (but instead got an error), its > quite a clear and unambiguous expression (for strings only). Suppose word = 'fox' container = 'the quick brown fox' What if the type of container is not necessarily known. i.e. it is possible that container could be something like: container = ['the', 'quick', 'brown', 'fox'] And suppose the type were important in this case, as to whether it were a single string vs. a list of words. As it is now, you are able to make this distinction, whereas with what you propose that distinction would be lost. I can't come up right now with a practical example of why this would be important or useful, though. Anyhow, if you have a string, as shown above, and you want to test for a word in the string (rather than using the .find method for strings) you could do this: word in string.split(container) this would split the string container on any and all white spaces into just the word elements. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From paul at prescod.net Sun Mar 31 11:01:29 2002 From: paul at prescod.net (Paul Prescod) Date: Sun, 31 Mar 2002 08:01:29 -0800 Subject: PEP 285: Adding a bool type References: <000f01c1f0a4$9f176d60$0334fea9@carol> Message-ID: <3CA732D9.BA7E963D@prescod.net> Arthur Siegel wrote: > >... > > If I am concerned about the readability of my code > for other non-experts (and I usually am), I might > do a: > > True = 1 > False = 0 > > at a modules head and go from there. > > I am not understanding what beyond that the > Boolean type accomplishes. > > It would perhaps not detract from the debate > if the upside could be explained in terms that > spoke to the practicalities of writing workable > and readable code in Python, rather than in > terms of language design theory and > implementation internals. One way to sum it up is "if that's a good convention for readability then why not make it a built-in concept in the language so that we do not all invent our own spellings for it?" Having bool be separate from integer is useful for introspection. For instance if you pass a "1" to Jython, COM or SOAP, it is hard for Jython or the Python COM bindings or ZSI to know whether you meant to pass an integer or a boolean. In the worse case this can mean you call the wrong overloaded method. Even in pure python it may occasionally (very occasionally) be useful to write code of the form: "if the first argument is a boolean then do X, else if it is an integer do Y." Finally, booleans can have different displays so that: print "isWindowMaximized:", isWindowMaximized will print "True", rather than "1". The former is a little clearer. Paul Prescod From jim.vickroy at noaa.gov Wed Mar 6 15:50:22 2002 From: jim.vickroy at noaa.gov (j vickroy) Date: Wed, 6 Mar 2002 13:50:22 -0700 Subject: (10093, 'Successful WSAStartup() not yet performed') ? Message-ID: I'm using Python 2.2 on a Win 2k machine. My socket script is generating the following error: (10004, 'Interrupted system call') Thereafter, the following error is generated until the script is stopped: (10093, 'Successful WSAStartup() not yet performed') Could someone shed some light on this? Here is the code snippet: > >#---------------------------------------- >class Interface(goes12_sxi.announcement.Publisher): > > def __init__(self): > self.name = 'pre-processor interface' > self.host = generic.IPC.Visible_Local_Socket_Host_Name() > self.port = Socket_Port() > self.stop_signal = threading.Event() > self.server_socket = generic.IPC.socket_listener(self.port) > > def _receive_messages(self): > > journal.put(goes12_sxi.journal.Note(self, 'started')) > > while not self.stop_signal.isSet(): > > try: > # the following statement is causing the exception ############### > transmitter = self.server_socket.accept() # blocks till something arrives > ..... > except Exception, details: > ..... >#---------------------------------------- > From gcordova at hebmex.com Wed Mar 27 16:11:47 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 27 Mar 2002 15:11:47 -0600 Subject: mutliple search and replace Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689EB@SRM201002> > > Greetings, > > Suppose i have a map (or two lists). is it possible to make a > sweep through > a string to find all occurances of key's in the map then > replace them all in > one sweep? > > cheers > trung > Sure, only that there's not a builtin function that does that, but it sounds easy enough to make it: def ReplaceLots(String, RDict): "Replace all occurrences of all keys in RDict inside String" for k in RDict: String = String.replace(k, RDict[k]) return String Simple, eh? Yeah, that's Python for ya. :-) -gustavo From rjones at ekit-inc.com Wed Mar 13 17:36:17 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 14 Mar 2002 09:36:17 +1100 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: <20020313122953.B15069@ActiveState.com> References: <20020313122953.B15069@ActiveState.com> Message-ID: <200203132236.WAA11518@crown.off.ekorp.com> On Thu, 14 Mar 2002 07:29, Trent Mick wrote: > Bugzilla has a big use community, hence, I would suspect better support. It > is heavily used in a lot of projects. Roundup is not, from what I know. It is used in several environments for several purposes. One of these days I'll do a quick poll of the userbase to find out... > With bugzilla you can explicitly add yourself and remove yourself from the > Cc lists of bugs. With roundup you get plopped onto a the nosy list of a > bug by responding to traffic on the discussion. > [snip] > Roundup's use of the subject line of emails to carry bug attributes did > not, in our experience, scale well. Have you investigated roundup recently? That is, since it was re-written from scratch using the spec from the Software Carpentry project? Or are you just making these statements based on several-year-old-knowledge? > Aahz wrote: > > What, if anything, does roundup have that bugzilla > > does not? > > It is written in Python. :) Yeah! :) Bugzilla has some stuff that roundup doesn't provide by default (parent bugs for example), but I believe that roundup is fully capable of all of Bugzilla's functionality by implementing simple detectors. They just haven't been written yet, since all the current users of roundup haven't had the need. Richard From martin at v.loewis.de Fri Mar 1 16:20:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 22:20:47 +0100 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: Skip Montanaro writes: > Just to make sure I understand correctly, under Stephen's propsal would > > s = "\xff" > > be correct? I assume > > s = "?" > > (a literal 0377 character) would be an error, yes? Yes, on both accounts. > That is, when you saw "arbitrary binary data" you are referring to > non-printable octets in the source file, right? Correct (except that whether something is printable is in the eye of the beholder). On the source level, the four letters '\', 'x', 'f', 'f' are not arbitrary binary - they follow a specific syntax. I actually doubt anybody is putting "arbitrary binary" data into source code. Instead, most such occurrences are likely "printable", if viewed in the encoding of the author of that code. Those would be outlawed, unless that encoding is UTF-8. Regards, Martin From phr-n2002a at nightsong.com Wed Mar 6 07:31:53 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 06 Mar 2002 04:31:53 -0800 Subject: [ANN] istring 1.0.1 released; announce list created References: <3C86047F.1080601@stroeder.com> Message-ID: <7xbse1yj0m.fsf@ruckus.brouhaha.com> Artur Skura writes: > It's not something revolutionary, just useful. If it was in standard Python, > I would probably use it every day. See PEP 215 for an integration proposal. From aahzpy at panix.com Fri Mar 22 18:09:19 2002 From: aahzpy at panix.com (Aahz) Date: 22 Mar 2002 18:09:19 -0500 Subject: mutlifile inheritance problem simplified References: <9896e047.0203211303.741f695a@posting.google.com> <3C9BAB77.B4E17C65@hotmail.com> Message-ID: In article <3C9BAB77.B4E17C65 at hotmail.com>, Marc wrote: > >I'm using Windows NT, Python 1.5.2, and IDLE 0.5 Try switching to Python 2.1.2 or 2.2; I'm sure that reload() has had some changeds. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From martin.franklin at westerngeco.com Thu Mar 21 17:54:33 2002 From: martin.franklin at westerngeco.com (Martin Franklin) Date: Thu, 21 Mar 2002 22:54:33 +0000 Subject: Pmw.ComboBox label_text param causes error References: Message-ID: Tom Good wrote: > The Pmw ComboBox sample code at: > > http://pmw.sourceforge.net/doc/ComboBox.html > > shows label_text as one of the possible keyword arguments to the > constructor. However, when I use it I get the error shown below. I'd > appreciate assistance in figuring out the problem. > > > PythonWin 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on > win32. > Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - > see 'Help/About PythonWin' for further copyright information. >>>> from Tkinter import * >>>> import Pmw >>>> Pmw.version() > '0.8.5' >>>> combo = Pmw.ComboBox(None, label_text="foo") > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python21\lib\Pmw\Pmw_0_8_5\lib\PmwComboBox.py", line 139, > in __init__ > self.initialiseoptions(ComboBox) > File "C:\Python21\lib\Pmw\Pmw_0_8_5\lib\PmwBase.py", line 557, in > initialiseoptions > raise KeyError, text + string.join(unusedOptions, ', ') + \ > KeyError: Unknown option "label_text" for ComboBox >>>> Tom, For some reason the COmboBox (and possibly other Pmw's) require the labelpos option if you want label_text (the default for labelpos is no label text so I supose this is by design..... anyhow this works:- import Pmw combo = Pmw.ComboBox(None, labelpos='w', label_text="foo") Martin From siegfried.gonzi at kfunigraz.ac.at Sun Mar 17 05:42:32 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Sun, 17 Mar 2002 11:42:32 +0100 Subject: why python for the academe? References: Message-ID: <3C947318.B0E80317@kfunigraz.ac.at> huck wrote: > > hello all, > > i've been lurking for a while and am amused at how > many people in the list here use python for scientific > computing. why not matlab (or octave or scilab or whatever)? First of all there is a rip-off concerning the European prices. This is one reason (personally for me here in Austria) not to use IDL/Matlab/Mathematica. Not only do they protect a sale outside of America (you won't get a license in America for Europe; you always must buy here at your local dealer) they even charge more than twice of the American prices (this cannot be explained by taxes/shipping/handling). For me this is unacceptable (I would have really no problem when a Third-World-Country would charge overgenerous high prices; but not America-Europe). I only know of PV-Wave (which is just similar to IDL; they bought the IDL code base ten years ago) which has got similar prices for Europe and America (or Common Lisp from LispWorks; they also charge the same prices here in Europe as they do for America). But the above is maybe just only valid for Europe, there must be more reasons. Python with the right combination (numerical libraries and plotting libraries) is much more flexible than lets say Matlab or IDL. What you buy with Matlab is a huge repository of pre-compiled code. Scientist normally do not get paid for programming (curiosity: but they do programming all the time) and a great many are not very well educated how to glue together libraries. Personally, I switched to Windows (even at home I just threw away my Macintosh; but this is another story), because it bothered me to waste my time on Unix with ./configure files and make cycles where at the end the compiler reports that the program does not compile. On Windows I get at least a pre-compiled program. And for me there is also the fact, that when you as a scientist write code in Python it is more likely that a colleague in a developing country can profit from your code. The Matlab or IDL prices for them are unreachable. This is also a reason why I just abandoned Fortran 90 (there are only some commercially deliverd compilers available; yes, yes F-language, but...), and in the meantime I think a scientist is better off when he is using C++; especially if he writes code which others can profit from (lets say a new radiation transfer code for example). But if were in a company I would rethink my stance and maybe I would rely on commercial products. It is a little bit strange to sell results based on free software. How can I convince my customer that he should buy my study and not expect to get it for free. Free software is not all that good as a great many of people want to make believe us. S. Gonzi From phr-n2002a at nightsong.com Fri Mar 22 17:11:26 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 22 Mar 2002 14:11:26 -0800 Subject: Sorting distionary by value References: Message-ID: <7xd6xwntgx.fsf@ruckus.brouhaha.com> Artur Skura writes: > No, and it seems the problem is not with sorting. > I wanted to write a compact word counting script (well, in shell > it can be done in a 5 lines or so), just for fun. >... > for i in a: > if i not in known: This is horrendously slow because for every input word, you're comparing it against all the previously seen words. > it seems it's slow not because of sorting... Correct. I didn't examine your code carefully enough to be sure, but what I think you want is something like this: counts = {} a = string.split(open(sys.argv[1],'r').read()) for w in a: if counts.has_key(w): counts[w] += 1 else: counts[w] = 1 words = counts.keys() words.sort() words.reverse() for w in words: print words[w], w From johnroth at ameritech.net Sat Mar 30 07:46:29 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 30 Mar 2002 07:46:29 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: "Guido van Rossum" wrote in message news:mailman.1017466974.6751.python-list at python.org... > I offer the following PEP for review by the community. If it receives > a favorable response, it will be implemented in Python 2.3. > > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. Yes. I think it will improve the readability of code. > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) That's a hard one. In general, I'd have to go with str(True) returning 1 for compatability reasons. If you don't, I would expect unit test suites to break, as well as anything that externalizes values as strings and then loads them again. Also, repr() should be documented as being changable from release to release - that is, the result of repr() is intended to be fed back into eval() in that release. > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). Keep it consistent with None. True and False. > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. Actually, the example seems totally unreasonable to me. It's treating the fact that February in a leap year has one more day than February in a non leap year as a magic number. Bad! Bad! More to the point, if bool is a subtype of integer, I don't see anything wrong with the type coercion, and I don't see very much value with the purist viewpoint. This could be looked at again if there is ever a version of Python with strong typing. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. Logically, it should return a bool. However, I'm quite willing to settle for whatever is needed for compatability (breaking the least amount of code.) John Roth From peter at engcorp.com Sun Mar 31 01:47:55 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 01:47:55 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: <3CA6B11B.3DFA74C1@engcorp.com> Ken Peek wrote: > > I don't see that adding a "bool" (or better: "boolean", since I HATE > abbreviated words) would be such a big issue. Agreed on that point. "bool" would be less clear to newcomers and possibly those with limited English. (Vague assumption there that those people might have heard of Boolean algebra but might not link it to the shorter form as quickly.) Besides, if we're doing this to look like the other languages, don't they use "boolean" more often? (I realize that's not really the reason for doing this.) From kragen at pobox.com Tue Mar 19 03:24:29 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 19 Mar 2002 03:24:29 -0500 Subject: Use apply() or not, and raising multiple exceptions (co-routines?) References: Message-ID: <83bsdlkls2.fsf@panacea.canonical.org> Roy Smith writes: > The only thing I can see is to have each check method return a list of > problems it found. Then, the main loop would look like: > > for check in self.checks: > for problem in check (self, data): > print 'failed check:', problem > > but that implies pushing a lot of scaffolding down into the check methods, > making them build and manipulate error lists to return. I'm trying to keep > them as clean as possible, so they're easy to write and debug. Well, PyUnit has the same problem. How about this? This skeleton is about a dozen lines of code. class basecheck: def __init__(self, complain): self.complain = complain class somecheck(basecheck): def test(self, data): if isbad(data): self.complain("data is bad") class complainer: def __init__(self): self.complaints = [] def __call__(self, complaint): self.complaints.append(complaint) def runsomechecks(checks, data): acomplainer = complainer() for check in checks: check(acomplainer).test(data) for problem in acomplainer.complaints: print "failed check:', problem But maybe you should just use PyUnit, which is in the standard distribution. From tatebll at aol.com Sun Mar 17 07:03:57 2002 From: tatebll at aol.com (Bill Tate) Date: 17 Mar 2002 04:03:57 -0800 Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: "Nick Arnett" wrote in message news:... > I'll be processing a fairly large number of short (1-6K or so) documents at > a time, so I'll be able to batch up things quite a bit. I'm thinking that > the database might help me avoid loading up a lot of useless data. Since > word frequencies follow a Zipf distribution, I'm guessing that I can spot > unusual words (my goal here) by loading up the top 80 percent or so of words > in the database (by occurrences) and focusing on the words that are in the > docs but not in the set retrieved from the database. Nick, Suggestion, you might also check out metakit (see www.equi4.com). There is a python binding for this embedded database. MK is extremely fast, very flexible in terms of designing a suitable schema and uses a very-straightforward querying syntax. Gordon McMillan added a sql engine on top of it so you can basically use SQL like syntax as well but it is not required. From tim.hochberg at ieee.org Wed Mar 27 09:32:07 2002 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Wed, 27 Mar 2002 14:32:07 GMT Subject: reduce vs. for loop References: <8Rco8.1017$0b.176940@news1.west.cox.net> Message-ID: Oops, that should have been: def fact4(n, step=1): from sys import maxint mult = 1 result = 1L subresult = 1 max_sub_result = maxint / n for mult in range(1,n+1,step): subresult *= mult if subresult > max_sub_result: result *= subresult subresult = 1 return result * subresult def fact5(n): if n < 1024: return fact4(n) result = fact4(n, 2) * 2**(n/2) * fact5(n/2) return result Where fact5 is faster for large enough n. These aren't quite as fast as I claimed before -- I should have been suspicous when fact4 sped up so much when I changed from a while to a for loop. I trusted that things were still working 'cause I had some code in their to check the results, but it depended on assert and I ran those final tests with '-O'. Doh! I beg the court for mercy -- it was late. As Fernado notes, these sort of computations are often better done using approximate methods, but that's not nearly as entertaining. -tim "Fernando P?rez" wrote: > Tim Hochberg wrote: > > > Try this out! For n=100, it's only twice as fast, but try it for n=1000, or > > n=2000 and it really shines.... (I think it even gives the right answer, > > which is a plus.) > > In [23]: fact4 10 > -------> fact4 (10) > Out[23]: 0L > > That doesn't look right to me. > > It's hard to say what the op was after, but in general when you need large n > factorials it's rare to truly need exact results. If you can live with an > approximate answer (good to 10 sig figs or so), then a constant-time solution > is vastly preferrable. Note that this is far from optimal, it's a 3 minute > port of the standard routine from NumRecipes. But it will do in a pinch: > > from Numeric import * > #--------------------------------------------------------------------------- -- > def gammln(x): > """Return the natural log of gamma(x)""" > > cof = array([76.18009172947146,-86.50532032941677, > 24.01409824083091,-1.231739572450155, > 0.1208650973866179e-2,-0.5395239384953e-5],Float) > > y = arange(x+1,x+7,typecode = Float) > tmp = x+5.5 > tmp -= (x+0.5)*log(tmp) > ser = 1.000000000190015 + sum(cof/y) > return -tmp+log(2.5066282746310005*ser/x) > > def fact5(n): > return long(round(exp(gammln(n+1)))) > #--------------------------------------------------------------------------- -- > > This solution obviously has two limitations: > > - not exact, but quite good. Look at a numerical comparison with an exact (but > super-slow) solution: > > def fact6(n): > return reduce(operator.mul, range(1,n+1), 1L ) > > In [27]: fact5 50 > -------> fact5 (50) > Out[27]: 30414093203509286326338827883471693198716826006464232959556714496L > > In [28]: fact6 50 > -------> fact6 (50) > Out[28]: 30414093201713378043612608166064768844377641568960512000000000000L > > In [29]: 1.0*(_28-_27)/_27 # force float div > Out[29]: -5.9048555901676581e-11 > > So that's pretty good numerically. > > - can't go outside the float range. > > In most 'typical' cases, neither of these is a problem (since you can write > most large n problems in terms of logs anyway, which is numerically much > saner). > > Cheers, > > f. From sab at freeuk.com Sat Mar 23 13:11:06 2002 From: sab at freeuk.com (G. Willoughby) Date: Sat, 23 Mar 2002 18:11:06 -0000 Subject: IOstreams/pipes, newbie question, capturing console info form another script? References: Message-ID: this is what i am using: [snip] class RenderBox: def __init__(self, renderMaster="aboutRoot", title="Rendering..."): self.renderMaster=renderMaster self.renderMaster=Toplevel() self.renderMaster.withdraw() self.renderMaster.title("DAoC MapperGUI") self.renderMaster.resizable(0, 0) self.renderMaster.protocol('WM_DELETE_WINDOW', lambda:0) frame0=Frame(self.renderMaster) frame0.grid(row=0, column=0, padx=10, pady=10) Label(frame0, text=title, justify=LEFT, anchor=W, font=("Arial", 12, "")).grid(row=0, column=0, sticky=W) self.text=StringVar() self.textLabel=Label(frame0, textvariable=self.text, width=35, height=8, justify=LEFT, anchor=N+W) self.textLabel.grid(row=1, column=0, sticky=W) self.renderMaster.update_idletasks() self.renderMaster.geometry("%sx%s+%s+%s" % (self.renderMaster.winfo_width(), self.renderMaster.winfo_height(), (self.renderMaster.winfo_screenwidth()/2)-(self.renderMaster.winfo_width()/2 ), (self.renderMaster.winfo_screenheight()/2)-(self.renderMaster.winfo_height() /2))) self.renderMaster.deiconify() self.renderMaster.focus_set() self.update() def updateText(self): self.text=app.mapperScript.read() self.update() def update(self): self.renderMaster.after(100, self.updateText) def destroy(self): self.renderMaster.destroy() [/snip] [snip] self.progressBox=RenderBox() self.mapperScript=os.popen("python mapper.py -settings mappergui.ini -scale %s -out latest_render.jpg -zone %s" % (self.imageSize, self.currentZone)) [/snip] but it doesn't work! i start the script off and the RenderBox pops up but everything freezes until the 'mapper.py' script finishes! any ideas??? "Chris Liechti" wrote in message news:Xns91DAB26BB55B5cliechtigmxnet at 62.2.16.82... > "G. Willoughby" wrote in > news:a7i9kq$ujm$1 at news7.svr.pol.co.uk: > ... > > os.system("python mapper.py -settings mappergui.ini -scale %s -out > > latest_render.jpg -zone %s" % (self.imageSize, self.currentZone)) > > [/snip] > > now i was wondering because this 'mapper.py' script and an > > included 'zone.py' writes alot of info to the console using > > 'sys.stdout.write()' > > can i intercept this using my first Tkinter prgram so i can display > > this info in another freshly created window. basically i am writing > > a gui for a cmdline script! if so has anyone got any examples of > > code for me to look at that would be great! > > have a look at os.popen. it returns a file-like object where you can > read the output from the programm you started. > > chris > > (PS: the NOSPAM will not help much, but its an inconvenience for > people that want to anwser you. some months ago we had a discussion > aout that on this group.) > -- > Chris > From just at xs4all.nl Sun Mar 10 02:12:01 2002 From: just at xs4all.nl (Just van Rossum) Date: Sun, 10 Mar 2002 08:12:01 +0100 Subject: round() function strange behaviour References: <3c8a9261.149508269@news> Message-ID: In article , Just van Rossum wrote: > [ ... ] but I see noone has quoted > Tim's tutorial extension ("node 14"): (Where "noone" is to be read as "Tim Peters", whose post I once again missed as it doesn't have a References header, which makes it show up as far as possible from the actual thread in my newsreader...) Just From mickey at tm.informatik.uni-frankfurt.de Sun Mar 10 16:23:34 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 10 Mar 2002 23:23:34 +0200 Subject: overloading a function References: Message-ID: <3c8bdce5@nntp.server.uni-frankfurt.de> Actually you're getting the most flexibility if you're using variable and/or keyword argument lists. def foo( *args, **kwargs ): ... Yours, :M: From martin at v.loewis.de Sun Mar 31 05:56:46 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 12:56:46 +0200 Subject: relational database? References: Message-ID: "Trung Hoang" writes: > What relational database is easy to setup and use with python? Gadfly. It is a pure-Python database, and requires little administrative interaction. It does not provide good performance, though... Regards, Martin From sjmachin at lexicon.net Wed Mar 6 08:03:35 2002 From: sjmachin at lexicon.net (John Machin) Date: 6 Mar 2002 05:03:35 -0800 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> <4dhb8u4abe8i9e811lgsi4ejf26fav2jk3@4ax.com> Message-ID: Tim Roberts wrote in message news:<4dhb8u4abe8i9e811lgsi4ejf26fav2jk3 at 4ax.com>... > def ShowSize(raw): > if raw < 3000: > return "%d" % raw > elif raw < 2000000: > return "%dk" % (raw / 1000) > elif raw < 2000000000L: > return "%dM" % (raw / 1000000) > else: > return "%dG" % (raw / 1000000000L) :-) I thought only a sales droid would call 1000000 bytes a Mb. (-: From gcordova at hebmex.com Wed Mar 27 13:39:52 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 27 Mar 2002 12:39:52 -0600 Subject: Text to HTML algorithm. Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689E7@SRM201002> Howdy y'alls. Does anybody have an implementation, or know of one, to format plain text into HTML? I need to preserve a minimum of structure, such as wrapping

    ...

    around paragraphs separated by at least one empty line and detecting unnumbered lists (at least). Thankyou very much for any help. -- Gustavo C?rdova Avila > gcordova at sismex.com ? 8351-3861 | 8351-3862 From shalehperry at attbi.com Thu Mar 7 12:12:26 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 07 Mar 2002 09:12:26 -0800 (PST) Subject: Handling bad tags with SGMLParser In-Reply-To: <6c80b2a1.0203070848.6a25b499@posting.google.com> Message-ID: > > The user of SGMLParser needs to be able to handle invalid tags. This > handling may be complex or as simple as just ignoring it and asking > SGMLParser to skip this tag and move along. As far as I can tell this > is not an option. > > As a side note, the text error message thrown is particularly > uninformation as it simply includes the first letter of the tag, in > other words always '<'. > match = special.match(rawdata, i) if match: if self.literal: self.handle_data(rawdata[i]) i = i+1 continue # This is some sort of declaration; in "HTML as # deployed," this should only be the document type # declaration (""). k = self.parse_declaration(i) if k < 0: break i = k continue is the offending code. 'special' is defined as re.compile(r']*>'). I see two options: 1) change the definition of special to a noop match. Something that is relatively cheap but can never match. 2) write your own parse_declaration() method. From cuvy at yvahk2000.pbz Mon Mar 25 18:58:24 2002 From: cuvy at yvahk2000.pbz (Phil Edwards) Date: Mon, 25 Mar 2002 23:58:24 +0000 Subject: Python, CGI and PGP Message-ID: <3c9fbf57@peer1.news.newnet.co.uk> I'm trying to get a CGI app working that is supposed to be able to produce PGP signed messages. The command line equivalent of what I'm trying to do in the CGI script would be: /usr/local/bin/pgp -z mypassphrase -sta -f < /tmp/sometext.txt > /tmp/sometext.pgp 2>/dev/null This works fine both at the CLI and in a bash script, and produces a text file with the '-----BEGIN PGP SIGNED MESSAGE-----' stuff at the top and the PGP signature stuff at the bottom. My recent attempts at getting this to work in the CGI script have been to simply run the same command as above, but using either command.getoutput or os.system from within Python. Doing this, I get the PGP signature block that I would normally expect to see at the end of the message, but nothing else. I suspect that the problem is down to the different execution environment which PGP sees when it's being run within my CGI script, but I've not been able to find anything in the PGP docs that has helped. I've done some research into this on the 'net, but I haven't been able to find any recent references to PGP usage within Python. Some guys were prototyping a PGP interface for Python 1.2 back in 1995, but there doesn't seem to have been any further work done since then. Is there currently a PGP module available anywhere? If not, can anybody point me in the direction of a site that is using PGP and Python? FYI, my version of Python is 2.1, and my PGP version is 2.6.3 (don't ask - just don't, that's all...you'll just start me thinking about it all over again, and I'll probably start to hyperventilate...) -- Phil Edwards Brighton, UK ================================================ NB: E-Mail address is rot-13 encoded Sorry to be a pain, but I get enough spam already... ================================================ From eppstein at ics.uci.edu Fri Mar 1 11:21:54 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 08:21:54 -0800 Subject: Status of PEP's? References: Message-ID: In article , "Bjorn Pettersen" wrote: > Of course, if anyone actually cared about this syntax, we would have a > PEP with a pro/con section, so we wouldn't have to reiterate the same > arguments over and over again I was starting to think it might be time to write a PEP, but then Tim's comment about how he dislikes iterating over 3 discouraged me. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From cbbrowne at acm.org Tue Mar 5 12:54:25 2002 From: cbbrowne at acm.org (Christopher Browne) Date: Tue, 05 Mar 2002 12:54:25 -0500 Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> <7xzo1om5wt.fsf@ruckus.brouhaha.com> Message-ID: The world rejoiced as Paul Rubin wrote: > Christian Tismer writes: >> Makes pretty much sense to me. >> Stackless can provide light-weight threads to all platforms. >> There is no need to use OS threads unless you need it >> for I/O. > Do you think it's feasible to modify Python to use non-blocking i/o > everywhere, and then simulate blocking in Stackless? I.e. when a > microthread does an i/o operation, Python would start the operation > asynchronously, and the Stackless microthread scheduler would block > the microthread til the i/o operation actually completes (detected > using select or SIGIO). That would indeed be rather cool; The Problem would be that this would lose platform independence a bit further still. There is a POSIX "aio" API; it is not uniformly implemented, and use of it would almost certainly dictate a fair bit of OS specificity, rather moreso than seems involved in "Stacklessness." See for more details just on what's going on on the Linux side of things... -- (concatenate 'string "cbbrowne" "@canada.com") http://www3.sympatico.ca/cbbrowne/wp.html Time flies like an arrow, fruit flies like a banana. From mertz at gnosis.cx Wed Mar 27 14:10:16 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Wed, 27 Mar 2002 14:10:16 -0500 Subject: Text to HTML algorithm. References: Message-ID: |Does anybody have an implementation, or know of one, |to format plain text into HTML? |I need to preserve a minimum of structure, such as |wrapping

    ...

    around paragraphs separated by |at least one empty line and detecting unnumbered |lists (at least). I'm rather fond of my Txt2Html utility: http://gnosis.cx/download/txt2html.zip YMMV. -- _/_/_/ 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 shalehperry at attbi.com Thu Mar 7 12:33:55 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 07 Mar 2002 09:33:55 -0800 (PST) Subject: Handling bad tags with SGMLParser In-Reply-To: <1015522226.444.21.camel@temp> Message-ID: > > I'm inclined at the moment to report this situation as a bug. But I > wanted to get some opinions as I'm neither an SGML expert nor fully > confident of my understanding of the SGMLParser class. > I agree this is a bug because the class name is SGMLParser yet it is concerning itself with html tags. From tanzer at swing.co.at Sat Mar 30 02:28:09 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Sat, 30 Mar 2002 08:28:09 +0100 Subject: PEP 285: Adding a bool type In-Reply-To: Your message of "Sat, 30 Mar 2002 00:39:10 EST." <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> Message-ID: > 1) Should this PEP be accepted at all. I can do without it, but wouldn't mind it, as long as bools don't get too strict (like point 4, below). IMHO, Python's traditional concept of truth is much better than a Pascal-like concept of truth. > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) If str and repr were to behave differently from each other, I'd expect repr(True) to return "1" and str(True) to return "True". Interchanging that seems strange. OTOH, I'm worried about backwards compatibility. > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). 'True' and 'False', please. It makes shadowing of the built-in values by user defined variables much less likely. > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. IMHO, `28+isleap(y)` is certainly better than `28+int(isleap(y))`. Used judiciously, booleans in arithmetic expressions can improve readability over conditional statements. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. I'd expect operator.truth to be an alias for 'bool'. If booleans couldn't be used in integer contexts any more, I'd prefer operator.truth to return an int . > Because of backwards compatibility, the bool type lacks many > properties that some would like to see. For example, arithmetic > operations with one or two bool arguments is allowed, treating > False as 0 and True as 1. Also, a bool may be used as a sequence > index. Counting the number of true values in a collection is a common operation. Using bool as an index is also commonly needed. IMO, allowing booleans in these contexts is a good thing (TM) in general, not only for backwards compatibility. > Other languages (C99, C++, Java) name the constants "false" and > "true", in all lowercase. In Python, I prefer to stick with the > example set by the existing built-in constants, which all use > CapitalizedWords: None, Ellipsis, NotImplemented (as well as all > built-in exceptions). Python's built-in module uses all lowercase > for functions and types only. But I'm willing to consider the > lowercase alternatives if enough people think it looks better. Please make it consistent with Python, not with an arbitrary set of other languages. > For truth testing of a value, one should use "if", e.g. "if x: print > 'Yes'", not comparison to a truth value; "if x == True: print 'Yes'" > is not only wrong, it is also strangely redundant. `if x:` is clear, concise, and generic. Adding comparions or an explicit coercion to bool makes it ugly and more difficult to read. ****** How will bool influence '__nonzero__'? Currently, Python insists that '__nonzero__ should return an int'. Will this be changed to 'should return a bool'? As that would break existing code, I hope not. -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From aahz at panix.com Fri Mar 8 08:58:47 2002 From: aahz at panix.com (Aahz Maruch) Date: 8 Mar 2002 05:58:47 -0800 Subject: why is python slow? References: Message-ID: In article , les ander wrote: > >why is a perl program faster than similar python program? Because it isn't? Faster, that is. Sure, one can construct Perl programs that are faster than the equivalent Python program, but one can certainly construct useful Python programs that are faster than the Perl equivalent, particularly if one restricts the libraries to those that come with a default install. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From mhammond at skippinet.com.au Tue Mar 19 03:29:45 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 19 Mar 2002 08:29:45 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: <3C96F705.50908@skippinet.com.au> Andrew Markebo wrote: > Hello! > > I am messing a bit with my bookmarks (gonna sync them between a bunch > of computers and browsers) and now comes the question.. How does > os.listdir in the windows-compiled python handle international > characters? > > For me on my windows 2000 machine, to get them into UTF-8 format I do > something like: > > for filename in os.listdir(): > utffilename=unicode(filename, "latin-1").encode("utf-8") utffilename=unicode(filename, "mbcs").encode("utf-8") should work. > p.s.2 what is the status on win9x? Give it up or ;-) I *think* it still works when accessing a Unicode aware file system (ie, network) Mark. From cd.cd at wanadoo.fr Sat Mar 30 09:44:06 2002 From: cd.cd at wanadoo.fr (Cyr) Date: Sat, 30 Mar 2002 15:44:06 +0100 Subject: Problem with Tkinter References: Message-ID: Thanks a lot for your help ;-) Cyrille From mmoore at cablespeed.com Wed Mar 6 12:27:26 2002 From: mmoore at cablespeed.com (Michele Moore) Date: Wed, 06 Mar 2002 12:27:26 -0500 Subject: Tkinter: can widgets automatically resize to fit parent? References: Message-ID: <3C86517E.8B2621D8@cablespeed.com> Eric Brunel wrote: > Andy Gimblett wrote: > > I want my Tk widgets (some of them, at least) to resize dynamically > > with the window. > > > > Trivial example: > > > > #!/usr/bin/env python > > > > from Tkinter import * > > > > class Application(Frame): > > > > def __init__(self, master): > > Frame.__init__(self, master) > > self.action = Button(self.master, text="Go") > > self.action.grid(sticky=N+E+W+S) > > Two reasons why it's not working: > - you didn't actually display your Application in its master. The > "Frame.__init__" stuff does not suffice: you should also do a pack or grid. > Then, inserting the button in self.master rather than in self should be > useless... > - you configured your button to take the size of its parent cell using the > sticky option, but you didn't tell the cell to take the whole space in its > parent. This should be done via the grid_rowconfigure and > grid_columnconfigure methods to set the weight option on the cell. > > So here is a code that does what you want: > > from Tkinter import * > > class Application(Frame): > > def __init__(self, master): > Frame.__init__(self, master) > ## Actually insert self in its master > self.pack(fill=BOTH, expand=1) > ## Configure cell at (0, 0) to take the whole space > self.grid_rowconfigure(0, weight=1) > self.grid_columnconfigure(0, weight=1) > ## Insert button in self rather than self.master > self.action = Button(self, text="Go") > self.action.grid(sticky=N+E+W+S) > etc... > > HTH > - eric - And watch using both pack() and grid() to be sure you are consistent in their usage per widget hierarchy level. All widgets you manage on 'master' will need to use pack() because you used pack() to manage your Application object on it. All the widgets managed on the Application (Frame) need to use grid() because you used grid() to manage the Button. Mixing pack() and grid() at the same hierarchy level causes the application to lock up and unless you've experienced this first hand, it may be difficult to debug. From writeson at earthlink.net Sun Mar 24 19:08:09 2002 From: writeson at earthlink.net (Doug Farrell) Date: 24 Mar 2002 16:08:09 -0800 Subject: py2exe 0.3.1 hangs trying to remove build under Win98SE References: <88bc63c6.0203191142.1926b089@posting.google.com> Message-ID: <88bc63c6.0203241608.73522f11@posting.google.com> Thomas, Thanks for your reply, I'll try writing a setup.py script specifically for my program and give it a try. I think I got it right in the one I copied, but you never know. I'll give it a try as py2exe would be a useful tool. Thanks for your help, Doug "Thomas Heller" wrote in message news:... > "Doug Farrell" wrote in message news:88bc63c6.0203191142.1926b089 at posting.google.com... > > Hi all, > > > > I'm trying to package up a Python2.2 program that uses wxPython with > > the py2exe system and I'm having no luck. I open up a DOS window (I'm > > running Win98SE) and run the following command line: > > > > python pyexe.py myscript.py > > > > The pyexe.py setup script is something I got from ASPN that is a > > generalized setup script for this purpose, I've listed it below: > > > > from distutils.core import setup > > import sys, os, py2exe > > > > name = sys.argv[1] > > sys.argv[1] = 'py2exe' > > > > sys.path.append(os.path.dirname(os.path.abspath(name))) > > > > setup(name=name[:-3], scripts=[name]) > > > > > > At the end of processing, I get the message: > > removing 'build\bdist.win32\winexe' (and everything under it) > > > > At this point the DOS window hangs and never returns. In fact I have > > trouble killing it with the Task Manager. In addition, at this point > > Windows Explorer no longer runs, it comes up, but the window frame is > > empty. I have to reboot my machine to get full control back. > > > > Doug, I cannot reproduce this (at least with a trivial script under Win98SE). > One thing I noted when I tried this: the build script cannot have the > name 'py2exe.py', because in this case 'import py2exe' imports your > compile script! You should rename it to something like 'compile.py', > and be sure to delete any py2exe.pyc or py2exe.pyo which may have been > created. I think this was mentioned in the ASPN recipe. > > > The script does create the dist directory where I expect it and there > > is a myscript.exe and accompanying DLL's and such there. But if I try > > to run that program, a DOS window comes up with various tracebacks in > > it about not being able to import various modules. The myscript.py > > file runs fine in the interpreter. Anyone have any idea what's going > > on here? I'm runnig py2exe version 0.3.1, so I have the latest. > > > Depending on the modules your script uses, py2exe may have problems > finding them. You should specify them to be included with the --includes > or --packages flag. > > Thomas From logstx at bellatlantic.net Sat Mar 16 15:23:16 2002 From: logstx at bellatlantic.net (logistix) Date: Sat, 16 Mar 2002 20:23:16 GMT Subject: pythonic way of depth first and breadth first tree iterators References: Message-ID: An iterator can either be implicit or explicit. If an object in a for clause isn't an iterator, the interpreter will try to create one by calling the __iter__ magic method via iter(). That way: for x in iterclass: # do stuff translates to this behind the scenes. for x in iter(iterclass): # do stuff You can also explicitly attach iterators via generator methods. for x in iterclass.depth(): #pass for x in iterclass.breadth(): # pass will not be translated to something like "for x in iter(iterclass.depth()):" because the depth and breadth methods are already returning iterators. -- - "Dave Reed" wrote in message news:mailman.1016242886.1030.python-list at python.org... > > We're planning to use Python in our CS1 and CS2 courses next year so > I'm beginning to think about the issues for these courses. > > http://www.python.org/doc/current/lib/typeiter.html states: > > If a container supports different types of iteration, additional > methods can be provided to specifically request iterators for those > iteration types. (An example of an object supporting multiple forms > of iteration would be a tree structure which supports both > breadth-first and depth-first traversal.) > > I don't quite understand exatly what that is saying - what would be > the pythonic way of defining/calling separate breadth first and depth > first iterators for a binary tree class - i.e., is there a way to > indicate which method to use when you make the call to iter() so that > I could do something like: for node in tree('depth'): > > and > > for node in tree('breadth'): > > Or is that just implying that I can make a depth first class iterator > class and breadth first iterator class that both support the > corresponding next() method and do something like: > > d = DepthIter(tree) > for node in d: > > where DepthIter is a class that takes a tree as a parameter to its > constructor and has a next() method that returns the nodes in a depth > first manner. And similarly, write a BreadthIter class? > > Thanks, > Dave > From tim.one at comcast.net Wed Mar 27 23:06:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 27 Mar 2002 23:06:49 -0500 Subject: The Python Way In-Reply-To: Message-ID: [Guido] > "The joy of coding Python should be in seeing short, concise, readable > classes that express a lot of action in a small amount of clear > code -- not in reams of trivial code that bores the reader to death." [Dale Strickland-Clark] > I didn't see the original post but I *really* hope this was said in > jest. > > Or is Guido getting writing software and writing novels confused? [Aahz] > Not in the slightest. Guido was responding to constructs like this: > > lock.acquire() > try: > code > code > code > code > code > code > code > code > code > code > code > code > finally: > lock.release() Actually, he wasn't. That was my attempt to hijack the favorable mindshare Guido attracted toward one of my own pet peeves. What Guido was actually railing against is code like this: class XandY: """A class to wrap x and y values. Use the .get_x() method to get the x value. Use the .set_x() method to set the x value. Use the .get_y() method to get the y value. Use the .set_y() method to g^Hset the y value. """ x = None # default value for x y = None # default value for y def __init__(self, x=None, y=None): self.set_x(x) # set the x value self.set_y(y) # set the y value def get_x(self): "Return the current x value, as most recently set by .set_x()." return self.x def get_y(self): "Return the current y value, as most recently set by .set_y()." return self.y def set_x(self, xvalue): """Set the current x value to xvalue. .get_x() returns xvalue if no other call to .set_x intervenes. """ self.x = xvalue def set_y(self, xvalue): """Set the current y value to yvalue. .get_y() returns yvalue if no other call to .set_y intervenes. """ self.y = yvalue def sum(self): "Return the sum of x and y." return self.x + self.y followed by 50 lines of unit tests to verify proper operation of the trivial methods. This kind of numbing excess is self-inflicted (for a meaning of "self" broad enough to encompass one's employer ). From pearu at cens.ioc.ee Sun Mar 31 18:07:29 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Mon, 1 Apr 2002 01:07:29 +0200 (EET) Subject: PEP 285: Adding a bool type In-Reply-To: Message-ID: On 31 Mar 2002, Martin v. Loewis wrote: > Pearu Peterson writes: > > > Just a random thought ... > > > > Theorem: > > ======== > > Assume specification of PEP 285. The following statements hold truth: > > > > True is One > > > > and > > > > False is Zero, > > > > where One and Zero represent integers 1 and 0, respectively. > > It depends on what the meaning of 'is' is. Did you mean 'is' in the > Python sense of checking identity? Then this theorem can't possibly > true: type(One) is int and type(True) is bool implies One is not True. Sure, this theorem could be improved for correctness by starting defining the meanings of words. I could not use "is" in Python sense because Python does not define objects One and Zero (note the use "represent" instead of "are"), for instance. I used "is" in a general sense that in some cases coincides with the Python "is" (as Tim already mentioned, also the 0 is 0 issue). > > Proof: > > ------ > > According to PEP, True and False are instances of bool that is a subclass > > of int. Therefore True and False can be considered as integers and it > > makes sense to compare them with integers. If n is an integer then the > > following statements hold > > > > True == n only if n is 1 > > > > and > > > > False == n only if n is 0. > > That is correct. However, a==b does not imply a is b. Sure. My main point with this theorem is that the above statements hold even if n is an arbitrary python object ("is" in a general sense). Therefore I find objects True and 1 the same (and questioning the necessity for introducing bool). They are not the same in Python "is" sense but this is irrelevant (as an implementation issue): Python "is" only compares Python objects and not the concepts that these objects represent. Later being more important to me, though, using the former quite often with None. (BTW, None has not always the meaning of False, but the meaning of "don't know" or "default", like in distutils). Pearu From phr-n2002a at nightsong.com Thu Mar 7 01:38:46 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 06 Mar 2002 22:38:46 -0800 Subject: hash(unicode(string)) == hash(string) sometimes (was Re: Why KeyError ???) References: Message-ID: <7xeliwg9vt.fsf@ruckus.brouhaha.com> Tim Peters writes: > If you're indeed correct that floatish numbers have no use as dict keys, > this routine is never executed, so a claim of "extra runtime" would swallow > itself in embarrassment . My solution to the "nine 9's" puzzle used floats as hash keys, so that code got executed at least once :). From SBrunning at trisystems.co.uk Thu Mar 7 04:01:33 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 7 Mar 2002 09:01:33 -0000 Subject: CP4E was Re: Deitel and Deitel Book... Message-ID: <31575A892FF6D1118F5800600846864DCBCD8C@intrepid> > From: Geoff Gerrietts [SMTP:geoff at gerrietts.net] > I'm a parent, too, and there's a big difference between "daddy", > "mommy", and the pronouncements that come from a child anywhere on up > to 18 months and spoken language. > > At three (in April), my son speaks more or less complete sentences > with occassional nods to the rules of grammar. About 3/4 of the time > my wife and I understand him. About 1/4 of the time, others can > understand him. And he's pretty advanced for his age; a lot of parents > guess him at older. Ooops! OK, you *do* have kids. Sorry. But I'll bet that your son has been making himself understood for some time, and he isn't three yet. I *can't* agree that "For those first three years, the child is almost completely incapable of making him or herself understood." And his 'nods to the rules of grammar' are almost certainly a lot more accurate than you think. Children his age get things right the vast majority of the time. It's just that the errors stand out. Again, Pinker talks about this in 'The Language Instinct'. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From s.ernst at web.de Fri Mar 15 08:11:43 2002 From: s.ernst at web.de (Sascha Ernst) Date: Fri, 15 Mar 2002 14:11:43 +0100 Subject: further infos Message-ID: 1. "command not found" is the error message. how can I get more detailed infos? 2. the dev tools are ok, I compiled Ruby some days ago successfully regards, sascha From cliechti at gmx.net Wed Mar 6 14:00:43 2002 From: cliechti at gmx.net (Chris Liechti) Date: 6 Mar 2002 20:00:43 +0100 Subject: [OT] Want to recognize pictures using Python References: Message-ID: "Raymond Hettinger" wrote in news:a65im4$9bp$1 at bob.news.rcn.net: > "F. GEIGER" wrote in message > news:a655p5$82t$1 at rex.ip-plus.net... >> I plan to buy a USB camera ... a bit with image analyzing. Nothing >> sophisticated, just color recognition ... > Yes, PIL is a good choice. and http://stud4.tuwien.ac.at/~e9326522/VideoCapture/ could help to get the imagaes from the camera. chris -- Chris From TBrixi at CSAS.cz Wed Mar 27 09:41:57 2002 From: TBrixi at CSAS.cz (=?iso-8859-2?Q?Brixi_Tom=E1=B9?=) Date: Wed, 27 Mar 2002 15:41:57 +0100 Subject: Strange behavior Message-ID: <414401922FF9D011BEC600805FEA07E301A865DC@XI0SXJ01> Hello, I have downloaded Python 2.2 along with win32 extensions. I have tried some samples and tests (to see what's new) and I have encountered some weird things when running e.g. Python22\Lib\site-packages\win32com\test\testExchange.py 1. when running command prompt it always ends with UnicodeError: ASCII encoding error: ordinal not in range(128) (caused by national characters - windows-1250 encoding) variable is of type types.UnicodeType 2. when running from Pythonwin IDE it goes through display everything even with corrent font set but since then pythonwin ide is somewhat confused. On every pressed Enter key is sends the following to the interactive window and instead of correct newline-and-indent it inserts two new lines without indentation ------------ Firing event '<>' failed. Traceback (most recent call last): File "C:\Python22\lib\site-packages\Pythonwin\pywin\scintilla\bindings.py", line 141, in fire rc = apply(binding.handler, args) File "C:\Python22\lib\site-packages\Pythonwin\pywin\idle\AutoIndent.py", line 256, in newline_and_indent_event lno = index2line(text.index('insert')) File "C:\Python22\lib\site-packages\Pythonwin\pywin\idle\AutoIndent.py", line 483, in index2line return int(float(index)) ValueError: invalid literal for float(): 83.0 ----------- How can I solve these problems (at least the first)? Thanks Regards Tom From martinkaufmann at yahoo.com Tue Mar 12 17:24:07 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Wed, 13 Mar 2002 11:24:07 +1300 Subject: Question about scientific calculations in Python References: Message-ID: <8ivs8usmcdgklfkm3j28ogmagol0i20cvi@4ax.com> On 12 Mar 2002 15:41:32 GMT, hat at se-46.wpa.wtb.tue.nl (Albert Hofkamp) wrote: >On Wed, 13 Mar 2002 01:22:18 +1300, Martin Kaufmann wrote: > >In general, there are at least 2 steps in a problem: >- Figure out what to do (what should I do in what order to obtain correct > results, how should I organize my software). >- Figure out how to do it fast enough. > >Python is extremely well suited for the first step. It is high level, so >experimenting can be done fast, without digging for low-level coding errors >(for example, the amount of code needed to implement a dictionary correctly is >quite astonishing with ample opportunity to make hard-to-find errors). >Being high-level also gives you the benefit that you can concentrate on finding >a good algorithm. Use as much libraries of Python as possible, as they tend to >be optimized for their task (and it saves you from having to code it). But if I then want to change to C I have to write all the functions for which I had a library in Python. >If you program well, and not use too many dynamic features of Python, you can >consider the code as a kind of prototype for an implementation in e.g. C. >Also, selecting a good algorithm has in general more impact on execution >speed than optimizing a bad algorithm. > >'Fast enough' in the second step heavily depends on your expectations and/or >requirements. I always try it first, and if I think it should be calculated >faster, then I think about speed. >First of all, if you can break the computation in independant pieces, do so, >and use more than 1 computer. If that is not enough, see whether you can use >faster or different libraries. If that is not enough, then re-code the program >in C/C++ (which should be not too difficult, since you already have explored >the best way to implement the program using Python (i.e. you don't need to do >step 1 again). In our group we already have a similar program written in C which is may times faster. I just started in Python because I wanted to know how much slower it is and because I don't know C... >As a rule of the thumb I use that I need to save at least as much time running >the program, as I am spending on writing it. >Thus if by re-implementing, I save 1 hour execution time, and I run it 10 >times, then I must be able to rewrite the code in 10 hours, otherwise I am >wasting time. >(if you want to learn a language, this rule doesn't always hold of course). I will have to rerun it for a lot more than 10 times. And during a PhD thesis the "wasting of time" is not always the biggest issue... Regards, Martin From akuchlin at crystal.mems-exchange.org Thu Mar 28 09:26:59 2002 From: akuchlin at crystal.mems-exchange.org (A.M. Kuchling) Date: 28 Mar 2002 14:26:59 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: In article , Dale Strickland-Clark wrote: > Absolutely. All of Mark's Win32 stuff are pretty much essential to > many Windows users now, I would guess. Any volunteers? --amk From martin at v.loewis.de Mon Mar 18 17:02:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Mar 2002 23:02:23 +0100 Subject: How to "hook" print statement. References: Message-ID: "Gillou" writes: > Any clue to have this done as transparently as possible ? I recommend to replace sys.stdout, and use isatty to determine whether it goes to the console or to a file. HTH, Martin From pythonmonkey at hotmail.com Mon Mar 4 23:39:26 2002 From: pythonmonkey at hotmail.com (P.M.) Date: 4 Mar 2002 20:39:26 -0800 Subject: Mac out of memory error on socket.bind Message-ID: hi all, I'm trying some simple python socket programming on my powerbook (OS9.2) and I'm getting an 'out of memory' error when I try to bind a socket, i.e.: HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) # errors here It only fails when my network connection is unplugged (I'm doing my playing around while I commute) and works fine when I have a valid connection. Is there a setting under TCP/IP that'll let me do this sort of localhost-only socket programming while I'm offline? thanks, jim From eppstein at ics.uci.edu Thu Mar 21 14:27:20 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 21 Mar 2002 11:27:20 -0800 Subject: How Can I Determine the Operating System with Python? References: Message-ID: In article , Cliff Wells wrote: > > >>> os.environ['OS'] > > 'Windows_NT' > > > > No idea what it does on other platforms. > > It depends upon whether the environment variable "OS" is present, so it's > probably less reliable than sys.platform (doesn't exist on RH Linux, at > least). Another one where os.environ['OS'] doesn't exist: >>> import sys >>> sys.platform 'mac' >>> import os >>> os.environ {} >>> os.name 'mac' Not sure how you're supposed to distinguish Classic from Darwin... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From jason at jorendorff.com Mon Mar 11 15:34:44 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 11 Mar 2002 14:34:44 -0600 Subject: About deletion of variables in version 2.1 In-Reply-To: Message-ID: Juan Huertas wrote: > Reading a large file and loading to a list: > > f=open('c:/xx','rb') > ls=[] > while not eof: > ln=f.readline() > ls.append(ln) > > This takes 5 seconds (reasonable) This code is a little nonsensical. Could you post real code that can be tested? ## Jason Orendorff http://www.jorendorff.com/ From sab at NOSPAM.freeuk.com Sun Mar 10 05:47:52 2002 From: sab at NOSPAM.freeuk.com (G. Willoughby) Date: Sun, 10 Mar 2002 10:47:52 -0000 Subject: Gurus, I wonder if you can take a look at this source code? Win32... References: Message-ID: Thanks :) G. Willoughby "Gerhard H?ring" wrote in message news:slrna8lkjk.7hm.gerhard at lilith.my-fqdn.de... > G. Willoughby wrote in comp.lang.python: > > Hi, > > I have started writing a text editor for Win32 platforms > > It works fine on Linux simply by not importing win32api. As far as I > can see, you could easily remove all uses of win32api functions. Is it > really needed for tooltips, for example? > > > and i wonder if anyone has a few minutes spare just to take a look > > at the source code and give me a little constructive critisism? > > I didn't find much to critizize :-) > > I've seen this bad practise several times: > > try: > # something > except: > pass > > A better way to do this is to only catch the exceptions that can be > caught there, like IOError or whatever. Catching all exceptions makes > the code difficult to debug and can hide errors for a long time. It's > also a good practise to not only "pass", but log the errors to a > logfile, or simply write the exception to stderr. > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From doug at pobox.com Tue Mar 12 12:28:11 2002 From: doug at pobox.com (Douglas Garstang) Date: 12 Mar 2002 09:28:11 -0800 Subject: doctest Hassles! Message-ID: <10d46bdc.0203120928.7e9c708b@posting.google.com> I posted a question yesterday about how to get doctest to interpret output from the execution of an external program. It was suggested I use: ls=os.popen("/bin/ls","r").read() instead of trying to use spawnv. Well, when I print the value of ls, I get: ' example.py example.pyc tester.py ' Notice the blank line at the end. Where did that come from? There isn't a file with no name in my directory, so why would it print an empty line? Also, why is the output in ONE column instead of across the screen (as in a normal ls) when spawnv is used? All I did was print the output of the ls command, but the output is different. Now, in my code I have: def tester3(): """ >>> import os >>> ls=os.popen("/bin/ls","r").read() >>> print ls example.py example.pyc tester.py """ It ignores the blank line at the end, as the docs say it will. On a side note, I've had this problem before with python, trying to read text config files. As soon as it hit an empty line, reading would stop! Huh? So, as a result, it ignores the empty line on the expect, but gets it on the output, and the test fails! What am I missing here? I would imagine that executing external programs is central to testing, but it seems to be _really_ difficult. From vng1 at mac.com Sun Mar 17 11:28:11 2002 From: vng1 at mac.com (Victor Ng) Date: Sun, 17 Mar 2002 11:28:11 -0500 Subject: problems with compiling python on osx In-Reply-To: <1016203474.1366.80723.m10@yahoogroups.com> Message-ID: I got Python 2.1.2 to build under OS X 10.1.2 to get Zope 2.5 running. Instructions can be found on www.zope.org. Just search for instructions to build Zope for OS X 10.1 (darwin5). Mind you- i was lazy and I never ran 'make test' so I'm just assuming my build works. vic ---- 1. "command not found" is the error message. how can I get more detailed infos? 2. the dev tools are ok, I compiled Ruby some days ago successfully regards, sascha "Just van Rossum" schrieb im Newsbeitrag news:just-226E14.13535315032002 at news1.xs4all.nl... > In article , > "Sascha Ernst" wrote: > > > I've downloaded the newest python sources and tried to run ./configure. I'm > > within the right directory, the shell is located correctly, all > > read/write/execute-rights are set, but even as a root I get the > > error-message "command not found!". is there anything I forgot? > > 1) specific error message please... > 2) do you have the proper dev tools installed? > > Just From fabi.kreutz at gmx.de Fri Mar 1 12:20:10 2002 From: fabi.kreutz at gmx.de (fabi.kreutz at gmx.de) Date: 1 Mar 2002 17:20:10 GMT Subject: SAX-Parser entity References: Message-ID: Hi, Harvey! Ahh, utf-16 sounds good. Thanks, I have at least one solution: Reading the xml-file into a buffer and convert it to utf-16. minidom is then able to parse the whole thing and saves the strings in unicode, which is fine again. I do not understand the part with "If your parser supports...". As it seems to me, the minidom default parser does not support ISO 8859/1 and even unicode makes problems only. I didn't know, you can reprogram the parser so easily. Anyway, thanks a lot. Bye Fabian Harvey Thomas wrote: > I would guess that your document is in ISO 8859/1 (otherwise known as > latin-1). XML parsers must be able to parse utf-8 and utf-16 and may > support other encodings. If your parser supports latin-1 then modify the > XML declaration. Otherwise use the codecs module. >> Problem: >> I try to use the minidom XML-Parser to parse my little file >> in order to generate HTML Code. >> Being german, I really like to use Umlauts but minidom does not. >> ... >> Traceback (most recent call last): >> "/usr/lib/python2.0/site-packages/_xmlplus/sax/handler.py", >> line 38, in fatalError >> raise exception >> xml.sax._exceptions.SAXParseException: :29:19: not well-formed >> >> where Character 19 in Row 29 is the occurence of an ?. From tim.one at comcast.net Tue Mar 19 11:03:26 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 19 Mar 2002 11:03:26 -0500 Subject: [wxPython 2.3.1] what's going on? In-Reply-To: Message-ID: [Pawel Oleksik] > Playing with wxPython modules I've found something -- perhaps bug. > Importing from wxPython.wx changes the calculation rules. > Here is an example (strictly based on the random.py self-verification): > > (Linux, glibc-2.2.5, wxGTK-2.3.1, wxPython-2.3.1) > > > Python 2.1.1 (#1, Aug 26 2001, 02:52:19) > [GCC 2.95.3 20010315 (release)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> import math > >>> 4*math.exp(-0.5)/math.sqrt(2.0) > 1.7155277699214135 > >>> from wxPython.wx import * > >>> 4*math.exp(-0.5)/math.sqrt(2.0) > 2,8284271247461898 ^ > Has anybody met this problem, or it's just my 'private reslult' :) That comma in the output is A Clue: somehow or other, importing stuff from wxPython is changing your locale, which in turn causes "-0.5" to be treated as 0 (the answer you got is correct for 4*exp(0)/sqrt(2)). Do a google search on wxPython locale for more clues; it may or may not be a GTK bug, and the most frequently suggested cure (I haven't tried it) is to do import locale locale.setlocale(locale.LC_ALL, "") after importing stuff from wxPython.wx. From d95-bli.no at spam.nada.kth.se Wed Mar 6 09:35:06 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-15?Q?Bj=F6rn?= Lindberg) Date: Wed, 06 Mar 2002 15:35:06 +0100 Subject: Order of constructor/destructor invocation References: <3C8466F9.2080903@jerf.org> <_f7h8.5541$aP6.6480@rwcrnsc54> <3C851D41.3000902@jerf.org> <3C85446B.B389BB0F@spam.nada.kth.se> <3C855848.60302@jerf.org> Message-ID: <3C86291A.4A2E9CA@spam.nada.kth.se> Jeremy Bowers wrote: > > Bj?rn Lindberg wrote: > > > and yes, all *standards* *conformant* compilers will follow this practice. > > Emphasis mine. That was my point. > > On an intuitive level, that's one of those "depend on it when you have > no other options" kind of features. Even when the standard specs those No it's not; it's a completely well-defined feature. Anyway the OP's original example wouldn't have been a beautiful specimen of code in C++ either, but since it was only an example it doesn't matter. A common use for the technique in C++ is so called "sentry"-objects that handle resources. A stack allocated object that acquires a lock or a file handle for example. The object will be destroyed upon leaving the function, and the lock can be released or the file handle closed. Elegant and efficient. Now imagine two resources where one depends on the other: void a_function () { sentry1 s1; sentry2 s2; ... } The sentry objects will be created and destroyed in the correct order for this kind of use to be possible. Bj?rn From h.jehadalwan at student.kun.nl Thu Mar 7 10:23:22 2002 From: h.jehadalwan at student.kun.nl (husam) Date: Thu, 07 Mar 2002 16:23:22 +0100 Subject: Python and computer graphics Message-ID: <3C8785EA.5010509@student.kun.nl> hi, can anybody points me to usefull resources (books, urls) about using python for computer graphics that help for building skills in this subject from scrash? thanks in advance From mhammond at skippinet.com.au Sun Mar 10 22:10:38 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 11 Mar 2002 03:10:38 GMT Subject: Porcess control on win32 References: <8beb91f5.0203101746.544e64dd@posting.google.com> Message-ID: <3C8C204F.1080100@skippinet.com.au> Ben C wrote: > Hi, > > I am trying to achieve this scenario on a Win32 machine ... > > a. create a lot of new processes (ie. open application 'x' a number of > times with different args) > > b. each time 1 of the processes exits ... do something > > I have looked at using somehting like this > > ... > > project_lst = ['application1', 'application2', 'application3', etc] > > for application in project_lst: > > process, thread, pid, tid = win32process.CreateProcess( > None, > application , > None, > None, > 0, > win32process.NORMAL_PRIORITY_CLASS, > None, > None, > win32process.STARTUPINFO()) > > win32event.WaitForSingleObject(process, win32event.INFINITE) > > print 'Application %s Has Just Exited) % (application,) > ... > > The problem with this structure is it spawns each application in > sequence ... how can I modify this sructure to spawn all applications > simultaneously and still have the print statement executed only when > one of the projects exits? Something like: processes = [] for app in project_lst: p, t, pid, tid = win32process.CreateProcess(...) processes.append(p) while processes: # Wait for one, then remove that one from the list. rc = win32event.WaitForMultipleObjects(processes, INFINITE, 0) offset = rc - win32con.WAIT_OBJECT_0 del processes[offset] Mark. From sumner-nntp5 at forceovermass.com Sun Mar 10 12:13:17 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Sun, 10 Mar 2002 17:13:17 GMT Subject: should i learn it first ? References: Message-ID: In article , Bengt Richter wrote: >> > I'd say if you don't know C, C++, or Python, then start with Python. > Then C++, then C. In that order, you won't have to unlearn patterns > of design you absorb solving problems with C. Ugh, I can see learning Python first but definitely learn C before C++. In that order, you won't have to unlearn patterns of design you absorb solving problems with C++. Seriously, the point of using a low-level language like C or C++ is to get next to the hardware, and it should be learned from that level first IMO. Otherwise, stay with a more productive language like Python. > If you start with C, you will get used to a procedural way of looking > at problems, and when you get to C++ you will be tempted to see it > as just C with extra features. You'll have to dislodge yourself from C > habits of thinking in order to "think objects" in C++. Coming from Conversely, if you learn in the other order you'll find yourself thinking of it as a limited version of C++ instead of a different language with its own idiom. The point of C is that it's procedural, small, and close to the metal. Viewing without the corrupting lens of C++ is extremely valuable, IMO. FWIW, I know more good programmers who learned C and then C++ than vice-versa. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From barry at zope.com Sat Mar 23 20:47:14 2002 From: barry at zope.com (Barry A. Warsaw) Date: Sat, 23 Mar 2002 20:47:14 -0500 Subject: [Python-Dev] [development doc updates] References: <20020323222421.8D11C28696@beowolf.fdrake.net> Message-ID: <15517.12322.143006.15447@anthem.wooz.org> >>>>> "Fred" == Fred L Drake writes: Fred> If you can't tell what the changes are, visit a page that Fred> needs to be scrolled to see the whole thing, and try Fred> scrolling it! Fred! Very very cool. Since I'm using the one true browser <0.9.9 wink> this works great. Would this work with a side bar a la ht2html's output? -Barry From pearu at cens.ioc.ee Sun Mar 10 15:06:44 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sun, 10 Mar 2002 22:06:44 +0200 Subject: How to disable assert statements inside a module? Message-ID: Hi, Is there a way to disable all assert statements inside a module, and without calling python with -O switch? Why? I have developed a module using lots of assert statements (yes, they are all relevant). Now when it is finished, I found that running python with -O switch the speed up is approximately 4 times. I assume that this is due to disabled assert statements. I don't want to remove all these assert statements because I might extend this module in future when they will be handy again for debugging. Next, I want to use this module from other modules that use it extensively. But then, I would expect a remarkable slow down because of the irrelevant assert statements in the first module. So, I would like to disable the assert statements in one module while in others, that are under development, assert statements are enabled. Is it possible? I am using Python 2.2. Thanks, Pearu From uwe at rocksport.de Mon Mar 25 06:57:40 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 25 Mar 2002 11:57:40 GMT Subject: wxPython and wxFlexGridSizer problem Message-ID: [ This is a repost of the following article: ] [ From: Uwe Schmitt ] [ Subject: wxPython and wxFlexGridSizer problem ] [ Newsgroups: comp.soft-sys.wxwindows ] [ Message-ID: ] Hi, when I try the following function on a linux machine I get an input mask consisting of a label and an input field. If i run it under Windows 2k, the label does not appear, and the inputfield is rendered into the first field of the grid... Here is the procedure: def testtt(window): basicSizer = wxBoxSizer(wxVERTICAL) gridSizer= wxFlexGridSizer(cols=2) t=wxStaticText(window, -1, "Eingabe:") gridSizer.Add(t, wxALL | wxALIGN_RIGHT) tt=wxTextCtrl(window, -1, "", size=wxSize(100,-1)) gridSizer.Add(tt, wxALL |wxALIGN_LEFT) gridSizer.SetSizeHints(window) gridSizer.Fit(window) window.SetSizer(gridSizer) window.SetAutoLayout(true) window.ShowModal() Can anybody help me ??? I use wxPython 2.3.2.1 and Python 2.1... Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From brueckd at tbye.com Sun Mar 24 19:37:19 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sun, 24 Mar 2002 16:37:19 -0800 (PST) Subject: list comprehension question In-Reply-To: <5.1.0.14.2.20020324115311.0457dbb8@202.95.131.154> Message-ID: On Sun, 24 Mar 2002, Tripp Scott wrote: > can i generate this list: > > [1, 1.1, 2, 2.1, 3, 3.1] > > with a list comprehension in a form of this: > > [SOMETHING for x in 1,2,3] > > and without using side effects like this? > > result=[] > [(result.append(x), result.append(x+1.1)) for x in 1,2,3] You gotta give us more info on the 1,2,3 part. Does that just represent a sequence of integers? If so, you can go with something like: >>> lo, hi = 1, 3 >>> [x/2 + 0.1*(x%2) for x in xrange(lo*2, (hi+1)*2)] -Dave From bogus@does.not.exist.com Thu Mar 28 01:06:20 2002 From: bogus@does.not.exist.com (Petri Savolainen) Date: Thu, 28 Mar 2002 06:06:20 GMT Subject: Zope Install probs on Mandrake 8.2 References: Message-ID: Do you have Python development package / libraries installed? You need them to build Zope from source. On Thu, 28 Mar 2002 07:16:38 +0200, Bo Vandenberg wrote: > I'm trying to install Zope from source on a fresh install of Mandrake > 8.2. I'd appreciate it if anyone here has advice for this. > > > "python wo_pcgi.py" fails building the extension modules saying "cannot > stat `/usr/lib/python2.2/config/Makefile.pre.in': No such file or > directory. > > This is indead true. > > Is there something a beginner should do at this point? > > Zope claims to run on python 2.1 will it run on 2.2??? > > Thanks in advance. From jim at jim.jim Wed Mar 27 17:21:20 2002 From: jim at jim.jim (jimh) Date: Wed, 27 Mar 2002 14:21:20 -0800 Subject: problems with circular references References: Message-ID: > > It sounds as though somehow or other you want to put the > actual error number data for each class into MessageCatalog > and give the 50 classes some interface for registering > their error numbers with MessageCatalog. Then MessageCatalog > is oblivious to what other classes there are, except that > at run time they tell it about themselves. You could add > another object for holding the error number data > and have one instance per class---if that provides a convenient > structure for accessing the error number data... > > susan > I will have to think about that one. When a class accesses the MessageCatalog, it may be requesting message text from _other_ classes' errors. Also, these are often called from cgi scripts, so they are run as a one-shot deal. Also(!), the case of an error is (theoretically) uncommon and the MessageCatalog is only instantiated if an error occurs. That way, if no error occurs, there is no overhead with importing the MessageCatalog. One thought I had was to split out all the error numbers from the class files (kind of like .h versus .c files). Then MessageCatalog.py would only import the ".h" files and I wouldn't have the circular import reference. However, that would add another 50(!) files. Jim From bokr at oz.net Wed Mar 13 16:32:01 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Mar 2002 21:32:01 GMT Subject: RFC PEP candidate: q''quoted ? References: Message-ID: On 13 Mar 2002 10:20:19 -0500, Christopher Barber wrote: >bokr at oz.net (Bengt Richter) writes: > >> you wouldn't choose the same delimiter ;-) I.e., the main point of >> using an (almost) arbitrary sequence of characters as a delimiter is >> so you'll always have a choice of new delimiters if you need them to >> wrap around text containing old ones. > >For comparison, in the Curl language, there is a concept of tagged verbatim >strings, which look like: > > |"...stuff..."| > >where can be any identifier (or nothing). > >If the tag is an integer, it specifies the number of characters in the string: > > |3"foo"3| > >This is useful when you are generating code containing arbitrary string >literals. > And for fast skips across the source by just a seek, if encoding is fixed. >There are corresponding tagged multi-line comments as well. > I like the symmetry. And the count idea, which I've seen in other forms, but not like that. I'll have to look at the multi-line format. Thanks. Regards, Bengt Richter From philh at comuno.freeserve.co.uk Sun Mar 10 14:24:17 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sun, 10 Mar 2002 19:24:17 +0000 Subject: PyBEEP Project References: <4e72770c.0203092131.457ad7@posting.google.com> <4e72770c.0203100958.31393b4c@posting.google.com> Message-ID: On 10 Mar 2002 09:58:22 -0800, Gabriel Wachob wrote: >It was pointed out to me that not everyone may know what BEEP is. BEEP >is an IETF spec (RFC 3080/3081): > >" >BEEP, the Application Protocol Framework, ... offers advanced features >such as: > >* a standard application layer that supports dynamic, pluggable >application "profiles" (protocols) >* peer-to-peer, client-server, or server-to-server capabilities >* multiple channels over a single authenticated session >* support for arbitrary MIME payloads, including XML >" > >and from RFC 3080: > >a generic application protocol kernel for >connection-oriented, asynchronous interactions called the BEEP >(Blocks Extensible Exchange Protocol) core. BEEP permits >simultaneous and independent exchanges within the context of a single >application user-identity, supporting both textual and binary >messages. Does this mean it is some sort of RPC framework? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From mhammond at skippinet.com.au Fri Mar 8 21:45:37 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 9 Mar 2002 13:45:37 +1100 Subject: [Python-Dev] PEP 282: A Logging System -- comments please In-Reply-To: <20020215164333.A31903@ActiveState.com> Message-ID: > I would appreciate any comments you might have on this proposal > for adding a > logging system to the Python Standard Library. This PEP is still an early > draft so please forward your comments just to me directly for now. Better late than never :) I think the PEP looks good! Re filters: I agree that we need not go as far as ipchains, and no one has said we should. So change that text accordingly. ie, the "The latter is modeled" para can just be a quick not that log4j does it differently, but we have opted for the simpler solution". > "XXX How to defined a nice convenience function for logging an exception? > mx.Log has something like this, doesn't it? I would suggest simply: def exception(self, msg, *args): This is almost identical to error(), but sys.exc_info() is called, and if available the exception details are appended to msg. As sys.exc_info() is called, this is only useful in an exception handler. If that isn't good enough, using traceback with StringIO is pretty easy to create your own log message. > XXX What about a .raising() convenience function? How about: Not convinced we need it. An error() call is pretty good, and hopefully will still stand out like a sore thumb. In general, I would expect a .error() call to be followed by an exception, or some other severe failure anyway, so is kinda redundant. > > What Logging Levels? > > The following are the logging levels defined by the systems I looked at: > > - log4j: DEBUG, INFO, WARN, ERROR, FATAL >... > The current proposal is to copy log4j. XXX I suppose I could see > adding zLOG's "TRACE" level, but I am not sure of the usefulness > of others. I agree 100% No need for TRACE either. What is a TRACE message? It is a debug message. Filtering should be done primarily via the module, not the level. (I loved "SYSTEM_UNIMPORTANT" - if it is unimportant, then don't have it:) > Static Logging Methods (as per Syslog)? I quite like the idea of a simple: import logging logging.error("Something is wrong") and worse, I quite like the idea of pulling namespace hacks so that a reasonable module name is used. Walking the stack until you find '__name__' in your globals is a good default ;) Good job! Mark. From fredrik at pythonware.com Mon Mar 18 17:39:17 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 18 Mar 2002 22:39:17 GMT Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy References: Message-ID: Magnus Lie Hetland wrote: > >the original code used Server -- after all, the object is > >representing a remote server. > > Well, that's one way of seeing it; but it *is* an xmlrpc *client*, no? no, it's a client support class. your program is the client. From mzou at bu.edu Sun Mar 24 22:29:05 2002 From: mzou at bu.edu (ricky) Date: Sun, 24 Mar 2002 22:29:05 -0500 Subject: question: python and UDP Message-ID: I am trying to write a python program to connect to a proxy server which takes the following header: however, the proxy server doesn't seem to understand the header i sent to it. all the ips were converted into binary format: serverip = socket.inet_aton(socket.gethostbyname()) and port number were converted to host byte order: serverport = socket.htons(int(sys.argv[x])) My question is how do i format the header so that proxy server would understand the information I send to it. the proxy server accepts UDP connection... i'd approxiate it if u could reply to my email address as well thank you 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32 bit IP address for your client | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | Server| | | 16 bit port # for your client | Flags | Unused | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32 bit IP address for server 1 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32 bit IP address for server 2 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32 bit IP address for server 3 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32 bit IP address for server 4 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 16 bit port # for server 1 | 16 bit port # for server 2 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 16 bit port # for server 3 | 16 bit port # for server 4 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Defined by you | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Defined by you | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Defined by you | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ The four bit Server Flags field specifies to which servers the packet should be sent. Each bit of of the field represents one of the four servers. A 1 bit indicates that the packet should be sent to that server and a 0 indicates that the packet should not be sent to that server. For example, if the field were set to 1110, the proxy server would send the packet to servers 1-3 but not to server 4. From eric.brunel at pragmadev.com Wed Mar 27 12:47:26 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 27 Mar 2002 17:47:26 +0000 Subject: menu.add_command options References: Message-ID: Paul Sage wrote: > Tkinter: > In the line: > > file_menu.add_command(label='Load Form', underline=0, > command=self.open_file) > > Does anyone have a list of options that go with the menu.add_command? I > need to pass the frame to the method open_file, but I don't know how to > pass that as an argument. You can't do that via any option in the add_menu method. Use "command=lambda o=self, f=yourFrame: o.open_file(f))" or the trick I gave in http://groups.google.com/groups?hl=en&selm=a4alhq%246tp%241%40norfair.nerim.net BTW, the answer to your original question (options for the add_menu method) may be found there: http://www.pythonware.com/library/tkinter/introduction/index.htm (in the part "Tkinter Reference" under "Menu", but just the option names I fear...) or there: http://dev.scriptics.com/man/tcl8.3/TkCmd/contents.htm if you know how to convert tcl-like syntax to Python-like syntax (usually read "option=value" where the manual says "-option value"). HTH - eric - From sholden at holdenweb.com Thu Mar 7 19:58:15 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 7 Mar 2002 19:58:15 -0500 Subject: Module Search Path? References: <3c87e781.62223437@news> Message-ID: wrote in message news:3c87e781.62223437 at news... > I want to store the modules I have written in their own directory. > When I add it to the search path with sys.path.append the changes are > made for one session only. How can I make permanent changes to the > search path? I am using ActivePython 2.1 (PythonWin) in Win98. > > Bruce Robbins See module site, and see if sitecustomize will do it for you. Alternatively make sure the directory is included in the PYTHONPATH environment variable, or fiddle in the registry (something your humble sacribe prefers to avoid under most circumstances). regards Steve From shomon at softhome.net Wed Mar 27 13:20:41 2002 From: shomon at softhome.net (skoria) Date: Wed, 27 Mar 2002 18:20:41 -0000 Subject: Extending/embedding versus separation Message-ID: Hi I have a system for processing usage statistics, for which most of the hard work is done by a small C program which is very good at quickly and with low memory usage, parsing logfiles, and putting the results in hash tables. Now I want to create fancy graphs, cross process the information gathered, work on presentation, make trends and things easy to spot. In short, I want to concentrate on other things than moving memory and pointers around. So the plan was until today to write everything out to a text file and process these files with python to display in html or whatever other format comes to mind. But I've been reminded that python is good at integrating with C programs through extension and embedding. This tells me that the other way to go from here is to turn my c program into a python extension, or somehow merge the two languages, so that I miss the step of saving the C programs results to disk. (and potentially increase memory usage?). I will be having a look at "programming python" tonight, to see which, out of extending and embedding, is what I should go for. Are there any other advantages to using this method, which apart from sounding cool, might offer something I've not thought of? If it's just "cool", then I'll skip it and just go the easy way, of keeping python and C separate, and saving the hash tables to disk. But I'd love people's imput, as this is an important stage in my little baby program's life... :) Thanks very much in advance, Ale From Mitch.Chapman at bioreason.com Fri Mar 22 17:56:45 2002 From: Mitch.Chapman at bioreason.com (Mitch Chapman) Date: Fri, 22 Mar 2002 15:56:45 -0700 Subject: Namespace Qualification Question References: <3C9B7C2A.20708@cpsc.ucalgary.ca__no_spam__> Message-ID: <3C9BB6AD.B331E12A@bioreason.com> Craig McLean wrote: > > I've been messing around with python namespaces and I've run into > something that I haven't been able to answer. > > Is there a module assosciated with the file you started the > interpreter with, and if there is what is it's name? For instance > > > python qux.py > > I would have thought that there would be a qux module, and that it's > name would be stored in the __name__ builtin. > > If I was using the interpreter interactively would that change things? When you use a module as your main module its name is "__main__". This is useful because it lets you use a file as both a module in a larger Python application and as a separate command-line utility: ________________________________________________________________________ #!/usr/bin/env python class Foo: ... def main(): """Do something useful with all of those command-line arguments.""" ... if __name__ == "__main__": """Program mainline for standalone execution.""" main() ________________________________________________________________________ This convention can also lead to subtle bugs, in particular with module-level state, in particular when your main() logic introduces a circular import dependency with another module. One interesting example of this sort of circular dependency is unittest.py, the XP-inspired (?) regression test framework which is included in the Python standard library. You use unittest.py by importing it and deriving test cases and suites from the base classes it provides: ________________________________________________________________________ # MyTest.py import unittest class MyTest(unittest.TestCase): ... ________________________________________________________________________ Then to exercise MyTest you do something like this: $ python unittest.py MyTests.py In this case unittest is used, in a single Python session, as both the program mainline and a module providing services to MyTest.py. When the above command is run, unittest imports MyTests and then searches through it for test cases, suites, etc. derived from unittest's own base classes. Whatever tests it finds, it runs. But in order to reliably detect subclasses of TestCase, unittest must import itself and ask issubclass(obj, unittest.TestCase) rather than just asking issubclass(obj, TestCase) In the latter fragment "TestCase" refers to "__main__.TestCase". But obj comes from MyTests, so if it is a TestCase it will have been derived from "unittest.TestCase". As far as Python is concerned "__main__.TestCase" is a different beast from "unittest.TestCase". So in order to reliably detect the test cases defined in MyTests, unittest must import and reference itself under its "published" name. This also has implications for modules which try to export singletons or default instances of classes. Any such module Foo which can also be invoked as a main program runs the risk of creating two instances of the "singleton", with interesting results. -- Mitch Chapman Dang! I'm wordy today From kseehof at neuralintegrator.com Sun Mar 24 05:20:34 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Sun, 24 Mar 2002 02:20:34 -0800 Subject: forgetting state In-Reply-To: <98b6685d.0203231539.1459d00d@posting.google.com> Message-ID: Some of the problems you may be running into can be solved by using reload(). This is assuming that your problems have to do with making changes to your program between runs. Also, avoid using from mymodule import * when mymodule.py is subject to change because it will complicate your life somewhat. Another trick is to put a reload in your modules: import foo reload(foo) import bar reload(bar) Remember to remove the reloads before you ship! If that doesn't help, launch your application from outside the shell. This is convienient if you make an icon to launch your application. I generally use the latter approach. As far as I know there isn't any good general solution to all of the problems that occur when you rerun programs from a python shell. > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Emerson Wood > Sent: Saturday, March 23, 2002 3:40 PM > To: python-list at python.org > Subject: forgetting state > > > Hi, how would I make a python interpreter > shell forget everything that I've done > and run a script or accepts commands as > if it were first run? > > The reason I ask is that I'm running > on Windows, and using the IDLE which > keeps a Python shell up all the time. > It would be natural to use that shell > to test my program, but I'm finding > problems running it twice. > > -Emerson > -- > http://mail.python.org/mailman/listinfo/python-list From helmut.zeisel at aon.at Wed Mar 6 05:43:03 2002 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: 6 Mar 2002 02:43:03 -0800 Subject: SWIG: output file name for *.py Message-ID: I use swig -python -c++ -shadow -o path/interface_wrap.cxx interface.i This creates two files: path/interface_wrap.cxx and interface.py in the *local* directory. How can I specify a different output directory for interface.py? According to Lutz, Programming Python, 2nd edition, p. 1139, also a third file interface_wrap.doc should be created. Why is this file not created? Do I need an additional option? Helmut From fredrik at pythonware.com Tue Mar 19 10:41:32 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Mar 2002 15:41:32 GMT Subject: python 2.1.2, Linux and 'os' library: bug or (bad) feature? References: Message-ID: Pawel Oleksik wrote: > No way! And as I've written above: python 2.1.1, > 2.1.0, and 2.0.1 work OK. can you spot the bug? $ more Python-2.1.1/Modules/posixmodule.c static PyObject * posix_system(PyObject *self, PyObject *args) { char *command; long sts; if (!PyArg_ParseTuple(args, "s:system", &command)) return NULL; Py_BEGIN_ALLOW_THREADS sts = system(command); Py_END_ALLOW_THREADS return PyInt_FromLong(sts); } $ more Python-2.1.2/Modules/posixmodule.c static PyObject * posix_system(PyObject *self, PyObject *args) { char *command; long sts; if (!PyArg_ParseTuple(args, "s:system", &command)) return NULL; Py_BEGIN_ALLOW_THREADS sts = system(command); Py_END_ALLOW_THREADS return PyInt_FromLong(sts); } From rnd at onego.ru Fri Mar 8 08:24:59 2002 From: rnd at onego.ru (Roman Suzi) Date: Fri, 8 Mar 2002 16:24:59 +0300 (MSK) Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <3C87C057.4040902@sympatico.ca> Message-ID: On Thu, 7 Mar 2002, Ramkumar Kashyap wrote: >My original intent for starting the thread was because I truly believe >in CP4E. In USSR in mid-1980s schools had similar (mis?)conception. It was said: 'Programming is second literacy!". And Computer Science was added to all curricula at secondary schools. And teachers were to learn it. (In fact, it was easier, because specialists came to schools from industry). Now we have very different situation in Russia. CS ("Informatics") teaches children theoretical concepts + using computers (and Internet, if possible). Programming is being taught only at some elite schools where teachers themselves are able to program or pretend the are. Children are distracted by colorful windows and interactive games from deeper joys of creative programming work... Even 10-11 form schoolchildren clearly prefer IDEs over "blockbox" of command prompt (unless they feel more dignity in the later). No wonder! CP is not 4E in Russia. Some high officials even dare to argue "Ohm's law" is not needed in schools' curricula... And those points of view are extreme. CP is almost purely creative. That is why it has no logic (let alone intuitive). And as everywhere creator need to know only building blocks (bricks), almost everything else is up to his mind. Choice is a foundation of creativity, IMHO. So, CP4E goal will be fulfilled when building blocks will be as clear, as bricks, and still as powerful as Python ;-) It will not surprise me if hundred years from now auctions will sell Emacs source at $1000000 and Van Rossum's works will be in the same price as Van Gogh. >In my freshman year, we were a total of 38 students in the EE >major. When I graduated four years later, there were 12 of us, no women. > I don't believe that programming concepts are more difficult/harder to >understand and grasp than any engineering curriculum or for that matter >physics/mathematics. Hmmm... True mathematics/physics are harder than programming, of course. >Somebody in this thread raised the point that the logic involved in >programming in not intuitive. I agree with that. The point I want to >make is that there are programs like Hooked-on-Phonics, and other >remedial language programs that are quite effective in raising the >literacy levels among adults. Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Friday, March 08, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "People are always available for work in the past tense." _/ From fdrake at acm.org Mon Mar 25 15:37:41 2002 From: fdrake at acm.org (Fred L. Drake) Date: Mon, 25 Mar 2002 15:37:41 -0500 (EST) Subject: [development doc updates] Message-ID: <20020325203741.2CD5118EAD0@grendel.zope.com> The development version of the documentation has been updated: http://python.sourceforge.net/maint-docs/ Documentation for Python 2.2.1 release candidate 2. From grey at despair.dmiyu.org Wed Mar 6 20:05:03 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 07 Mar 2002 01:05:03 -0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 16:57:03 -0800, David Eppstein wrote: > I think you have made my point for me, that range is hard to use > correctly. Did you try running range(n-1,0)? What list did it give you? >>> range(-10,0) >>> [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1] And? How does this prove your point other than some minor nit I'm sure you're going to pick? Point stands, there are other ways of doing it. While I've got your attention, let me ask you this. In your notation how would you do the following? for x in range(n-1,-1,-2): That, unlike the allusion you made above, is not a nit. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From cliechti at gmx.net Fri Mar 29 18:09:09 2002 From: cliechti at gmx.net (Chris Liechti) Date: 30 Mar 2002 00:09:09 +0100 Subject: Breaking String into Values References: Message-ID: robert garretson wright wrote in news:HD5p8.33836$tg4.398811 at vixen.cso.uiuc.edu: > I am working on reading in a data file format which is set up as a > series of lines that look like this: > > 3500035000010104A Foo 45 > > I want to break up into a variables as follows: > a = 35000, b = 35000, c = 10104, d = 'A', e = 'Foo', f = 45 > > My current code (auto-generated from a data dictionary) looks > something like this: > > temp = line[0:5] > a = int(temp) > temp = line[5:10] > b = int(temp) > temp = line[10:15] > c = int(temp) > temp = line[15:16] > d = temp > temp = line[16:20] > temp = temp.rstrip() > e = temp > temp = line[20:23] > f = int(temp) > > with a bit more error checking around the int() calls. > > Is there a better way to do this? The files have around 1000-8000 lines > each so I would like it to be fast. Is there a package around that > someone has coded up as a C-extension to do this? i had to remove one "0" from the input to match you results above here's some abuse of the struct module >>> l = struct.unpack("5s5s5s1s4s3s","350003500010104A Foo 45") >>> a,b,c = map(int, l[:3]) >>> d,e = l[3:5] >>> f = int(l[5]) >>> a,b,c,d,e,f (35000, 35000, 10104, 'A', ' Foo', 45) but i think your solution is easy to understand and fast enough for some thousand lines within seconds. chris -- Chris From christophe.delord at free.fr Fri Mar 1 12:22:50 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Fri, 01 Mar 2002 18:22:50 +0100 Subject: Python's Syntax References: Message-ID: <3C7FB8EA.8060005@free.fr> Hi, If your question is about block separators, just read the documentation for further details : http://www.python.org/doc/current/ref/indentation.html Lines with the same indentation are in the same block: if condition: inst1 # do this if true inst2 # do this if true else: inst3 # do this if false inst4 # always do this David Russell wrote: > Hi, > > I can't get my head around Python's syntax for the if, for, while etc. > statements. > > I'm used to the classic: > > if (condition == TRUE) > { > Do this > } > else > { > Do this > } > > I've had a look at a couple of tutorials for Python and it appears like > this: > > if condition == TRUE: > do this > > > How do you tell it when to stop? I just can't figure out how to do it. Could > somebody explain it to me please, even though I have a strange suspicious > that it is one of the simplest deatils imaginable. > > Also, another thing about Python's syntax. Are statements just sperated by > their lines, or do they have some form of seperator (like a semi-colon)? > > > Thanks for any help, it is appreciated. > > (Sorry if this appears twice, the first time I sent it I got an error so I'm > not sure if both will show up) > > > > > > -- Christophe Delord http://christophe.delord.free.fr/ From upersad at tstt.net.tt Tue Mar 19 21:23:55 2002 From: upersad at tstt.net.tt (Umesh Persad) Date: Tue, 19 Mar 2002 18:23:55 -0800 Subject: arrays help Message-ID: <000501c1cfb6$495eed80$77c75ed1@umesh> Hi, I am just getting started with Python from a c/c++ and Java background. I am programming a game and I wanted to represent a gameboard by a double subscripted array. How do I do this in Python? Thanks, Umesh From phr-n2002a at nightsong.com Wed Mar 27 09:13:22 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 27 Mar 2002 06:13:22 -0800 Subject: Primes.... References: Message-ID: <7x1ye6drp9.fsf@ruckus.brouhaha.com> "FREDRIK HULDTGREN" writes: > I should have been more specific, yes I am talking about cryptology, and > sadly enough I am runnign win2k, the unix stuff goes out the window. As > for how large of numbers I am looking for, I'd say about 512bit numbers > should do it(perhaps larger, depens on how slow it becomes). Got any > URLs that explain Fermat/Miller-Rabin tests? Fermat test: def probably_prime(n,base=3): return pow(base,n,n)==base For cryptography sized random numbers this is basically 100% accurate. The unix stuff just pertains to reading random #'s from /dev/urandom. If you're running cygwin, that emulates it so it should still work. Otherwise write a C extension that calls CryptGenRandom from the Windows CAPI. I'm hoping someone will submit a module that does that to the Python library. From aahzpy at panix.com Wed Mar 20 14:36:27 2002 From: aahzpy at panix.com (Aahz) Date: 20 Mar 2002 14:36:27 -0500 Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: In article , Nick Arnett wrote: >Aahz: >> >> Well, well, well, long time no see. Why not just use Verity? ;-) > >I was wondering if that was you -- how many Aahzes could there be in the >world? Quite a few, actually, but only one or two others use it as something other than a nickname. >> Seriously, for this kind of work, it's quite likely that Perl can be >> coded to be a bit faster than Python, but if you're expecting to need to >> do a lot of iterative work on your algorithms, programmer time will >> count for a lot, and Python will probably win there. > >I've actually done a lot of it in Perl already and I'm re-coding it in >Python. I'm astounded and very happy at how much faster I'm able to code in >Python. And I can read it a few weeks later without squinting too hard. ;-) >Say, how does it look to find a marketing weenie on the Python list? >Actually, I've always coded, I just sometimes manage to supress the urge. >The work I'm doing now is closely related to what I was working on when >Verity lured me, back when the Web was a baby. We get all types here; that's one of the things I love about the Python community. >> Given that it sounds like you want to create your own inverted word >> index and do some sorting/searching based on word counts, it'll be hard >> to get more bang for the buck than a real database. Unless you're on a >> shoestring, consider getting a commercial database; you should probably >> also check to see whether MySQL or PostgreSQL will give you better >> performance. > >I'm using MySQL; that's what the Perl stuff was talking to. Well, in the "Java and Python" thread, someone posted an URL that said that MySQL comes close to Oracle for speed, at least when talking to Java: http://www.eweek.com/print_article/0,3668,a=23115,00.asp >Say, do you know if anyone has created a Python wrapper for VDK (Verity >Developer Kit, for the rest of you)? Eventually, when I want to bear the >cost, I'll probably want to use it. For now, though, I'm trying to stick >with open source tools for anything that gets deployed. When I was working at SearchButton.com, we wrote one, and it's quite handy to use VDK from Python. It was a lot easier than writing the equivalent from Perl. But the code is lost along with SB.com. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. --Aahz From just at xs4all.nl Mon Mar 18 13:48:42 2002 From: just at xs4all.nl (Just van Rossum) Date: Mon, 18 Mar 2002 19:48:42 +0100 Subject: Correct to use instance = module.__dict__[class_name]() ? References: Message-ID: In article , Andy Gimblett wrote: > def bar(module_name, class_name): > module = __import__(module_name, globals(), locals(), []) > handler = module.__dict__[class_name]() > return handler > > Is this correct? In particular I'm worried that __dict__ is not the > thing to use to get at the class object, but only really because I > don't recall seeing it used like this before. Again, it seems to work > fine - I just want to make sure I'm doing The Right Thing. :-) All > input appreciated. This would be better: def bar(module_name, class_name): module = __import__(module_name, globals(), locals(), []) handler = getattr(module, class_name)() return handler Just From bokr at oz.net Tue Mar 26 15:40:15 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Mar 2002 20:40:15 GMT Subject: beginner question References: Message-ID: On Tue, 26 Mar 2002 07:29:33 GMT, "Qiang.JL" wrote: > >"Bengt Richter" wrote in message >news:a7p5o2$5oe$0 at 216.39.172.122... >> On Tue, 26 Mar 2002 05:25:28 GMT, "Qiang.JL" wrote: >> >> >for this line: >> > >> >>>> g=(lambda x: ' '.join(x.split())) or (lambda y: 'second') >> > >> I doubt if this expression is doing what you want. It is the same form as >> >> g = a or b >> >> which will set g to a, unless a counts as false (e.g., None,'',[],(), or >zero), >> in which case g will be set to b irrespective of b's value. So your >expression >> is effectively equivalent to >> >> g=(lambda x: ' '.join(x.split())) >> > >sorry english is not my native language, but why equivalent ? are you saying >the second condition is useless? > Yes, the way you have written the expression for g, it will be ignored. The effect of the "or" in the statement g=(lambda x: ' '.join(x.split())) or (lambda y: 'second') is to say Bind the symbol 'g' to the first term on the right hand side that evaluates to true. In this case, the first term is a function defined by (lambda x: ' '.join(x.split())) Looking with the interpeter, you can see: >>> (lambda x: ' '.join(x.split())) at 0x0079FAF0> So your statement could be broken down to a sequence like: >>> a = (lambda x: ' '.join(x.split())) >>> b = (lambda y: 'second') >>> g = a or b Looking at the results, g becomes bound to the first term of the or: >>> a at 0x007A1D70> >>> b at 0x007A1720> >>> g at 0x007A1D70> >>> g==a 1 (Note that the a and g locations are identical at 7A1D70 vs the b location at 7A1720). > >> If you really don't want to use def and you want to use your original >> expressions, use another lambda to tie them together, e.g., (OTTOMH, >> not very well tested ;-) >> >> >>> g = lambda x: (lambda x: ' '.join(x.split()))(str(x)) or (lambda y: >'second')(str(x)) >> >>> g(' ') >> 'second' >> >>> g(g) >> ' at 0x007DB060>' >> >>> g(' a bc def') >> 'a bc def' >> >> Notice that the ouside lambda has a body that both defines _and_ calls the >internal lambdas >> with the str()-protected arguments. The second lambda will only be called >if the first one >> returns ''. The outside lambda then returns the result from whichever >internal one. >> >> But I'd say that's pretty ugly to read compared to >> >> >>> def g(x): >> ... return ' '.join(str(x).split()) or 'second' >> ... >> >> ;-) >> >> Regards, >> Bengt Richter >> > >if the original lambdas work like yours why you add another one outside ? it >seems does the same thing. Well, it only seems ;-) Look closely at the way it's written (see below). >Weird i run into problem with this one .. > >>>> def g(x): > return ' '.join(str(x).split()) or 'second' > >>>> g(0) >'0' >>>> g('') >'second' >>>> g=(lambda x: ' '.join(str(x).split())) or (lambda x: 'second') >>>> g('') >'' # why it prints '' instead of 'second' ?????? See above. You are still misunderstanding the meaning of your g=(lambda x: ' '.join(str(x).split())) or (lambda x: 'second') statement. It does _NOT_ combine the two lambdas into a new function. Instead, it chooses ONE of the lambdas according to the 'or'. That is why I put another lambda around them both. So that the outside lambda could use the 'or' to choose between their _results_. Notice that the body of the ouside lambda is an expression that actually _calls_ the inside lambdas: (lambda x: ' '.join(x.split()))(str(x)) or (lambda y:'second')(str(x)) ^^^^^^^^ ^^^^^^^^ so the 'or' is choosing between results, not between lambdas. To make a function out of the above expression requires the outside lambda. >>>> g(0) >'0' > >what's wrong here ? Nothing. Everything is working as written ;-) When the result of a complex expression seems mysterious, try evaluating smaller pieces interactively. Also, if you play with the disassembler, you can see how the compiler translates your statements and expressions. E.g., comparing your g definition with my wrapped one: >>> import dis >>> dis.dis(compile("""g=(lambda x: ' '.join(str(x).split())) or (lambda x: 'second')""",'','exec')) 0 SET_LINENO 0 3 SET_LINENO 1 6 LOAD_CONST 0 ( at 007DAB90, file "", line>) 9 MAKE_FUNCTION 0 12 JUMP_IF_TRUE 7 (to 22) ^^^^^^^^^^^^-- here it's choosing the first lambda and jumping to 22 to store it because the value being tested here is the lambda function itself, not a result of calling the lambda, as in the correct version -- 15 POP_TOP 16 LOAD_CONST 1 ( at 007DAB10, file "", line >) 19 MAKE_FUNCTION 0 >> 22 STORE_NAME 0 (g) 25 LOAD_CONST 2 (None) 28 RETURN_VALUE >>> Versus: >>> dis.dis(compile("""g = lambda x: (lambda x: ' '.join(x.split()))(str(x)) or (lambda y:'second' str(x))""",'','exec')) 0 SET_LINENO 0 3 SET_LINENO 1 6 LOAD_CONST 0 ( at 007DB3A0, file "", line 1>) 9 MAKE_FUNCTION 0 12 STORE_NAME 0 (g) 15 LOAD_CONST 1 (None) 18 RETURN_VALUE Here it only sees one lambda. It is not choosing between two to store with name 'g'. To see how the body expression of this lambda looks, we can disassemble it. Note that this is an expression, not a statement, so we have to tell the compiler 'eval' instead of 'exec': >>> dis.dis(compile("""(lambda x: ' '.join(x.split()))(str(x)) or (lambda y:'second')(str(x))""",'eval')) 0 SET_LINENO 0 3 LOAD_CONST 0 ( at 007D9130, file "", line 1>) 6 MAKE_FUNCTION 0 ^^^^^^^^^^^^^-- here we have the first lambda, but we're NOT going to JUMP_IF_TRUE here 9 LOAD_NAME 0 (str) 12 LOAD_NAME 1 (x) 15 CALL_FUNCTION 1 ^^^^^^^^^^^^^-- here we call str(x) for safety to make the arg for the lambda 18 CALL_FUNCTION 1 ^^^^^^^^^^^^^-- here we call the first lambda,, and now have the result '' or 'something' 21 JUMP_IF_TRUE 19 (to 43) ^^^^^^^^^^^^ -- this will not jump if the result was ''. Here we may go on to the second lamda 24 POP_TOP 25 LOAD_CONST 1 ( at 007D91C0, file "", line 1>) 28 MAKE_FUNCTION 0 ^^^^^^^^^^^^^-- here we have the second lambda 31 LOAD_NAME 0 (str) 34 LOAD_NAME 1 (x) 37 CALL_FUNCTION 1 ^^^^^^^^^^^^^-- call str(x) for safety as before 40 CALL_FUNCTION 1 ^^^^^^^^^^^^^-- here we call the second lambda >> 43 RETURN_VALUE For the code of the lambda bodies: >>> dis.dis(compile("""' '.join(x.split())""",'','eval')) 0 SET_LINENO 0 3 LOAD_CONST 0 (' ') 6 LOAD_ATTR 0 (join) 9 LOAD_NAME 1 (x) 12 LOAD_ATTR 2 (split) 15 CALL_FUNCTION 0 18 CALL_FUNCTION 1 21 RETURN_VALUE and >>> dis.dis(compile("""'second'""",'','eval')) 0 SET_LINENO 0 3 LOAD_CONST 0 ('second') 6 RETURN_VALUE HTH. BTW, why did you choose lambda to define your g function? lambdas in Python are limited to a single expression body, so it is very constraining, and you wind up writing hard-to-read code if you need to do anything complex. Immediately binding to a symbol like your 'g' just begs for using def instead. Regards, Bengt Richter From jason at jorendorff.com Thu Mar 14 07:24:04 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Thu, 14 Mar 2002 06:24:04 -0600 Subject: Hexadecimal bytes to integers In-Reply-To: <3C908ADF.7040009@vip.fi> Message-ID: pekka wrote: > How can I convert messages below to list of bytes: > > message = 0x01040000000271 > or > message = 0104000000A271 > to > m = [0,1,0,4,0,0,0,0,0,0,0,0,'A',2,7,1] Well, if it's a string then you can do this. >>> message = '0104000000A271' >>> m = [ int(b, 16) for b in message ] >>> m [0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 10, 2, 7, 1] ## Jason Orendorff http://www.jorendorff.com/ From andreas at mtg.co.at Wed Mar 13 14:15:39 2002 From: andreas at mtg.co.at (Andreas Kostyrka) Date: Wed, 13 Mar 2002 20:15:39 +0100 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: References: <3C86047F.1080601@stroeder.com> Message-ID: <20020313201539.2995aad0.andreas@mtg.co.at> On Wed, 6 Mar 2002 12:10:58 +0000 (UTC) Artur Skura wrote: > Ask yourself which query is clearer: > > (1) db.query("""SELECT foo, bar > FROM %s > WHERE rsrc_id = %s > AND name = '%s'" % (table, rsrc_id, name)) > > Or: > > (2) qry = istring("""SELECT foo, bar > FROM $table > WHERE rsrc_id = $rsrc_id > AND name = $.name""") > db.query(qry) > And what about: db.query("""SELECT foo, bar FROM %(table)s WHERE rsrc_id = %(rsrc_id)d AND name = '%(name)s'""" % locals()) pure standard Python :) Andreas From philh at comuno.freeserve.co.uk Wed Mar 6 19:28:30 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 7 Mar 2002 00:28:30 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 09:08:57 -0800 (PST), Sean 'Shaleh' Perry wrote: >I am a little confused. > >Your proposal starts with the claim that people are looking for a natural way >to loop over a range of integers. How about: for i = 1 to 10: or for i is 1 to 10: I think these are both equally good and both much preferable over the horrible for 1 <= i <= 10: which I can only assume is someone's sick idea of a joke. This syntax could easily be extend, to allow a step other than 1: for i = 1 to 10 step 3: -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From garry at sage.att.com Mon Mar 4 10:16:42 2002 From: garry at sage.att.com (Garry Hodgson) Date: Mon, 4 Mar 2002 15:16:42 GMT Subject: Hosting References: <283adf56.0202201551.7026d548@posting.google.com> Message-ID: <3C838FDA.5016804F@sage.att.com> Kevin Dahlhausen wrote: > > Does anyone know of an inexpensive web host that allows compilation > and use of Python extensions from your own directory? i've been happy with http://www.your-site.com/ 50 MB Disk Space, 25 POP3 E-Mail Accounts, 6 Gigs Transfer, Daily Tape back-ups, E-Mail Control Panel, Frontpage 2000 Extensions, Private Logs, RealAudio & RealVideo Detailed Statistics, 99.9% Guaranteed Uptime, 24/7 FTP Access, your own cgi-bin directory. i can login using telnet or ssh and futz around with directory structures, compile code, etc. i left my previous host because their support was poor. these folks have been very responsive, the few times i've had questions. -- Garry Hodgson Let my inspiration flow Senior Hacker in token rhyme suggesting rhythm Software Innovation Services that will not forsake me AT&T Labs 'til my tale is told and done. garry at sage.att.com From billbobill at web.de Thu Mar 28 15:58:44 2002 From: billbobill at web.de (pitbill) Date: Thu, 28 Mar 2002 21:58:44 +0100 Subject: Running zope as a WIN32 service Message-ID: Hi there, I've installed Zope 2.4 two weeks ago and didn't choose to run Zope as a service :( Now I want to run Zope as a service, because I'm bored of starting it via the batch file. Can someone tell me how I can do this? Thx a lot pitbill From Dag at animagicnet.no Wed Mar 13 06:22:08 2002 From: Dag at animagicnet.no (Dag) Date: 13 Mar 2002 11:22:08 GMT Subject: module import in cgi scripts Message-ID: I'm trying to write a cgi script in python but I'm having a lot of problems importing modules. I've simplified my script down to #!/usr/bin/python2.2 import pg print "hello\n" if I run it from the command line it prints "hello" as expected, but if I put it in my cgi-bin directory and access it from a web browser the web server returns Internal Server Error and the error log says: Traceback (most recent call last): File "/var/www/cgi-bin/summarypie.py", line 4, in ? import pg ImportError: No module named pg I have checked and double checked and the pg modules is in the python sys.path. What's wrong? I'm running this on Apache 1.2.23 on linux. Dag From jcromwell at ciena.com Thu Mar 14 13:52:50 2002 From: jcromwell at ciena.com (Cromwell, Jeremy) Date: Thu, 14 Mar 2002 10:52:50 -0800 Subject: fun codeop hack Message-ID: This is fun. For simplicity, also add this routine to codeop.py: def addMacro(pattern, result): import re patRe = re.compile(pattern) def _macro(string): return patRe.sub(result, string) Compile.macros.append(_macro) Now you can do this: >>> import codeop >>> codeop.addMacro(r'for\s+(\w+)\s*=\s*(\d+)\s+to\s+(\d+)\s*:', r'for \1 in range(\2, 1 + \3):') >>> for i = 1 to 6: ... print i ... 1 2 3 4 5 6 --Jeremy Cromwell -----Original Message----- From: logistix [mailto:logstx at bellatlantic.net] Sent: Tuesday, March 12, 2002 7:05 PM To: python-list at python.org Subject: fun codeop hack Replace the Compile class with the following: class Compile: """Instances of this class behave much like the built-in compile function, but if one is used to compile text containing a future statement, it "remembers" and compiles all subsequent program texts with the statement in force.""" macros = [] def __init__(self): self.flags = 0 def __call__(self, source, filename, symbol): for macro in Compile.macros: source = macro(source) codeob = compile(source, filename, symbol, self.flags, 1) for feature in _features: if codeob.co_flags & feature.compiler_flag: self.flags |= feature.compiler_flag return codeob ============================ Now you can do all kinds of fun stuff like this in IDLE and PythonWin ============================ PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import re >>> forRe = re.compile(r'for\s+(\w+)\s*=\s*(\d+)\s+to\s+(\d+)\s*:') >>> def newFor(string): ... return forRe.sub(r'for \1 in range(\2, 1 + \3):',string) ... >>> import codeop >>> codeop.Compile.macros.append(newFor) >>> >>> for i = 1 to 6: ... print i, i*i ... 1 1 2 4 3 9 4 16 5 25 6 36 >>> PS. For the record I'm perfectly happy with current for loop syntax. Just thought it was a good example -- http://mail.python.org/mailman/listinfo/python-list From jjd at enteract.com Wed Mar 6 10:03:30 2002 From: jjd at enteract.com (jim dutton) Date: 6 Mar 2002 15:03:30 GMT Subject: Brenda Lee Ehmka has forgotten about Kevin Ehmka References: Message-ID: In article , xganon wrote: >Brenda, do you wash your hands and your cunt after you masturbate, or do you >leave your own skank all over yourself, pretending it's Jackie Tokeman's jism? > Steve chaney Brenda is out of your league. Get over her. ========================================================================= Visit a homepage: www.bishopdutton.org Read about the internets biggest kook/pedophile/obese/ chronicly unemployed/women beater. ie the worst of the internet: http://www.pat-acceptance.org Feed blobbi the psychopath a hog http://pat-acceptance.org/bobbi.html ========================================================================= **whoop whoop chany alert** now me, i wouldnt call chanby a philistine. he's a fanboy. an angry one ... much like the angry ape in the passage from Measure For Measure that i quoted above. and accordingly we see chabny once again adopting the cartoontoothed battle-postures of Quake Arena in order to give his inferiority complex a temporary boner, a sad, tiny, angry, miniature boner that will last long enough to drop doomed legacyless chanbyseed across multiple pages of the japanese preteen rape comix that he holds so defensively close to his heart. -cb >Date: Wed, 31 May 1995 19:21:16 -0600 (MDT) >From: What happens if I press THIS button? >To: Talk-List >Subject: This is the side of Tawnya that GunHed won't tell anyone. (snip) >There was a lot that caused me to no longer want to be with Steve. Some >of it was the fact that he was too .. rigid. To me, he had no sense of >humour and he took all my questions to be personal attacks. Yes, I >admit that I was a bitch to him for the last year. That's because I did >not want to be with him. Since April of '94, I told him that I wanted >out of the relationship. But he wouldn't let me go. He refused to let >me leave him even though he knew I wasn't happy with him. So, I started >arguments at any opportunity I could. I made his life a living hell >trying to get him to let me go, but he wouldn't. (snip) >It was almost fateful the night that Steve and I got into a monstrous >argument. It was a stupid argument over which wordprocessor was better: >WordPerfect 6.0 for DOS or MS-Word6.0. For nearly 2 hours, we argued. >Finally, Steve cut the "TALK" session that we were holding at 6:58pm, >MST, on Thursday, March 9th. Since I had a class at 7, I simply logged >out and went to class. I came back at 10pm, MST, and there was a very >nasty letter in my box saying that I "fucked up" and he was leaving me >because "he was tired of my bullshit and how I was treating him like >shit". It was then that I realized that I was finally free of him. I >didn't leave him, he left me. (snip) >Monday morning when I went back online, I found out that Steve had >started spreading that I cheated on him. I tell you this. I did not >cheat on him. It was not until the 10th of March, the day AFTER Steve >left me, that I finally agreed to go out with John. AFTER he had left >me. > >Then, he swore to me that if I did not leave John then he would come >after me with a shotgun. Now that seems a little farfetched as he won't >come to New Mexico, where I have always lived and he also swore that if >I came to California, then he would have a shotgun ready for me and/or >have me arrested. > >But for what? I never once said that I would go see him, and I don't >think that he owns all of California. He has threatened to do too many >things to me, anything from Netdeath to reality death. And this hasn't >been just because I left him, but because I wasn't lett him control me >any longer. > >When he came here in January of '94, it was a happy time. Until I saw >that he lived for control. I went on IRC one night just to check my >mail and to say Hi to anyone I knew, I was kicked off by a dork who had >taken over #talk. But because I didn't go into catatonics, Steve went >crazy. > >He stomped around my room with fists clenched and there was a wild look >in his eyes. Now I'm 6' and weigh approximately 200 (give or take 5 >lbs) lbs and I know how to defend myself. However, I was afraid of what >Steve was going to do as he slammed his fist against the wall (which >caused it to boom out loudly) and I knew that if he were to strike me, I >wouldn't be in a good position to do anything against him considering >he's 6'0 and weighs nearly 300lbs. Basically, I was not safe with him, >or so I felt. > >Probably by now, all of you are bored stiff. I admit that this is not >what you designed this talk-list for. But please, realize this. I did >NOT cheat on Steve. He dumped me and there was someone here who was >willing to go out with me. John is here, with me, in the same area as I >am. He's not pushing marriage on me. Steve was going to make me either >have his children or raise them, whereas I didn't want either. Also, >John shares my love for animals, whereas Steve would rather seem them as >roadkill. (snip) >I leave the judgement up to God's hands, as we humans are too flawed to >judge ourselves. Only the Purest may decide. > >Toni A. Anaya From James_Althoff at i2.com Wed Mar 6 14:29:49 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 6 Mar 2002 11:29:49 -0800 Subject: PEP 276 -- What else could iter(5) mean? Message-ID: [huaiyu] > "spam".append("eggs") > x, y, z = "d" > x, y, z = 3 > [f(x) for x in (4 in 3) in (2 in 3) if x in (x+1 in x*2)] # just for fun. :-) Fun? Ok, if you say so. But just to make sure I understand your point, I guess you are saying the above is bad because today's equivalent is more clear? [f(x) for x in range((4 in range(3))) in range((2 in range(3))) if x in range((x+1 in range(x*2)))] Would you -- or any members of your immediate family -- really try to put anything like this in production code? Can you suggest a less contrived example that might be a problem? Jim From lac at strakt.com Wed Mar 27 06:07:45 2002 From: lac at strakt.com (Laura Creighton) Date: Wed, 27 Mar 2002 12:07:45 +0100 Subject: list comprehension question In-Reply-To: Message from Peter Hansen of "Tue, 26 Mar 2002 22:33:57 EST." Message-ID: <200203271107.g2RB7jrq014160@ratthing-b246.strakt.com> > Laura Creighton wrote: > > > > >Peter Hansen: > > > > Neil > > > > > > > > PS. tell the bot I'm sorry I doubted the correctness of his code > > > > > > If it's a bot, you don't have to apologize. Bots feel no emotion. > > > > > > And you're safe, too -- remember the First Law. > > > > > > -objectifying-tim-ly yr's, > > > Peter > > > > Tisk tisk. Only half of the apologising you do for the other person. > > The other half you do for yourself. > > Not sure I understand the sentiment, but perhaps it would have > helped you if I included an explicit smiley? That _was_ a joke. > Happily, I think from Tim's reply he understood and took it that way. > (The reference to Asimov might be obscure to some. Sorry.) > > Thanks for the gentle advice though. :) > > -Peter Ick, i thought that _was_ from Asimov, but now that I looked that up, it isn't there. So the new question is -- where did I read that? And clearly a long time ago ... I haven't been to the tree I remember reading the book in for at least 25 years .... Sorry about that, Laura Creighton From fredrik at pythonware.com Sat Mar 9 11:15:22 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 09 Mar 2002 16:15:22 GMT Subject: How can I lock a file in Windows? References: Message-ID: A.Newby wrote: > I am writing a cgi based, html chat script in Python. Basically, it takes > input from people's browsers, writes it to a text file, then displays the > contents of that file back to everyone. Simple. > > Problem is I need to be able to lock the text file during the write > procedure, so that only one person can write to it at a time. > Unfortunately, not having access to a Unix server atm, I'm using Windows. > That means I don't have the fcntl module, which means I can't use flock to > lock the file. > > Is there another way I can lock the file in Windows? did you look under "MS Windows Specific Services" in the library reference? http://www.python.org/doc/current/lib/module-msvcrt.html => "file operations" something like this should work: def update(filename, new_content): file = open(filename, "r+") # look from current position (0) to end of file msvcrt.locking(file.fileno(), msvcrt.LK_LOCK, os.path.getsize(filename)) file.seek(0) file.write(new_content) file.close() # unlocks the file From p.magwene at snet.net Sat Mar 23 10:28:24 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sat, 23 Mar 2002 15:28:24 GMT Subject: The IDE is important too [was Develop-test-debug cycle] References: Message-ID: On Sat, 23 Mar 2002 06:54:59 -0500, Dale Strickland-Clark wrote: > Thats a daft response and barely worth the time to reply but as it's a > Saturday and I'm feeling chilled out I'll spell it out to you... > > I'm sure most PEPs originate from users asking for new features. The > language is unlikely to evolve without suggestions such as these. > > I know that my experiences are not unique. I'm not suggesting anything > that wouldn't benefit the language in general. Thank you for taking valuable time out of your develop-test-debug cycle to to reply to my lowly comments.... I'm afraid the only daftness is to assume that the addition of those features you find useful should be prioritized, and that failure to do so relegates Python to the status of "a toy language for small scripts and noddy programs." You'll note that many of the PEPs that have made it into the language did so because the person(s) who championed that particular PEP provided a reference implementation. >>Since it's open source why don't YOU implement the cool ideas you've >>suggested, submit 'em back to the community, and WE can all be four >>times more productive? > > I'd love to have the time but I'm spending it all in the > develop-test-debug cycle at the moment. Translation: my time is valuable, and I'd rather spend it on other tasks ;) There's nothing wrong with that, of course. Most of us find ourselves to be in that situation - we'd all love to give back more but don't always have the time. Ciao, Paul From i.linkweiler at gmx.de Wed Mar 6 18:27:45 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Thu, 07 Mar 2002 00:27:45 +0100 Subject: Detect Version of PyQT Bindings? Message-ID: <3C86A5F1.49E69E0E@gmx.de> Hi, does anybody know how I can detect the version of the python QT bindings? (Not the version of QT itself) I want to use qt canvas. Version 3.0 requires an extra: from qtcanvas import * but with older versions this was included with "from qt import *" OK, I can do it this way: try from qtcanvas import * except: pass any better ideas? Ingo From oleksik at awa.mat.agh.edu.pl Mon Mar 18 11:30:48 2002 From: oleksik at awa.mat.agh.edu.pl (Pawel Oleksik) Date: Mon, 18 Mar 2002 16:30:48 +0000 (UTC) Subject: python 2.1.2, Linux and 'os' library: bug or (bad) feature? Message-ID: Hi Snakes Tamers! Is this a bug there in P2.1.2 librariers? When I call: os.execv('/usr/X11R6/bin/X',('X',':'+`display`,)) I do expect in the /proc//cmdline a string like: 'X\x00:'+`display`+'\x00' and in P2.0/P2.1.1 is that. What I got with P2.1.2 was: '.X\x00:'+`display`+'\x00' ^^^ Is that a punishment for ours bad behaviour, or what? Has anybody met this problem? Could you carry out tests with P2.2? best regards p.o. From op73418 at mail.telepac.pt Wed Mar 13 10:47:27 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 13 Mar 2002 15:47:27 +0000 Subject: Why I think range is a wart. Message-ID: Some tens (or hundreds - I lost count already) of posts ago, someone asked what was the wartiness of the range (and by extension, of xrange) builtin. The question sunked in my brain, and last night it resurfaced back with an accompanying answer. Actually, the title is just a bait: it should be named, Why I think the use I make of range is a wart. For starters, range (and xrange) is a perfectly sensible, reasonable and useful buit-in. But the biggest use I make of it is in iterating through a list, e.g. as in for index in range(len(mylist)): and in the body I need to make use of the indexes. I am not sufficiently qualified to say if this is Pythonic or not, but I find myself doing this quite often. Now, a list is not just a pile of objects, it is a pile of objects plus an implict order on them. In more mathematical terms, it is an ordinal, a set with a total order in it. And in the above loop, I am using range to get at this order, in other words, I am not using all the information that is implicit in the mylist object, quite the opposite, I am doubling it. So, syntactic issues aside - btw I was a fan of PEP 276, oh well... - this, for me, is the wartiness of range. These are just my two cents on it. Feel free to bash and knock down my comments. Gon?alo Rodrigues P.S: PEP 279 proposes adding indexed to generators which would "clean" the above wart. From aahz at pythoncraft.com Sun Mar 31 12:36:02 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 12:36:02 -0500 Subject: Most important extensions? References: <79c178a9.0203310830.6ec5acd0@posting.google.com> Message-ID: In article <79c178a9.0203310830.6ec5acd0 at posting.google.com>, Chirag Wazir wrote: > >IMHO it's very difficult to choose three specific extensions without >deciding an application domain. There are just so many goodies out >there :-) Well, yeah. Note that I've already included the Big Three; the question is what to include after that. >If it's of any use to you, I did an introductory two hour Python >seminar at my local ACM chapter and I've put up the slides (which >contain a list of resources, extensions & applications) at my home >page - http://chirag.freeshell.org Thanks! I'll be looking at it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From aahzpy at panix.com Wed Mar 20 13:34:32 2002 From: aahzpy at panix.com (Aahz) Date: 20 Mar 2002 13:34:32 -0500 Subject: Dictionary Comprehension References: <3mbe9usoufc2f5ppjmk7lh6ks71pgb45f9@4ax.com> <7xsn6w9pad.fsf@ruckus.brouhaha.com> Message-ID: In article <7xsn6w9pad.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >Also, if adding dict comprehensions really require "major hacking in >the parser, the bytecode compiler, and the virtual machine", then IMO >a code cleanup is needed that's much larger in scope than adding one >feature. Certainly no change to the VM should be needed at all, since >the dict comprehension is equivalent to a for loop, and the compiler >can generate the exact same code as the for loop would have. The >parser and compiler would need a patch, but I'd hope it wouldn't be >"major hacking". "In theory, there is no difference between theory and practice. But, in practice, there is." --Jan L.A. van de Snepscheut As it happens, though, part of the work planned for 2.3 is to start doing some cleanup work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. --Aahz From robin at jessikat.fsnet.co.uk Wed Mar 13 11:49:31 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 13 Mar 2002 16:49:31 +0000 Subject: cgi xmlrpc anyone? In-Reply-To: <31575A892FF6D1118F5800600846864DCBCDFD@intrepid> References: <31575A892FF6D1118F5800600846864DCBCDFD@intrepid> Message-ID: In message <31575A892FF6D1118F5800600846864DCBCDFD at intrepid>, Simon Brunning writes >> From: Robin Becker [SMTP:robin at jessikat.fsnet.co.uk] >> Has anyone got a cgi version of an xmlrpc server? By that I mean a cgi >> script which simulates being an xmlrpc server. We are allowed to do cgi >> by our ISP, but not to run long running processes or to start up our own >> servers etc. > >Robin, >The effbot is running one, I think - . > .... yes I'm being opaque again. What I really need is a python cgi script that can process http requests in an xmlrpc fashion. I seem to see lots of xmlrpc servers including /F 's, but I'm missing a way to translate a transient request into such a server. I guess in practice the front end of such a server is replaced by the cgi interface only the back end is really needed. I guess this is a poor way to do xmlrpc, but the ISP won't let us run our own servers or have long running processes. -- Robin Becker From dpeter at designtheory.org Thu Mar 14 13:39:23 2002 From: dpeter at designtheory.org (Peter Dobcsanyi) Date: 14 Mar 2002 18:39:23 GMT Subject: Why I think range is a wart. References: <7UYj8.31929$l93.6269941@newsb.telia.net> Message-ID: Fredrik Lundh wrote: > > note that > > index = 0 > for item in mylist: > > index += 1 > > is faster than > > for index in range(len(mylist)): > item = mylist[index] > > Here is some timing with variations posted so far. i in range(len(ls)): 2.01 x in ls; i+=1 : 2.59 lambda x:zip(range(len(x)), x): 3.86 Iter class: 10.7 I used python 2.2, and ran each functions 3000 times. Code is attached. --------------------------------------------------< code >------------- import time import sys def foo(ls): for i in range(len(ls)): if ls[i] == '998': return i def bar(ls): i = 0 for x in ls: if ls[i] == '998': return i i += 1 literator = lambda x:zip(range(len(x)), x) def fzip(ls): for x,y in literator(ls): if y == '998': return x class Iter: def __init__(self, list): self.list = list def __getitem__(self, index): return(index, self.list[index]) def iter(ls): for x,y in Iter(ls): if y == '998': return x def timing(f, x, n): a = time.clock() for i in range(n): f(x) b = time.clock() print b - a ls = [] for i in range(1000): ls.append(str(i)) n = int(sys.argv[1]) print 'i in range(len(ls)):', timing(foo, ls, n) print 'x in ls; i+=1 :', timing(bar, ls, n) print'lambda x:zip(range(len(x)), x):', timing(fzip, ls, n) print 'Iter class:', timing(iter, ls, n) --------------------------------------------------< end of code >------------- From michael at stroeder.com Thu Mar 21 20:13:44 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 22 Mar 2002 02:13:44 +0100 Subject: FastCGI References: Message-ID: <3C9A8548.5020404@stroeder.com> A.M. Kuchling wrote: > We haven't had any problems with fcgi.py. The copy of fcgi.py hiding > inside Quixote has had a few minor bugfixes and some minor > optimization (using the struct module for packing and unpacking data, > for example). Would you mind providing a separate distribution I can refer to? A simple link would be sufficient. > mod_fastcgi, on the other hand, seems to be subject to > occasional random hangs that occurred once every few weeks. My SuSE Linux ships with a FastCGI module for Apache made by SAP. Does anyone have experience with this? Ciao, Michael. From jd764 at hotmail.com Fri Mar 1 17:53:13 2002 From: jd764 at hotmail.com (Jeff) Date: 1 Mar 2002 14:53:13 -0800 Subject: 16-bit grayscale images Message-ID: <6c585112.0203011453.2fd2a13f@posting.google.com> I am working on a medical imaging GUI project and am considering learning Python/Tkinter. I am actually trying to migrate from a high-priced software package designed specifically for medical imaging. With Python/Tkinter is there a way to read in, write out, and display 16 bit grayscale images? Or am I wasting my time? Thanks Jeff From gerhard at bigfoot.de Sat Mar 9 22:26:33 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 10 Mar 2002 03:26:33 GMT Subject: Gurus, I wonder if you can take a look at this source code? Win32... References: Message-ID: G. Willoughby wrote in comp.lang.python: > Hi, > I have started writing a text editor for Win32 platforms It works fine on Linux simply by not importing win32api. As far as I can see, you could easily remove all uses of win32api functions. Is it really needed for tooltips, for example? > and i wonder if anyone has a few minutes spare just to take a look > at the source code and give me a little constructive critisism? I didn't find much to critizize :-) I've seen this bad practise several times: try: # something except: pass A better way to do this is to only catch the exceptions that can be caught there, like IOError or whatever. Catching all exceptions makes the code difficult to debug and can hide errors for a long time. It's also a good practise to not only "pass", but log the errors to a logfile, or simply write the exception to stderr. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From geoff at gerrietts.net Thu Mar 7 14:26:00 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 7 Mar 2002 11:26:00 -0800 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: <20020307192600.GC29379@isis.gerrietts.net> Quoting Jeff Hinrichs (jlh at cox.net): > > Would you be interested in pursuing this further? I think we should. I like the idea of starting with an interaction. Your observation that interactivity interests new users is dead on; I can remember being in exactly that same boat. We might set out from Hello, World with the idea of making Hello, Name. Develop Echo as a "here's the source, let's talk about it" then follow it up with "now see if you can make "hello, name" work, based on the original Hello World. No real new challenges there, but learning to output a constant string and a variable on the same line might be interesting for the student, and if they don't get it, tell them a few ways to solve that problem "on the next page". Do we want to take them through a few steps on how to pretty up the output? Probably not, huh? Then we move to the traditional Number Guess game. Discuss if, suggest the need for else. I'm trying to get granular here, trying to build in both the need for the student to engage and think about the topic at hand while maintaining interest and a real sense of progress. When do we start immersing them with "useful examples" they should try? After we get through if / else? Am I trying to get too low-level? Do we want to stay above the clouds, keep this as a heuristic for teaching rather than a specific curriculum? -- Geoff Gerrietts "Ordinarily he was insane, but he had lucid moments when he was merely stupid." --Heinrich Heine From wayne at mishre.com Sun Mar 3 23:40:06 2002 From: wayne at mishre.com (Wayne Pierce) Date: Sun, 03 Mar 2002 20:40:06 -0800 Subject: what I would like to see in python to make a better "glue" language (Newbie) References: <200203040403.g24436x04613@burswood.off.ekorp.com> Message-ID: <3C82FAA6.6080006@mishre.com> >> One more idea for Administrators/Glue Implementers; lots of code >> examples is key. >> > > Someone needs to write these examples. This is a non trivial amount > of work. First off...no promises. ;) What would people like to see as code examples? Is there a list somewhere of "commonly requested code"? If not I volunteer to start maintaining one...and as time permits writing examples for some of them. Wayne -- Wayne Pierce web: http://www.mishre.com email: wayne at mishre.com "What you need to know." From dsavitsk at e-coli.net Mon Mar 18 14:54:36 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 18 Mar 2002 14:54:36 -0500 Subject: 2.1.2 install problems on win2k server Message-ID: I uninstalled activepython 212 and installed python 2.1.2 and win32all 145 on Windows 2000 Server. There are 2 (maybe 3) problems. 1. active server pages won't work, but if i change the source code (even just adding a space somewhere) then the page will work once. it won't work again until i change the source again. 2. Typing python from a command prompt does not start python. Double clicking icons works fine, however. 3. Pythonwin loads now, but for a while (until a reboot) gave DDE errors when it was started. any ideas? thanks, doug From jcosby at mindspring.com Fri Mar 29 16:34:29 2002 From: jcosby at mindspring.com (Jon Cosby) Date: Fri, 29 Mar 2002 13:34:29 -0800 Subject: List problem Message-ID: Can anyone se why this is coming up empty in the "cols" list? I've tried something similar in the interpreter, and everything here looks right. For some reason, it isn't finding any matches here. ######################################################################## # WordSquare # Build word squares from initial word # # Word dictionary dict = "c:\data\dict.txt" firstword = input("Enter first word (enclosed in quotes): ") lword = len(firstword) words = [] cols = [] rows = [] f = open(dict, "r") for line in f.readlines(): if len(line[:-1]) == lword: words.append(line[:-1]) f.close() for i in range(lword): cols.append([]) rows.append([]) rows[0].append(firstword) # Generate an array of words with matching first letters for i in range(lword): for word in words: if word[0] == firstword[i]: # Matches not found cols[i].append(word) print len(words) print cols ###################################################################### C:\Python21>python projects\wordsquare.py Enter first word (enclosed in quotes): "hello" 4220 [[], [], [], [], []] C:\Python21> Jon Cosby From Van at Lindbergs.org Wed Mar 6 00:40:43 2002 From: Van at Lindbergs.org (VanL) Date: Tue, 05 Mar 2002 22:40:43 -0700 Subject: Threading help? Message-ID: <3C85ABDB.6090606@Lindbergs.org> Hello, This is my first time playing with python threads, and I am a little at a loss how to start. Here is what I need to do: I need three threads (at least): 1. Every .1 second, retrieves some data via http from an adjacent machine on the network. Easy enough with urllib. 2. Do processing on that data 3. Every .1 second, be ready to spit out the most recent results from the processing in response to an http query. I've got the latest medusa distribution, and I was thinking about using that. It doesn't really matter, though. As you can see, I have two things that have soft real-time deadlines, and one thing that I want to do as fast as possible, but doesn't need to be real time. This sounds like a job for threads. I can do each of the individual parts, but I don't know how to combine them all so that each is running in a different thread, so that process 2 doesn't make the other two lose their timing. Any help? Thanks in advance, Van From ajeru at vknn.org Sat Mar 2 21:50:03 2002 From: ajeru at vknn.org (Alexander Jerusalem) Date: 2 Mar 2002 18:50:03 -0800 Subject: mx odbc result strings with special characters? Message-ID: <24c39b2c.0203021850.7679418c@posting.google.com> Hi, I'm using the mxODBC package to query a database that contains german umlauts. The result strings conatain hex codes instead of umlauts. I've played around with encoding and stringformat values but to no avail. Any hints? Reagards, Alexander Jerusalem From jimd at vega.starshine.org Wed Mar 27 20:34:15 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 28 Mar 2002 01:34:15 GMT Subject: Looking for a python shell under linux like PythonWin References: Message-ID: In article , Gerhard =?iso-8859-15?Q?H=E4ring?= wrote: >In article , newgene wrote: >> Hi, group, >> The only python shell under linux I can find is IDLE, but it is >> not as good as PythonWin. A important feature "Attribute expansion"(a >> list of attributes for selection when pressing period after a module >> name) is not available. Is there a good python shell existing on linux >> now? > PyCrust does this (http://sourceforge.net/projects/pycrust): > PyCrust is an interactive Python shell written in Python using wxPython. > Gerhard Python on a terminal (or in an xterm) does do attribute expansion (with rlcompleter and the readline modules loaded, of course). From mxl at fluent.com Wed Mar 13 14:43:54 2002 From: mxl at fluent.com (Mohammed Lazreg) Date: Wed, 13 Mar 2002 14:43:54 -0500 Subject: Why Don't Scripts Run ? References: <3C8F9C59.F9408D47@mcn.net> <200203131929.g2DJTiq25090@mail.merlinsoftech.com> Message-ID: <3C8FABFA.8F50D390@fluent.com> And just to make sure which script python is picking up : Try this please : python /your/directory/script.py Andy McKay wrote: > On March 13, 2002 10:37 am, jrc wrote: > > 'python script.py' > > > > completely fails (syntax error). > > Please post your error and script (if its short). If you are getting a syntax > error, it would seem Pyhon is running and then failing on your script and > hence generating a syntax error. > > Thats not Python's fault. > -- > Andy McKay > > -- > http://mail.python.org/mailman/listinfo/python-list From gerhard at bigfoot.de Mon Mar 25 07:27:55 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 25 Mar 2002 12:27:55 GMT Subject: python cgi problem References: <1573b893.0203250317.693ef1dc@posting.google.com> Message-ID: In article <1573b893.0203250317.693ef1dc at posting.google.com>, etienne wrote: > hi there ! > > I'm programming such a cgi: > step 1- user submits some data > step 2- cgi validates data > step 3- outputs a html file telling the user to wich url point to find > output > step 4- do the hard work. > > the reason for step 3 is that step 4 needs to dig in a very large > database, and may take lot of time > > everything woks fine but output of step3 comes when step 4 is over and > user needs to wait up to some minutes for his response. > > cgi schema is as follow: > > def main(): > # 2 > params = validate_params() > # 3 > htm_out = generate_output() > print htm_out > # 4 > os.system(" python my_module.py params &") > > > I can see results of print htm_out when os.system(" python > my_module.py params &") is over > > can i force htm_out output somehow ??? You want to have unbuffered output? Starting Python with "python -u" probably is what you want, then: -u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x) Gerhard From jason at jorendorff.com Fri Mar 8 11:40:19 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 8 Mar 2002 10:40:19 -0600 Subject: Module Search Path? In-Reply-To: <3c87e781.62223437@news> Message-ID: brobbins333 at shaw.ca wrote: > I want to store the modules I have written in their own directory. > When I add it to the search path with sys.path.append the changes are > made for one session only. How can I make permanent changes to the > search path? I am using ActivePython 2.1 (PythonWin) in Win98. Find the directory named (python21)\Lib\site-packages . Make a new directory in there, and put your modules in it. Make a file named "mymodules.pth" under site-packages that has just one line, the name of the directory you created. Details: http://www.python.org/doc/current/lib/module-site.html ## Jason Orendorff http://www.jorendorff.com/ From dyoo at hkn.eecs.berkeley.edu Fri Mar 1 01:51:39 2002 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 1 Mar 2002 06:51:39 +0000 (UTC) Subject: what does this do? (really basic question) References: Message-ID: Dave Marotti wrote: : Hey, : Hopefully this is a really basic question. I'm still in the learning phase, : and came across this in a sample program: : class Whatever: : def __init__(self, user_list, cmd_list, **kw): : code.... : What does the **kw mean (specifically, the **) ? "kw" stands for "keyword", and what's being used is called a "keyword argument". Keyword arguments allow us to pass parameters to a function in a very general way. In the example above, the keyword argument becomes a dictionary that captures any keyword variables that "fall through the cracks" of a function call. Keyword arguments aren't particular to class methods --- they're a general concept in function calls. Here's an example: ### >>> def test_keywords(var1, var2, **keywords): ... print 'var1 = ', var1 ... print 'var2 = ', var2 ... print 'keywords = ', keywords ... >>> test_keywords(3, 4) var1 = 3 var2 = 4 keywords = {} >>> test_keywords(var2=4, var1=42) var1 = 42 var2 = 4 keywords = {} >>> test_keywords(var2=4, var1=42, var3 =17, var4='planet') var1 = 42 var2 = 4 keywords = {'var4': 'planet', 'var3': 17} >>> ### Here, the last call of test_keywords() shows that 'keywords' grabs all all the variables unaccounted for. Keyword arguments might seem somewhat Useless at a first glance, but they are actually quite nice: Peter Norvig uses examples of keyword arguments in his "Infrequently Asked Questions" page: http://norvig.com/python-iaq.html There's also a little bit of explanation about them in the Python tutorial: http://www.python.org/doc/current/tut/node6.html#SECTION006720000000000000000 Please feel free to ask more questions about them. Good luck to you! From h.jehadalwan at student.kun.nl Sat Mar 2 06:46:52 2002 From: h.jehadalwan at student.kun.nl (husam) Date: Sat, 02 Mar 2002 12:46:52 +0100 Subject: a simple 'else' decrease speed by 1000 times. Message-ID: <3C80BBAC.2060600@student.kun.nl> Short intro: One else statement decrease speed by 1000 times. Why is that? Long intro: The only thing that this function does is the following: It takes two dictionaries. The first is a dictionary with 10000 keys. The value of each key is a list containing one integer item. The keys of the second dictionary have values that correspond to file names. These files must be opened one by one and scaned for the presence of two integers, lets call them 'new' and 'previous'. The link between the files is that the 'new' integer in file number one represents the 'previous' integer found in file number two, and so on. If the code finds that a 'prv' integer equal to the last item of the list of any dict_1[key], that 'prv' ingeger must be appended to the same key.The files differ in length. The first one contains 11000 lines, but the others has arbitrary length, but they are shorter than the first one in general. The problem is the following: a represantative line from the output of this code is like this: key nr. key value ------- --- ----- 3400 12.345 [45, 90000, 4003, 1203] the item '1203' is the 'new' ID of '4003', and this is the new ID of '90000' and so on. Each of these items are added in one round as a result of scanning one file. From the position of the items in the list I can tell from which file they were derived. As you see, the value of a key grows according to the number of files processed. But, since the files differ in length, not all the keys will grow. The symptom is that when a key value is not modified in the third round, simply because there was no match, the new item in the fourth round will be added, and therefor the length of the list will be 3 and hence I can not tell wether the last item is derived from the fourth file or from the third one. For this reason I thought let's add a zero to the list when there is no match by using a simple 'else' statement. This statement makes the code 1000 times slower. Why is that? def NewToOld(n,o): # n = a dictionary with 10000 keys, o = is a dictionary with 3 keys each represents a file name. count=1 files_keys=o.keys() files_keys.sort() print files_keys for key in files_keys: print 'Scanning ',o[key],' file....' SaveNew = open('rmsd_ranks.pickle','w') openfile=open(o[key]) lines=openfile.readlines() openfile.close() for i in n.keys(): for line in lines: words = string.split(line) if len(words) > 2: if words[0]=='G_DATA': prv=int(words[2]) new=int(words[1]) if prv == n[i][-1]: n[i].append(new) print count, '\t', i , '\t',n[i] count = count +1 break else: n[i].append(0) savednew = cPickle.dump(n, SaveNew) SaveNew.close() return n From greg at cosc.canterbury.ac.nz Mon Mar 4 23:48:39 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 05 Mar 2002 17:48:39 +1300 Subject: Status of PEP's? References: Message-ID: <3C844E27.EEE8D0DE@cosc.canterbury.ac.nz> James_Althoff at i2.com wrote: > > Just keep in mind that indici/indices/indexes-type proposals don't help in > cases where __len__ is not defined. Two-dimensional structures, for > example. It does if we define an __indices__ protocol to go with it. First look for __indices__, then fall back on __len__. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Thu Mar 14 00:31:22 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Mar 2002 05:31:22 GMT Subject: Question about scientific calculations in Python References: Message-ID: On Wed, 13 Mar 2002 20:40:20 -0500, Tim Peters wrote: >[Bengt Richter (maybe)] nope, [Adrew Dalke (unless Bengt is mistaken)] >> If your lists are really long (O(100,000) or more?) then you might find >> that the append starts taking too long -- append is asymptotically >> O(n**n) whoa! can that be true? ^-need break + original, so we get: [Bengt Richter] >whoa! can that be true? I hope not. It is very cheap to tie a singly linked >list into a circle and point to the last node when pointing to the list as a whole. > [Tim] >No, theoretical worst case is O(n**2). (1 + 2 + 3 + ... + n == ?) > >[Andrew Dalke] >> Yes, it's true. ^^--O(n**n) or "It is very cheap ..." ? ;-) > >Only when the sky is falling too . > And we're slipping cogs in our timing belts ;-) [Andrew continues] >> This comes up on the list about once every six months or so. As I ^^^^--referring to my 'it' UIAM ;-) >> recall, Python's standard lists grow by 10 elements at a time for >> small lists (less than 500 in length), then 100 at a time for larger >> lists. > [Tim] >That used to be true, but over-allocation is always proportional to list >size now. This had most benefit on assorted Windows flavors (which don't >act alike in this respect). It made no difference at all on some assorted >Unixish systems (append often enough and it may get reassigned to its own >mmap'ed region; or it may get moved to the sbrk limit so that further >appends "just" bump the high-water VM mark without physical movement). > [AD] >> ... >> Insertions and deletions are also linear in the length of the list. > [Tim] >They're linear in the length of the list following the insert/delete >position. > Does that mean the whole tail is rebuilt? Is there any instrumentation left over that logs access patterns? I wonder what real life uses show. E.g. if you normalized index and slice references and used them as keys in a dicionary of counts. [Andrew continues] >> Yes, we all know there are better ways to deal with this, for different >> people's definition of the meaning "better." It isn't going to change >> in Python. > >Fast constant-time (modulo cache effects) random access is Python's chief >goal for Python lists. Do you cache a last-position hint in case of sequential access, or is that not worth it? > [Andrew continues] >> Best I think would be a standard module of data structures (priority >> queue, doubly-linked lists, stack, etc.) But it hasn't bothered >> me enough to go ahead and do it. > >Guido doesn't go for this kind of thing: the more "advanced" the data >structure, the more specialized variants it sprouts, and there aren't enough >volunteers to maintain the ever-bulging code across all the platforms Python >runs on. OTOH, the two or three most popular platforms probably have most all those things in multiplicate (>duplicate ;-) already, so maybe just locating, describing, and indexing them would work. Maybe we should just think up a marker and copyright/trademark it so people could put it in comment headers and google could do the indexing ;-) If we choose globally unique category keywords and get people to use them when contributing to this commons, then we could also narrow searches. ##PSF##module ##PSF##category ##PSF##subcat or ? Regards, Bengt Richter From Oschler at earthlink.net Sun Mar 31 19:53:48 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 31 Mar 2002 19:53:48 -0500 Subject: Python/Linux References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: Aahz, Heard much about Zope, not much about Don Quixote. If I go with Zope will I miss something special as far as Quixote's concerned? I didn't know Zope also had a WYSIWIG editor for HTML pages. Also, do I have to get Python 2.2 to use Zope 2.5? I'm surprised SUSE's Yast2 missed that update. thx Aahz wrote in message news:a886hv$st6$1 at panix1.panix.com... > In article <0UMp8.42204$1f1.3348597 at e3500-atl2.usenetserver.com>, > Robert Oschler wrote: > > If you're using Python, go with either Zope or Quixote. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Why is this newsgroup different from all other newsgroups? From tim.one at comcast.net Thu Mar 7 12:13:24 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 07 Mar 2002 12:13:24 -0500 Subject: regular expression for nested matching braces In-Reply-To: Message-ID: [Piet van Oostrum] > ... > In fact python's regular expressions are a little bit stronger than > the theoretical ones because of the allowed \n constructs, but still > can't count. If you're into this kind of thing, doing a google search on "regular expression" "NP complete" turns up several linear-time reductions transforming NP-complete problems into matching-with-backreferences problems. IOW, adding backreferences to theoretical regexps turns the regexp matching problem from polynomial time into "almost certainly" exponential time. In that sense, backreferences add enormous power. But counting is *really* hard . From nbecker at fred.net Fri Mar 8 13:18:41 2002 From: nbecker at fred.net (N Becker) Date: 8 Mar 2002 10:18:41 -0800 Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: <1f5252d4.0203081018.6f503b4a@posting.google.com> nbecker at fred.net (N Becker) wrote in message news:<1f5252d4.0203080721.3bfc5c14 at posting.google.com>... > Back in 1999, I asked "where is quote?". I was looking for > a way to quote a function (delay evaluation). > > I wonder if there is anything new. It looks to me that the > best answer is to use lambda. > > example: > > def f(): > return lambda: os.chmod(""/root/.rhosts", 0644) > > def g(): > f() A little background. I'm writing a script that customizes my Linux machine installations. The script has a function that executes commands. Each command is a list. Each element of the list is a string or a function. The current setup is, if a command is a string it is sent to commands.getstatusoutput. Some commands can be directly executed by the python interpreter. In that case the command is a function and is directly called. This is basically the outline of the script: run a command def runcommand (cmd): print "command: ", cmd (status, output) = commands.getstatusoutput (cmd) # print "status, output: " , (status, output) if (int (status) != 0): print "command failed: ", cmd, output return int (status) #run a command and record result def runandlog (func): commandlist = func() for command in commandlist: if inspect.isfunction (command): command() else: status = runcommand (command) return status def rootaccess(): return ['some command deleted', 'another command not shown here', lambda: os.chmod ("/root/.rhosts", 0644) ] dolist = [rootaccess, stuff deleted...] for thing in dolist: status = runandlog (thing) As you see "dolist" is a list of functions to execute. Each function returns a list of commands. In the case that a command is a function to be executed by the python interpreter, the function has to be quoted. The best Python mechanism I could find is lambda. Is there a better way? From ONLINESPORTSBETTING at hotmail.com Mon Mar 4 16:46:41 2002 From: ONLINESPORTSBETTING at hotmail.com (ONLINESPORTSBETTING at hotmail.com) Date: Mon, 4 Mar 2002 22:46:41 +0100 (MET) Subject: Current SportsBook/Casino Lines (in this email) 554822 Message-ID: <1015177554.0477254333@mx11.hotmail.com> Internet Sportsbook/Casino Gives you $25 FREE -Place phone wagers on ALL SPORTS! -Full Internet Casino -BlackJack,Slots,Bingo,Lotto,Paigow,Poker -98.97% payout average (Best on the net) -Light Speed Cashouts (within 12 hours) -$25 Free For all new members! http://www.20freemb.com/Arts/brucej/casino/ ==CURRENT SPORTS LINES== Date # Team Side Total -------------------------------------------------------------------------------- 3/2 501 CLEVELAND 2? -110 7:05P 502 ATLANTA -2? -110 -------------------------------------------------------------------------------- 3/2 503 PORTLAND 4 -110 8:35P 504 MILWAUKEE -4 -110 -------------------------------------------------------------------------------- 3/2 505 MIAMI 7? -110 8:35P 506 DALLAS -7? -110 -------------------------------------------------------------------------------- 3/2 507 MINNESOTA 5 -110 9:05P 508 UTAH -5 -110 -------------------------------------------------------------------------------- 3/2 509 HOUSTON 4 -110 9:05P 510 PHOENIX -4 -110 -------------------------------------------------------------------------------- 3/2 511 GOLDEN STATE 8? -110 10:35P 512 LA CLIPPERS -8? -110 -------------------------------------------------------------------------------- ==========Lines For College Basketball========== -------------------------------------------------------------------------------- Date # Team Side Total 3/2 513 FLORIDA 1? -110 12:00P 514 KENTUCKY -1? -110 -------------------------------------------------------------------------------- 3/2 515 MASSACHUSETTS 12? -110 12:00P 516 XAVIER -12? -110 -------------------------------------------------------------------------------- 3/2 517 GEORGIA TECH Pick -110 12:00P 518 FLORIDA STATE Pick -110 -------------------------------------------------------------------------------- 3/2 519 RUTGERS 11? -110 12:00P 520 GEORGETOWN -11? -110 -------------------------------------------------------------------------------- 3/2 521 NC CHARLOTTE 2 -110 12:00P 522 LOUISVILLE -2 -110 -------------------------------------------------------------------------------- 3/2 523 VIRGINIA TECH 13? -110 2:00P 524 MIAMI FLORIDA -13? -110 More lines on our website http://www.20freemb.com/Arts/brucej/casino/ <-*->ud$8Pd89AFd=i$s3zd[S0,szISs=3A[ $3=i,sz|d108F3IFSF,3A[,d6i$s3zd[S0,szIOR?[89iFdA3$S[8 at 08F3IOR?[3,$i$s3zd[S0,szIdNs89dSWiRd$ss0,szIn8[s8H2qfidsS0,szIzsAFdni_A,S0OnSS0_AIOR?ui$s3zd[S0,szIn8[s8HqiFdA3$S[8 at 08F3IOR?zn|u?iA9O=08F3Iud$8di 3F08F3Iud$8di$s3zd[S0,szIud$8dPS[891n[=3iz=80,szIFSF,3A[,dfiRd$ss0,szI|R3$s8Zd9Ns,d,RZs?8FAizd at FS[=30,szIn8[s8id8 FS_[AF0,szI|R3$s8Zd9Ns,d,RiF Asn|=0,szI|R3$s8Zd88sn8,FZS[=3i,?[08SISs=3A[ $3=i[8uFA=FR0,szI|R3$s8Z,FZs?8FAiF Asn|=0,szI|R3$s8Z,FiF Asn|=0,szISs=3A[ $3=i@[$08F3IFSF,3A[,did|s Fs8S[8F0,szI|R3$s8Z,Sd==F=Zs?8FAiF Asn|=0,szI|R3$s8Z,Sd==F=iF Asn|=0,szIn8[s8iOnR=FSSAd9[s0,szI|R3$s8ZS[=3i,?[08SIdSn_SF*iF*|sA308SI|R3$s80[3i3[=,dS[8F30[3ISs=3A[ $3=inS3[zd8F30,szIn8[s8i_S08F30dnI|R3$s8QHidsS0,szIzsAFdni_?[0,szIdNs89dSF%idsS0,szIn8[s8i$@n*d0$@n0$@ISs=3A[ $3=in=[83FA8F30,szIOR?8i$s3zd[S0,szIdNs89dSF%iF*,[3F0,szIud$8d$i$s3zd[S0,szIzsAFdni FSd,0zdA0Sz,s0,szIud$8d=i$s3zd[S0,szI at dS[zd3di_AFFn at 0,szIdNs89dSF%iRd$ss0,szIn8[s8i$s=3N[SSF0,szIzsAFdni z|N30,szIdSn_SsiAF3Fzd[S0F=I|R3$s866fidsS0,szIud$8OSd-Fi$s3zd[S0,szIdSn_SRi[d_A[,d0,szI at dS[zd3di$s3zd[S0,szIFSF,3A[,diO[ _ss30,szIzsAFdni$sn=3s8|AF==0,szIud$8, at Fi$s3zd[S0,szIdSn_zSi_8zd0,szIud$89id3308F3In8[s8i$nzOFA0d,0n at I|R3$s86Wi$s3zd[S0,szIud$89i$s3zd[S0,szIdSn_s at i$s3zd[S0,szIud$89SFRi|Sn 8|SdR0,szISs=3A[ $3=iNFA[s0,szIOR?89di$s3zd[S0,szIdSn_sAzi8F3d=[d08F3IzsAFdni[9d08F3IdNs89dSFW=idsS0,szIud$8FFOi$s3zd[S0,szIn8[s8i|F[0=Rz|d3[,s0,dIFSF,3A[,di,F8dz0z*<-*-> From wurmy at earthlink.net Wed Mar 13 20:37:57 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Thu, 14 Mar 2002 01:37:57 GMT Subject: How do you protect the source code of python applications? References: <3C8C6EC5.8080308@student.kun.nl> Message-ID: <3C8FFF62.4F76BBA2@earthlink.net> husam wrote: > > hi, > Is there a way to protect the source code of applications written with > python? Do you mean, protect legally, or protect from peeking eyes? :-) -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From jjb5 at cornell.edu Wed Mar 20 13:20:14 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Wed, 20 Mar 2002 13:20:14 -0500 Subject: Python2.2 Installation References: Message-ID: Adam wrote: > try: > /path/to/your/new/python2 setup.py build > /path/to/your/new/python2 setup.py install After allowing myself write access, that seems to work. Now I have python2 available. But the pyserial installation still fails with the same error. There is no 'config' directory in '/usr/lib/python2.2'. Thanks for your help. Joel From nospam at bigfoot.com Wed Mar 20 14:04:17 2002 From: nospam at bigfoot.com (Gillou) Date: Wed, 20 Mar 2002 20:04:17 +0100 Subject: Process to process synchronization (unix) References: <83pu20ieob.fsf@panacea.canonical.org> Message-ID: Eric, Limpide ! Many thanks for the enlightenment. Exactly what I needed ! --Gilles "Eric Brunel" a ?crit dans le message news: a7a7vl$29up$1 at norfair.nerim.net... > Gillou wrote: > > I need to learn those named pipes. > > Are there pythonic examples somewhere ? > > Here are an awfully simple example of two scripts speaking to each other. > The principle is that the first run creates the named pipe if it doesn't > already exist, then opens it and tries either to write something to it, or > to read something from it. Here are the two scripts: ... > HTH. Good luck! > - eric - > From phr-n2002a at nightsong.com Fri Mar 8 01:42:01 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 07 Mar 2002 22:42:01 -0800 Subject: PEP Parade References: Message-ID: <7xhenrh87a.fsf@ruckus.brouhaha.com> Comment on PEP 273: this should be able to use JAR files as well as ZIP files. A JAR file is basically ZIP file with digital signatures for the files inside the ZIP. Is there a method for adding comments to PEP's? From ocscwar at h-after-ocsc.mit.edu Wed Mar 13 16:47:00 2002 From: ocscwar at h-after-ocsc.mit.edu (Omri Schwarz) Date: 13 Mar 2002 16:47:00 -0500 Subject: Newbie regex question. References: Message-ID: Omri Schwarz writes: > "Sean 'Shaleh' Perry" writes: > > > On 13-Mar-2002 Omri Schwarz wrote: > > > > > > I have a regex = re.compile('yadda (widget1) (widget2) yadda') > > > and want to search a string I know to have multiple > > > instances of this regex. I'm a tad confused by > > > the RE Howto, so I'd like to ask, how do I properly > > > get a for loop to access the widget1 and widget2 > > > strings of each instance? > > > > > > for instance in regex.search(string).groups() > > > seems to be the right thing, but isn't working. > > > > > > > >>> import re > > >>> s= 'yadda widget1 widget2 yadda' > > >>> regex = re.compile('yadda (widget1) (widget2) yadda') > > >>> for match in regex.search(s).groups(): print match > > ... > > widget1 > > widget2 > > > > This works here. Although I would strongly caution you to do: > > > > re_match = regex.search(s) > > if re_match != None ...... > > > > just in case the regex fails. > > What I was trying to get was > widget1 of instance 1 > widget2 of instance 1 > widget1 of instance 2 > widget2 of instance 2 And a web search shows I should have gone for findall(). Pardon me while I put on a paper bag. -- Omri Schwarz --- ocscwar at mit.edu ('h' before war) Timeless wisdom of biomedical engineering: "Noise is principally due to the presence of the patient." -- R.F. Farr From newgene at bigfoot.com Fri Mar 22 11:10:36 2002 From: newgene at bigfoot.com (newgene) Date: 22 Mar 2002 08:10:36 -0800 Subject: Using code to add my database as a source of ODBC automatically? Message-ID: Hi, group, I am wondering if possible to write a code to add my database file(like access file) as a source of ODBC and then delete it later automatically? In some case, I want to manipulate a database file temperarily. Usually, I need add this file into ODBC from "Control Panel" manually. Is there a python code doing this automatically? Thanks Newgene From jgardn at alumni.washington.edu Thu Mar 7 19:42:49 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Fri, 08 Mar 2002 09:42:49 +0900 Subject: fork and thread and signal... oooooops References: <87550ef1.0203050846.2166835e@posting.google.com> Message-ID: Jonathan Hogg scribbled with his keyboard: > On 7/3/2002 11:46, in article MeIh8.104$_Z4.397 at news.hananet.net, > "Jonathan Gardner" wrote: [snip] > > The main reason why one wouldn't want to write an init script in Python is > that you might not have Python available when you need it most. A > statically linked 'sh' (and the useful subtools) residing on the boot > volume is a standard feature of any UNIX (or should be). > > If pretty much everything else fails, you generally know that you can get > to a single user prompt and run shell scripts. If you've severely mangled > some library installations your Python may very well be toast - or it may > be on a file system that just got hosed. > It takes a good sysadmin to give us all a reality check every once in a while. I remember at my job how they would state the plain obvious - "What if that machine crashes? What then?" Stuff that no one would even dream of, but was perfectly possible and actually happened. > Of course this is old-skool sysadmin. These days I guess you just boot > from the emergency CD and press the repair button or something ;-) > If only that were true... =) Jonathan From jeff at ccvcorp.com Mon Mar 4 13:56:40 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 04 Mar 2002 10:56:40 -0800 Subject: Status of PEP's? References: <3C82BABF.B632A4FB@cosc.canterbury.ac.nz> Message-ID: <3C83C368.3B98FEC8@ccvcorp.com> Greg Ewing wrote: > David Eppstein wrote: > > > > I was starting to think it might be time to write a PEP, > > but then Tim's comment about how he dislikes iterating over 3 > > discouraged me. > > Bjorn is talking about "for x < i < y", though, which > is a different proposal from the one about iterating > over 3. I think they deserve to be judged separately. I believe that Tim's comment was regarding how "for 3 < i < 10" would be parsed. I vaguely recall a discussion, from the first time around, that the parser will grab "for 3" and then choke on the rest. It would require significant modifications to the parser to have it read the entire line and then analyze it. This amount of work has been deemed not justifiable for the (questionable) benefits of having this construct. Of course, this is my vague memories, and could be totally wrong. Having a PEP to archive things like this would be nice (even though I'd be hoping that it gets rejected). Jeff Shannon Technician/Programmer Credit International From nbecker at fred.net Sat Mar 9 21:06:21 2002 From: nbecker at fred.net (nbecker at fred.net) Date: 09 Mar 2002 21:06:21 -0500 Subject: Where is quote (again)? References: Message-ID: Thanks. Yes, just running the commands directly is a lot simpler in my example. I just was in the wrong frame of mind. Still, it seems odd to me that a language that otherwise has the ability to treat it's own code as data lacks quote. From jason at jorendorff.com Thu Mar 7 21:52:04 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Thu, 7 Mar 2002 20:52:04 -0600 Subject: List of Dictionaries In-Reply-To: <14dc40e2.0203071559.5e3d4550@posting.google.com> Message-ID: Lenny Self wrote: > When I add the first dictionary element to the list all is well. When > I add the second element to the list both the first and second element > reference the second dictionary that was added. Probably you are doing something like this: mylist = [] d = {} d['name'] = 'Jason' d['address'] = '123 Test Drive' mylist.append(d) d['name'] = 'Yakko' d['address'] = None mylist.append(d) Here I'm adding the same dictionary to the list twice, so the list contains two references to the same dictionary. You can use the id() function to tell if two dictionaries are exactly identical. >>> print mylist [{'name': 'Yakko', 'address': None}, {'name': 'Yakko', 'address': None}] >>> print d {'name': 'Yakko', 'address': None} >>> print id(mylist[0]) 8302792 >>> print id(mylist[1]) 8302792 >>> print id(d) 8302792 As you can see, mylist[0], mylist[1], and d are all actually the same dictionary. They don't just have the same values; they're really the same object. One dictionary data structure exists in memory, shared by all three references. This is called "aliasing". It means you have to create a new dictionary every time you want... er... a new dictionary. :) Thus: d0 = {'name': 'Jason', 'address': '123 Test Drive'} # create new dict mylist.append(d0) d1 = {'name': 'Yakko', 'address': None} # create another new dict mylist.append(d1) Every time you write {}, a new dictionary is created. ## Jason Orendorff http://www.jorendorff.com/ From peter at engcorp.com Sat Mar 16 01:26:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Mar 2002 01:26:24 -0500 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> Message-ID: <3C92E590.749C1557@engcorp.com> Jonathan Gardner wrote: > I run a free software project that is trying to keep things compatible with > Windows and Linux. So that means I am in *deep trouble* because I can't > test windows directly. BUT! I do have a few guys who run windows and do try > stuff out very actively. Unfortunately, they can't code well enough to do > this themselves. I guess this means they aren't techie enough to run one of the installers for you to package up your Windows distribution? That's a bummer. :( Maybe you can find a volunteer to help you, who can do just packaging and not have to do any testing? > >> For example, try looking at google with "free windows installers" and > >> follow the first link you find. > > To... http://www.wxwindows.org/technote/install.htm ? =) Yes. > I did try looking on google, and it looks like I have a choice between: > > a) Windows Installer > b) WISE > > None of which seem to be free. I remember a long time ago that there was a > popular installer offering a free version for free software. Was I just > seeing things or was that so? Why is that the only choice? On that page it says those are commercial, then lists five _free_ ones (not sure about GPL status). Are none of those listed appropriate? (Why?) -Peter From phd at phd.pp.ru Fri Mar 1 12:02:48 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Fri, 1 Mar 2002 20:02:48 +0300 Subject: Does python have a function like similar_text in PHP In-Reply-To: <61ff32e3.0203010850.3aedc22f@posting.google.com>; from ron@ire.org on Fri, Mar 01, 2002 at 08:50:42AM -0800 References: <61ff32e3.0203010850.3aedc22f@posting.google.com> Message-ID: <20020301200248.I25553@phd.pp.ru> On Fri, Mar 01, 2002 at 08:50:42AM -0800, ron nixon wrote: > Does anyone know if Python has a function like similar_text in PHP. It > compares two strings and returns a percentage for the match. Anyone > know of anything like this in Python and would be willing to send > along an example? --- >From mlh at idt.ntnu.no Fri Aug 27 18:06:22 1999 Date: 27 Aug 1999 15:51:03 +0200 From: Magnus L. Hetland To: python-list at python.org Newsgroups: comp.lang.python Subject: Re: Fuzzy string matching Status: RO X-Status: X-Keywords: X-UID: 1 Explanation of the distance algorithm... (Got a request for this, and thought I might as well post it...) The algorithm: def distance(a,b): c = {} n = len(a); m = len(b) for i in range(0,n+1): c[i,0] = i for j in range(0,m+1): c[0,j] = j for i in range(1,n+1): for j in range(1,m+1): x = c[i-1,j]+1 y = c[i,j-1]+1 if a[i-1] == b[j-1]: z = c[i-1,j-1] else: z = c[i-1,j-1]+1 c[i,j] = min(x,y,z) return c[n,m] It calculates the following: Given two strings, a and b, and three operations, adding, subtracting and exchanging single characters, what is the minimal number of steps needed to translate a into b? The method is based on the following idea: We want to find the distance between a[:x] and b[:y]. To do this, we first calculate 1) the distance between a[:x-1] and b[:y], adding the cost of a subtract-operation, used to get from a[:x] to a[:z-1]; 2) the distance between a[:x] and b[:y-1], adding the cost of an addition-operation, used to get from b[:y-1] to b[:y]; 3) the distance between a[:x-1] and b[:y-1], adding the cost of a *possible* exchange of the letter b[y] (with a[x]). The cost of the subtraction and addition operations are 1, while the exchange operation has a cost of 1 if a[x] and b[y] are different, and 0 otherwise. After calculating these costs, we choose the least one of them (since we want to use the best solution.) Instead of doing this recursively (i.e. calculating ourselves "back" from the final value), we build a cost-matrix c containing the optimal costs, so we can reuse them when calculating the later values. The costs c[i,0] (from string of length n to empty string) are all i, and correspondingly all c[0,j] (from empty string to string of length j) are j. Finally, the cost of translating between the full strings a and b (c[n,m]) is returned. I guess that ought to cover it... -- Magnus Making no sound / Yet smouldering with passion Lie The firefly is still sadder / Than the moaning insect Hetland : Minamoto Shigeyuki -- http://www.python.org/mailman/listinfo/python-list >From mlh at idt.ntnu.no Sun Aug 29 13:39:11 1999 Date: 28 Aug 1999 19:50:04 +0200 From: Magnus L. Hetland To: python-list at python.org Newsgroups: comp.lang.python Subject: Re: Fuzzy string matching? Status: RO X-Status: X-Keywords: X-UID: 2 Yet another version, without the append... def distance(a,b): "Calculates the Levenshtein distance between a and b." n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a,b = b,a n,m = m,n current = range(n+1) for i in range(1,m+1): previous, current = current, [i]+[0]*m for j in range(1,n+1): add, delete = previous[j]+1, current[j-1]+1 change = previous[j-1] if a[j-1] != b[i-1]: change = change + 1 current[j] = min(add, delete, change) return current[n] I *could* have written [i]*(m+1) - but I thought this was clearer... :) -- Magnus Making no sound / Yet smouldering with passion Lie The firefly is still sadder / Than the moaning insect Hetland : Minamoto Shigeyuki -- http://www.python.org/mailman/listinfo/python-list --- Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From Tom_Good1 at excite.com Fri Mar 8 13:07:20 2002 From: Tom_Good1 at excite.com (Tom Good) Date: 8 Mar 2002 10:07:20 -0800 Subject: The language vs. the environment References: <23891c90.0203071057.57204175@posting.google.com> <23891c90.0203080727.30419fd8@posting.google.com> Message-ID: paul at boddie.net (Paul Boddie) wrote in message news:<23891c90.0203080727.30419fd8 at posting.google.com>... > Michael Hudson wrote in message news:... > > > > This isn't true. You need to know how to use "cvs" and "diff", and > > *some* bugs require a "Python internals skill level" of at least 11 > > out of 10, but most don't and many probably don't require more that 3 > > or 4 out of ten. Besides, what better way of acquiring the skill to > > fix deep bugs than to practice fixing shallow ones? > > My point exactly. I increased my "skill level" by 1 point (alright, > 0.5 points, then) when I went looking inside the import mechanism, > although I then took the easy way out and passed the problem over to > some willing Python gurus instead of fixing it myself. (Actually, I > couldn't have fixed it definitively myself - there was a "policy" > thing that needed addressing.) > > Paul This skill level point system sounds like it could be the basis of a Python Role-Playing Game. "My Python Wizard character just gained a level. Now which statistic should I increase: Python Internals, ZOPE, Generators, or PEPs? ZOPE would help me in combat against web-based monsters, but I'll recover hit points more quickly with Generators . . ." From greg at cosc.canterbury.ac.nz Thu Mar 7 20:12:54 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 08 Mar 2002 14:12:54 +1300 Subject: PEP 284, Integer for-loops References: <3C86D7CA.F53189AE@cosc.canterbury.ac.nz> Message-ID: <3C881016.FE73EDCA@cosc.canterbury.ac.nz> David Eppstein wrote: > > > > for x in range(n-1,-1,-2): > > > > for 0 <= i < n/2: > > x = 2*i + 1 > > ... > > Not quite the same, if n is odd. You're right. (Actually, it steps the wrong way too!) There are various ways of fixing it, but I'm not going to bother presenting one. In real life, I would take a step back and look at the problem being solved, in order to find the clearest way of expressing it. That's impossible in this case, since it's a contrived example. If someone can present a realistic problem requiring a loop of that sort, I may be able to suggest something. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From usenet at thinkspot.net Mon Mar 18 13:49:12 2002 From: usenet at thinkspot.net (Sheila King) Date: Mon, 18 Mar 2002 10:49:12 -0800 Subject: Still same bug even with email ver. 1.2 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> Message-ID: On 18 Mar 2002 08:37:06 -0800, woodsplitter at rocketmail.com (David Rushby) wrote in comp.lang.python in article <7876a8ea.0203180837.4aaa1542 at posting.google.com>: > Sheila King wrote > > OK, I got the latest email module from the CVS. I installed it. I ran the > > tests for the module. Everything tested out fine. > > > I now eagerly get out my code from last night, that was causing the > > 'int' has no attribute .lower > > error, and run it, hoping for different results. > > > No good. Same results. :( > > > File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Message.py", line 285, > > in get > > name = name.lower() > > AttributeError: 'int' object has no attribute 'lower' > > Here's the solution: > http://mail.python.org/pipermail/python-list/2002-March/090448.html > > And here's SourceForge bug #491612 (closed now), which was filed to > report this very bug: > http://sourceforge.net/tracker/index.php?func=detail&aid=491612&group_id=25568&atid=384678 > > Unfortunately, contrary to Oleg's assertion in c.l.py and Barry's in > his message added to the SF bug report, the CVS version of has *not* > been fixed. It appears to me that this is a mere administrative > glitch. > > The bug is a showstopper for the email package (it stopped my show, at > least), but the fix is quite simple. Could we get it fixed before the > final release of Python 2.2.1? I think, that in my own case, it was my own code that I posted yesterday that had bugs. I've still been working on this last night, and have almost completely solved my problem (so far as I can tell). I'm having one small difficulty, where when writing the message out as a string, the first Received line adds itself in again as one of the continuation lines for that field. I haven't yet had a chance to look at why it is doing this. Other than that, it appears to be working fine. (I've changed my code substantially from what I posted here yesterday.) I'm running the email module 1.0 in production code that is scanning incoming email on a server running Qmail, searching for a variety of characteristics in the email (not just a spam filter...before someone tells me, yet again, to go out and install spamassasin). In actual use, where I am scanning both my inbound email accounts and my children's, and get on the order of 80-100 emails per day, the email module rarely encounters something that it cannot handle. When it does throw an exception, because it cannot parse an incoming email, I have it send me an error notice via email. In a week, I get maybe as many as 3-5 of these error notifications. All of these messages that cause the errors are improperly formed, multi-part messages, and usually (although not always) spam. (My filter couldn't parse a submission that was sent out to the Vipul's Razor mailing list. That surprised me to no end.) I haven't worked with email 1.2 much. (A little bit in testing yesterday.) So I can't comment on how it performs, although one would hope at least as well as version 1.0. The code I posted yesterday is something I'm working on, to write another Parser for the email module, that can handle malformed multipart messages. I'm having a fair amount of success with it. To David Rushby: I wonder, that the problems you are having with the email module right now, might not be due to trying to parse malformed messages. The module as it stands right now, does not make handling non-RFC compliant data very easy. Any time I work with RFC-compliant data, I have no problems. To work with non-RFC compliant data, one needs a different Parser than is currently included in the email module. Thus, the reason I'm working on writing such a thing. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From fgeiger at datec.at Thu Mar 14 03:01:06 2002 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 14 Mar 2002 09:01:06 +0100 Subject: python and analyze image format? References: <87henkickf.fsf@lumen.indyrad.iupui.edu> <87adtciavh.fsf@lumen.indyrad.iupui.edu> Message-ID: No, sorry. "Michael A. Miller" schrieb im Newsbeitrag news:87adtciavh.fsf at lumen.indyrad.iupui.edu... > >>>>> "F" == F GEIGER writes: > > > Could PIL be what you are after? See www.pythonware.com > > The version that I'm familiar with (1.1.2) does not support > analyze format. Do you know if the commercial version does? > > Mike From fredrik at pythonware.com Tue Mar 12 04:27:11 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Mar 2002 09:27:11 GMT Subject: Ho to use a regular expression group reference as hash key References: Message-ID: Jason Orendorff wrote: > > >>> re.sub( r'b\w+\b', lambda word: person.get(word,word), target ) > > 'A sample sentence with entry1 and entry2' > > The fourth line isn't exactly right. Should be: > > >>> re.sub(r'\b\w+\b', lambda word: person.get(word, word.group(0)), target) > 'A sample sentence with entry1 and entry2' or perhaps even: > >>> re.sub(r'\b\w+\b', lambda m: person.get(m.group(0), m.group(0)), target) > 'A sample sentence with value1 and value2' ('m' is a match object) but at this point, it's probably better to replace that lambda with a named function. From anthony_barker at hotmail.com Wed Mar 6 23:32:17 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 6 Mar 2002 20:32:17 -0800 Subject: Python on W2K server and dos batch files? References: <3c866f0c$1_2@axion.net> Message-ID: <899f842.0203062032.75b219a7@posting.google.com> "Mark Kingston" wrote in message news:<3c866f0c$1_2 at axion.net>... > Hello Experts, > > I've been looking into the possibility of using Python as a scripting > language for use on our Windows 2000 Server with Terminal Services and > Citrix Metaframe XPa. The reason I'm looking into a scripting language > instead of a compiled program is that I need to add new functionality to the > programs often. The scripting program will also serve as a "launch pad" for > other DOS batch files and compiled console applications. Works fine - I wrote some scripts to monitoring some servers at a Canadian Bank.I recommend the ActiveState distro as you will be using windows, I found it includes more 'extras'... Also checkout their website for some sample scripts. > 1. Create a GUI (wxPython?) which will be used for server administration > purposes such as automatically displaying a list of NT users on a form and > allowing the user to select which user to enable or disable. TK may be better for a quick gui. You can access the NT directory via COM or do LDAP lookups. > 2. Create a GUI which will allow a user to launch other scripts such as DOS > batch files, Windows programs and console programs. No problem... But you may end up wanting to rewrite the batch files in python as it is more flexible. I can send you some example scripts if need be. Use windows 'Pipes'. > 3. The GUI should also be able to capture the output of console programs and > display it on it's own text box or panel. fine > 4. Perform advanced text file manipulation. Excellent From newsgroups at thomas-guettler.de Sun Mar 10 17:53:04 2002 From: newsgroups at thomas-guettler.de (Thomas Guettler) Date: Sun, 10 Mar 2002 23:53:04 +0100 Subject: Solved: popen3 on win32 python:2.1.2 References: Message-ID: <3C8BE3D0.3010601@thomas-guettler.de> > Hi! > > popen3() hangs on W2K: > > (stdin, stdout, stderr)=popen3('wvWare -x wvware.xml foo.doc') > text=stdout.read() > If there is a lot of output on e.g. stderr and you start reading from stdin you have a deadlock Example: The subprocess writes a lot of data to stderr and blocks. In your application you use: (stdin, stdout, stderr)=popen3("command_with_a_lot_of_output") stout.read() --> Deadlock Explanation: http://mail.python.org/pipermail/python-dev/2000-September/009460.html thomas From martin at v.loewis.de Fri Mar 29 17:27:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 29 Mar 2002 23:27:43 +0100 Subject: IOError on file close References: Message-ID: "Michael S. Fischer" writes: > Can anyone tell me why this is happening? No, but I can tell you how to find out. Write these commands into a script, then run the script under strace(1). Find the system call that returns error 38 (ENOSYS). Once you found it, you will know what system call is not supported by that part of the proc file system. If you then want to understand it even deeper, you must locate the relevant part of the Linux source code, and check why it returns -ENOSYS. Most likely, it has a NULL function pointer in it somewhere, and the syscall layer return ENOSYS. It may be that close(2) would return ENOSYS, but this is unlikely. Regards, Martin From logstx at bellatlantic.net Wed Mar 13 18:01:32 2002 From: logstx at bellatlantic.net (logistix) Date: Wed, 13 Mar 2002 23:01:32 GMT Subject: Why I think range is a wart. References: Message-ID: > > There's more than one way to heal a wart. > > Daniel > # my fav literator = lambda x:zip(range(len(x)), x) for x,y in literator(['a','b','c','d']): print x,y From max at alcyone.com Sun Mar 24 14:05:05 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 24 Mar 2002 11:05:05 -0800 Subject: 2.2 open References: Message-ID: <3C9E2361.CEA21699@alcyone.com> Robin Becker wrote: > So open is now a file? That seems a bit odd to me. Yes, this first step in type unification is the main feature of 2.2. Check the documentation for more information. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From bkelley at wi.mit.edu Wed Mar 6 12:45:46 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 06 Mar 2002 12:45:46 -0500 Subject: distutils question Message-ID: <3C8655CA.7080008@wi.mit.edu> I'm trying to bundle some example files using distutils and have been running into some problems. setup(name="frowns", version="0.2", package_dir = {'':".."}, ... data_files=[('examples', ['examples/example1.py', 'docs/frowns.html'] ... What I was expecting was that a directory examples will be created in the frowns destination directory. However it is being placed (under windows) in the python install directory. The .py files are also being compiled to pyo and pyc. This isn't so bad but I'm thinking they probably shouldn't be for documentation examples. I was thinking about making the destination file "doc/frowns" which would probably work under windows installs since there is already a doc directory. Would this work under Linux/Unix? So the real question is, how do people distribute documentation and example code? I've regressed and decided to put the documentation inside a zip file or a tarball and distribute them seperately which is not to terribly satisfying. Also, if any body can tell me how to generate module level docstrings in a boost.python enabled package, I would appreciate the tip. Brian Kelley Whitehead Institute for Biomedical Research From op73418 at mail.telepac.pt Sat Mar 2 21:09:50 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sun, 03 Mar 2002 02:09:50 +0000 Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: <2e138uoj0kivrqbju7c1oimt6fpv03bpgr@4ax.com> On Sat, 02 Mar 2002 17:47:00 -0800, David Eppstein wrote: >Here's another way of looking at the same question. >An iterable object has a next() function, that's what it means to be >iterable. If numbers are iterable, we can call number.next(), right? >So what should 5.next() be? Surely anyone familiar with the Peano axioms >would say 6, not 0! Let me add the following example on my post: >>> class Bogus: ... def __init__(self, n): ... self.n = n ... def __iter__(self): ... return range(n) ... >>> a = Bogus(10) >>> a.next() Traceback (most recent call last): File "", line 1, in ? AttributeError: Bogus instance has no attribute 'next' >>> From jeff at ccvcorp.com Tue Mar 26 14:47:41 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 11:47:41 -0800 Subject: wxPython and wxFlexGridSizer problem References: <3C9FBE22.A72B4A27@ccvcorp.com> Message-ID: <3CA0D05D.B42BF0E1@ccvcorp.com> Cliff Wells wrote: > Also, I notice that your calls to gridSizer.Add are incorrect. The second > argument is supposed to be a boolean flag indicating whether the widget > should be expanded in the sizer's primary direction (in the case of a > wxFlexGridSizer, I'm not sure what that means, but you still need the > argument, at least as a placeholder). The wxALL and wxALIGN_* flags should > be the third argument. Oooh, I missed that, the first time through. Actually, though, the second argument isn't a boolean, though, it's an integer, which represents the weighting given to that item when expanded. (If you add item 1 with weight 2, item 2 with weight 0, and item 3 with weight 1, then any expanded space will be split up, with 2/3 of it going to item 1 and 1/3 going to item 3...) Jeff Shannon Technician/Programmer Credit International From miracle at paradise.net.nz Wed Mar 27 16:40:55 2002 From: miracle at paradise.net.nz (Matthew Sherborne) Date: Thu, 28 Mar 2002 09:40:55 +1200 Subject: [Python-Help] Re: How to get a key from dictionary? References: <20020326204100.576.qmail@web9302.mail.yahoo.com> Message-ID: <003b01c1d5d8$13b86b70$08020196@Jonah> Yes. Good response. Your code is best :) GBU Matthew Sherborne From spacedweller at hotmail.com Sun Mar 10 21:22:58 2002 From: spacedweller at hotmail.com (j45729) Date: Mon, 11 Mar 2002 02:22:58 -0000 Subject: New Member Message-ID: Hi i'd like to introduce myself. My name is Jon. I think Python is one of the coolest scripting languages! I'm a new student and i'm enjoying learning Python. I hope to use Python in many applications for the web and for problem solving and anything else. I think it will be fun! I'm so glad i have all of you here for my support! what a great plus in learning this language is having so many who are interested in the same language. -Jon From Ken.Peek at Engineer.com Sat Mar 30 14:07:37 2002 From: Ken.Peek at Engineer.com (Ken Peek) Date: 30 Mar 2002 11:07:37 -0800 Subject: Another stab at a "switch/case" construct (for Python 3000): References: Message-ID: Steven Majewski wrote in message news:... > On Fri, 29 Mar 2002, Bjorn Pettersen wrote: > > > > From: Steve Lamb [mailto:grey at despair.dmiyu.org] > > > > > > its_called_a_directory_pointing_to_functions = {'case':closed} > > > > > > I do not believe that any language which can have a hash > > > of function pointers has any business with a case statement. > > > > But that only works when all the functions in all the branches take the > > same number and types of arguments -- hardly the general case. > > > > table = {} > > table[key] = func, (args,...) > ... > > def doit( k ): > return table[k][0]( *table[k][1] ) > > > You could also use entries that are lists of (func,args) pairs, > and there are ways of constructing nested tables. > > > -- Steve Majewski You could also write some nice (very readable!) assembly language code, and add some wrappers to Python! This would be a GREAT alternative to adding standard constructs to Python! sarcastically yours, Ken Peek From sarnold at arnolds.dhs.org Mon Mar 4 22:50:18 2002 From: sarnold at arnolds.dhs.org (Steve Arnold) Date: 04 Mar 2002 19:50:18 -0800 Subject: Status of PEP's? In-Reply-To: <7xwuwrofhk.fsf@ruckus.brouhaha.com> References: <7xwuwrofhk.fsf@ruckus.brouhaha.com> Message-ID: <1015300226.1855.4.camel@rama> On Mon, 2002-03-04 at 19:33, Paul Rubin wrote: > David Eppstein writes: > > While we're picking minor nits, I would consider the natural numbers to > > include zero. > > Usually the term "natural numbers" don't include zero. > http://mathworld.wolfram.com/NaturalNumber.html Yay, somebody found mathworld (or a text book). Natural numbers are the counting numbers (positive integers). Zero is not in the set of Natural numbers (it is only used as a place holder). Now if you said Whole numbers, or non-negative integers, that would have been entirely different. Isn't it nice to have children spread out from 3rd grade to 7th grade? I love helping with math homework... Steve From toorop at cyborgnation.org Mon Mar 25 12:10:58 2002 From: toorop at cyborgnation.org (Toorop) Date: Mon, 25 Mar 2002 18:10:58 +0100 Subject: What is the problem ??? Message-ID: <137278443120.20020325181058@cyborgnation.org> Bonjour , I'm trying to install a python script for smtp server qmail. The script : qmfilt by Dru Nelson (http://sourceforge.net/projects/qmfilt/) environement : RH 7.2, python 2.2, qmail 1.03 +patch qmail-queue When i run it manually in test mode(no complete processus), it's ok, but When i run it with Qmail, my smtp log say : @400000003c9f1d13372a65fc /usr/bin/python2: error while loading shared libraries: libc.so.6: failed to map segment from shared object: Cannot allocate memory Is anyone heve a idea ?? -- Toorop Working a year in IA make you believe in God From jhg at galdon.com Thu Mar 14 04:18:37 2002 From: jhg at galdon.com (Juan Huertas) Date: Thu, 14 Mar 2002 10:18:37 +0100 Subject: About deletion of variables in version 2.1 References: Message-ID: Sorry, i'm trouble, the problem is not in the deletion of variables. The problem takes into zlib (decompress method). I'ts not work fine. Thank You for your interest. "Jason Orendorff" escribi? en el mensaje news:mailman.1015879323.25989.python-list at python.org... > Juan Huertas wrote: > > Reading a large file and loading to a list: > > > > f=open('c:/xx','rb') > > ls=[] > > while not eof: > > ln=f.readline() > > ls.append(ln) > > > > This takes 5 seconds (reasonable) > > This code is a little nonsensical. Could you post real code > that can be tested? > > ## Jason Orendorff http://www.jorendorff.com/ > > From emile at fenx.com Wed Mar 27 09:18:37 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 27 Mar 2002 06:18:37 -0800 Subject: seek in a file References: Message-ID: "Andreas Penzel" wrote in message news:a7s4q4$no0i9$1 at ID-69142.news.dfncis.de... > "Steven Majewski" wrote: > > > Are the files too big to fit in memory ? > > the file is about 1 MB, i have to test out working > > > What do you want to do with the lines ? > > ( I hope you weren't planning on trying to modify a line in a file: > > because of the variable length on lines, if you don't write > > exactly the same number of chars back, you will either overwite > > the next line, or leave an extra partial line after your edited > > line. Most text editors read the whole file into memory and then > > write out a new file after it's modified in memory. ) > > In the file are barcodes of products, one per line. > The program has to look if the scanned code from the barcode-scanner is > identically with one in the file included. This is important because the > barcode-scanner sometimes works not correct. All i need is an search-routine > that compares the scanned code with the codes in the file. If there is an > code, the programs waits for the next code. > Then you probably want to read the whole file in and restructure for optimal access. The duplicate values for multiple keys is no longer an issue. Build a look up dictionary and use it: #--untested-- productlist = open('\path\and\filename').readlines() upcdict = {} for rec in productlist: product, upccode = rec.split(delimiter) upcdict[upccode] = product # or None if you're just validating try: upcdict[scannedcode] except: invalid code handling HTH, -- Emile van Sebille emile at fenx.com --------- From peter at engcorp.com Sat Mar 23 11:19:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 23 Mar 2002 11:19:43 -0500 Subject: The IDE is important too [was Develop-test-debug cycle] References: Message-ID: <3C9CAB1F.316E24BB@engcorp.com> Dale Strickland-Clark wrote: > > Paul Magwene wrote: > >Since it's open source why don't YOU implement the cool ideas you've > >suggested, submit 'em back to the community, and WE can all be four times > >more productive? > > I'd love to have the time but I'm spending it all in the > develop-test-debug cycle at the moment. Maybe you would benefit from switching to the test-develop-test cycle of Extreme Programming instead? It could get you out of that rut. -Peter From martin at v.loewis.de Thu Mar 28 05:42:13 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 28 Mar 2002 11:42:13 +0100 Subject: unicode experiments + questions -- PythonWin?? References: Message-ID: "Irmen de Jong" writes: > > The print does not do any conversion; it just sends bytes to the output > stream. > Hmm... how does it send the unicode string to the output stream? It invokes its .write method. > Not as raw unicode (unconverted), because print redirection throws > an encoding exception. Depends on what the output stream is. If it supports Unicode strings directly, it may be able to write them without converting them. If it is a file object, the write method invokes the ParseTuple "s" conversion (actually, "s#" or "t#" depending on binary mode), which in turn will, for a Unicode object, invoke the default encoding. Regards, Martin From dalke at dalkescientific.com Wed Mar 13 20:07:54 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 13 Mar 2002 18:07:54 -0700 Subject: Question about scientific calculations in Python References: <9gcu8u483cn544anr78k67jsknuv4tb6ks@4ax.com> Message-ID: Martin Kaufmann: >I didn't quite understand this part. How should I precompute the zero >entries? How do I know where they are? Or should I just cut them out >before and access the histogram differently? You have for s in s_vector[1:]: sum = 0 for entry in hist[1:]: if entry[1] == 0: continue x = 2 * pi * s * entry[0] sum = sum + (2 * entry[1] * (sin(x) / x)) intensity = atoms * pow(f_s_vector[n], 2) * (1 + sum / atoms) i_vector.append(intensity) n = n + 1 The hist entries are not dependent on s, so the non-zero elements can be pulled out beforehand. nonzero_hist = [entry for entry in hist[1:] if entry[1] != 0] for s in s_vector[1:]: sum = 0 for entry in nonzero_hist: x = 2 * pi * s * entry[0] sum = sum + (2 * entry[1] * (sin(x) / x)) intensity = atoms * pow(f_s_vector[n], 2) * (1 + sum / atoms) i_vector.append(intensity) n = n + 1 >The list are not that long. Probably only a couple of thousands >entries. Then don't worry about that tweak. >I tried to use weave.inline. Here is my code. But put your coffee away >before you read it (you might spill it otherwise over your keyboard) >and _please_ don't laugh out loudly.. I really didn't know what I was >doing, but it somehow worked... Well, I don't drink coffee. But then, I also don't often write Python/C extension code. Someone else will need to check that code. > The speed of the weave solution is quite incredible! Factor of 8 is pretty nice, and within the normal rule of thumb people expect for an implementation in C. Andrew dalke at dalkescientific.com From tchur at optushome.com.au Tue Mar 12 15:26:21 2002 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 13 Mar 2002 07:26:21 +1100 Subject: english thesaurus and dictionary References: Message-ID: <3C8E646D.A0A29E12@optushome.com.au> Bob Roberts wrote: > > I want to incorporate an english thesaurus and dictionary into my > application. Does anybody know of freely available thesauri and > dictionaries that I could use? Have a look at Oliver Steele's PyWordNet Python interface to WordNet at http://pywordnet.sourceforge.net As Oliver notes, WordNet (see http://www.cogsci.princeton.edu/~wn/ ) is a lexical database of word meanings and lexical relationships (including synonyms, hyponyms etc), so it can be used as a dictionary and thesaurus, although it does much more. The WordNet database is very extensive, though - it might be overkill in some circumstances. Both WordNet and PyWordNet have free, open source licenses. Tim C From eric at vasilik.com Sat Mar 16 02:16:51 2002 From: eric at vasilik.com (Eric Vasilik) Date: 15 Mar 2002 23:16:51 -0800 Subject: Help with a Python ASP C extension module ... Message-ID: <40ee0487.0203152316.70c12a49@posting.google.com> I am writing a C extension to Python. The reason I am writing an extension is that I believe that the implementation of Response.BinaryWrite() in the Window's ASP extension (I am using Active State's Python 2.1) is not releasing the global interpreter lock. I am getting very poor performace using it and I believe that my server is not taking advantage of writing out multiple streams because of the global lock. Instead of writing out a response with: Response.BinaryWrite( buffer( open( fileName, 'rb' ).read() ) ) I am now doing the following: PythonExt.binaryWriteFile( Response, fileName ) The difference between these two is that the first calls the default implementation of Response.BinaryWrite and the second calls an extension I have written which reads the file and writes it out to response, all while the interpreter lock is released. My problem, is I cannot find any documentation on how to get a hold of the IResponse object from the Python Response object. I need to get it so that I may call BinaryWrite on without going back into the Python interpreter. I thought I would be able to find the source for the Response object with the source from Active State, or the source from Mark Hammond's win32All, but I found no references there. Any help would be appreciated. From seeger at sitewaerts.de Thu Mar 7 11:40:48 2002 From: seeger at sitewaerts.de (Felix Seeger) Date: Thu, 07 Mar 2002 17:40:48 +0100 Subject: time date math problem References: Message-ID: Emile van Sebille wrote: > Felix Seeger >> Hi >> >> What I want: >> >> Date: >> >> 20.03.2002 >> >> 20.05.2002 - 21.00.0000 = 30.04.2002 >> >> > > mxDateTime includes that and more. Take a look at > http://www.egenix.com/files/python/mxDateTime.html > Ah thanks, that works great. have fun Felix From bokr at oz.net Sat Mar 9 16:11:05 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 21:11:05 GMT Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> Message-ID: On Sat, 09 Mar 2002 17:17:13 GMT, "Fredrik Lundh" wrote: >Edward K. Ream wrote: >> Dynamic tracing is trivial to implement. More importantly, it is >> simpler to use and more flexible than any static scheme such as the one >> described in 282. > >except that in real systems, the end user couldn't care less >about what/when/how your Python functions are called. > >they do care about syslog-compatibility, severity levels, and >trivial things like getting the same logging messages also after >you've refactored your program... Yes, ISTM standardizing the format of log files is of primary importance, and we should be careful that a convenient mechanism doesn't establish a de facto format that locks out desirable tool synergy possibilities. (This has to be an old itch. Is there an RFC? Shall I be lazy and just ask rhetorically, and not google? Yes, for now ;-) If you have a standard format it is not hard to filter single-line stuff for particular concerns even just using grep. If you have a standard for context-entry/context-exit logging you can use standard tools to extract the chunks of interest. If you have time tagging standards with extended options you may be able to glean performance/profiling info in a standard way. You might want a cheap way to log time tagged sync into all channels. Etc., etc., and it should be easy to filter the log(s) to drive source browsing. The point is the log format is more important than how it got written. A convenient standard log module will certainly help standardizing. You could also make it a command line option to instantiate log (and a devlog alias) as a builtin, for even more convenience. It might be interesting to give the parser a simple line exclusion capability (perhaps based on name token match to supplied names). Then you could e.g. run with devlog statements excluded (including the devlog=log alias-defining statement) and later strip them out of the source by the same pattern. The exclusion names could be a command line option also (just an OTTOMH idea). You could in/ex-clude arbitrary debug functions calls similarly. It would be nice to be able to distribute log-capable software with logging optimized out by default, but available. I don't think that a developers' code line exclusion capability would be suitable for that, though. IOW, I could see a development version of software being heavily log-enabled and assert-filled, and it would be convenient to anticipate optimizing it out optionally during test runs, and probably stripping most of it out for a final version. If you chose simple conventions for writing log statements on lines by themselves, and differentiated to-be-stripped development code from final in some standard way (something to discuss and decide) like using e.g., a standard devlog.error("this will be stripped") alias for log, you could make the job relatively easy. I'd like see a log file grammar definition discussed first, before a nice convenient log module establishes a premature de facto standard. I'd like to see a log file grammar be part of the PEP, not just something to be imperfectly inferred from the examples. I recognize that the author is researching precedents and putting a lot of effort into getting it right, but I think discussion focusing on the log file grammar and various real uses will make future tool synergy more likely. Tool synergy might be a good topic for a PEP section. Regards, Bengt Richter From maric.michaud at cirec.com Thu Mar 21 11:59:57 2002 From: maric.michaud at cirec.com (Maric) Date: Thu, 21 Mar 2002 17:59:57 +0100 Subject: Problem with threads Message-ID: <000201c1d0f9$d5649f20$470010ac@GERLAND2.local> * I want to use TKinter with multi-threads, is there any solution ? * How PyQt does support threading ? Thanks ! From phr-n2002a at nightsong.com Mon Mar 4 15:31:14 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 12:31:14 -0800 Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> Message-ID: <7xzo1om5wt.fsf@ruckus.brouhaha.com> Christian Tismer writes: > Makes pretty much sense to me. > Stackless can provide light-weight threads to all platforms. > There is no need to use OS threads unless you need it > for I/O. Do you think it's feasible to modify Python to use non-blocking i/o everywhere, and then simulate blocking in Stackless? I.e. when a microthread does an i/o operation, Python would start the operation asynchronously, and the Stackless microthread scheduler would block the microthread til the i/o operation actually completes (detected using select or SIGIO). From aahz at pythoncraft.com Sun Mar 31 20:31:56 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 20:31:56 -0500 Subject: Python quick setup URL for Linux setup? References: Message-ID: In article , Robert Oschler wrote: > >Yep, says I've got 2.1.1. But is there an equivalent to PythonWin on >Linux? I'm GUI spoiled :) Not directly. You can use Tools/idle/ but that's not quite as refined as PythonWin from what I've heard. There are also some other GUI projects, which you can find at http://www.vex.net/parnassus/ Look under Python Tools/Extensions, then Editor / IDE. You'll also find many, many arguments on this subject by going to Gooja and doing a search on "IDE comp.lang.python". ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From peter at engcorp.com Fri Mar 29 18:16:27 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 18:16:27 -0500 Subject: string copying References: Message-ID: <3CA4F5CB.E8961330@engcorp.com> Jeff Shannon wrote: > > In article , > robin at jessikat.fsnet.co.uk says... > > Is there some special reason why python inhibits string copying. I > > suppose there's some attempt being made to make these constants. To make > > differing versions of 'abc' one has to resort to silliness like 'ab'+'c' > > 1) Strings are immutable. This implies that there is zero > practical difference between two references to two separate > string objects of identical value, and two references to the same > string object. The only one I've been able to think of is the surprisingly common situation of trying to consume vast quantities of memory quickly by something like: a = [0] * 1000000 for i in xrange(1000000): a[i] = 'bigstringsuckinguplotsofmemory' If nothing else, this confuses newbies for a while... From jgardn at alumni.washington.edu Sat Mar 2 04:11:09 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Sat, 02 Mar 2002 18:11:09 +0900 Subject: Useful, robust shell utilities References: <%8Wf8.518$Az6.2357@news.hananet.net> <3C806342.E28D1ED0@engcorp.com> Message-ID: Peter Hansen scribbled with his keyboard: > Jonathan Gardner wrote: >> >> There would be a big benefit to see something like: >> >> res = chmod("-c", "-R", "u=rwx,g=rx,o=", a_file, another_file, >> a_directory) > > Is that anything like > > os.system('chmod -c -R u=rwx,g=rx,o= %s %s %s' % (a_file, another_file, > a_directory)) > Gotta love being on a Unix system. That's EXACTLY what it would do. For those of you who aren't intimately familiar with 'chmod', let me tell you what this command does. It recurses to all the subdirectories (but not the ones that start with '.') and changes the mode of the files to be inaccessible to the world, only readable and executable to the people in the file's group, and readable, writable, and executable by the owner. If it actually made a change, it would print out the name of the file it changed. > > If so, why are you trying to rebuild the unix shell within Python? > (Or what am I missing?) > The limitation of the above os.system call and my future, unimplemented chmod call would be that my function would return a list of names of the files it changed (provided the -c option is present, or something like that). It would also allow interactivity between the Python script and chmod, so you can have a function that will determine whether or not to change one particular file. So, while 'chmod' the program in the Unix toolbos is implemented for shells, 'chmod' the function in Python will be useful for Python. Also because Python ports to Windows, and Windows ain't Unix. It would be nice to have those tools with you no matter where your program goes, rather than having to do: if os.name != "posix": raise OSError, ("You're not using a real OS. " "You know that real OSes are free nowadays, don't you?.") I wanted to write an installation script for my program. No, it's not a standard module - it's a game, and you certainly don't want your games to get mixed in with your real modules. If all my users were on Unix systems, then I would have done it with a shell script. But they aren't. So I had to figure out how to get the job done on Windows. It looks like python was my closest bet. I ended up writing some simple tools for the job that could have been done with 'sed', 'rm', and 'install' in Unix. Perhaps someone else would like to have these tools available to them wherever they use Python. Jonathan From edream at tds.net Mon Mar 4 21:12:59 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 05 Mar 2002 02:12:59 GMT Subject: Reorganizing python.org (was: Why isn't pychecker...) References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> <3C841006.634D0059@tds.net> Message-ID: <3C84299A.20EC85A2@tds.net> Steve Lamb wrote: > > Another example, the otherwise superb intro to Tkinter, > > http://www.pythonware.com/library/tkinter/introduction/index.htm > > would be vastly more useful if it fit on a single page. > > Define "page". If you say 800x600 you'd lose. Good question. How would you define a page in terms of web design? Eliminating most if not all scrolling on reference pages seems particularly important. Some reference pages seem way too long. And your point is well taken. I have a large monitor, but I use relatively big fonts, so I'm only using 1024x768... Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From dlharris at mail.usyd.edu.au Thu Mar 7 08:36:46 2002 From: dlharris at mail.usyd.edu.au (Dave Harrison) Date: Fri, 8 Mar 2002 00:36:46 +1100 Subject: overloading a function Message-ID: <20020307133645.GA995@dave@isetroc.com> Hi there all, If I have a function, but I want to be able to call it two different ways - the ways being differentiated by the paramaters I pass the function) how do I do this ?? At the moment I have def Foo(num) def Foo(num,dflt) however I am only getting the first of the two, and the second function is ignored. I couldn't find anything in the documentation, any ideas ? From gh_pythonlist at gmx.de Mon Mar 4 13:03:42 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 4 Mar 2002 19:03:42 +0100 Subject: Can Python do this? In-Reply-To: References: Message-ID: <20020304180342.GB4480@lilith.hqd-internal> Le 04/03/02 ? 12:51, Robert Oschler ?crivit: > Hello, Python newbie here. > > Let's say I'd like to build a method name into a string variable (e.g. > "FuncCall" + "1" to attempt to call "FuncCall1"). Can I then call that > method by somehow having the interpreter evaluate the string variable into a > call to the desired method? (I know this is usually done in a language like > Prolog or Lisp but I'm hoping Python can do it too.) This can easily be done with the built-ins eval and exec. But in 99 % of all cases, it's a really bad idea to use them. Perhaps you can tell us what you're trying to accomplish anyway? There's usually a better way than (ab)using eval/exec. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 5.7 ?C Wind: 2.1 m/s From fredrik at pythonware.com Sat Mar 9 12:53:17 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 09 Mar 2002 17:53:17 GMT Subject: PEP 282: A Logging System -- comments please References: <3C894E28.BB2CCE7B@tds.net> <3C8A4810.85A56A1@tds.net> Message-ID: Edward K. Ream wrote: > > > > except that in real systems, the end user couldn't care less > > about what/when/how your Python functions are called. > > > > they do care about syslog-compatibility, severity levels, and > > trivial things like getting the same logging messages also after > > you've refactored your program... > > I was talking about functionality, not packaging. Naturally, a logger > would be a class. hmm. I'm pretty sure you said: ... the trace function uses the name of the method from which trace was called as the tracepoint string .... and ... the app (or tracing object) maintains a dict of enabled tracepoint names. The user can add or delete entries in the dict at run time ... which doesn't work in the kind of real-life applications I build, but where PEP 282 would work right out of the box. ...but maybe you meant something else. (after all, you also said "These will be my last words on this subject" in an earlier post... ;-) From erno-news at erno.iki.fi Sun Mar 24 17:54:36 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 25 Mar 2002 00:54:36 +0200 Subject: The OOM-Killer vs. Python References: <3c9e2b5f.9993062@news.t-online.de> Message-ID: In article <3c9e2b5f.9993062 at news.t-online.de>, gerson.kurz at t-online.de (Gerson Kurz) writes: | I have a python-based SMTP server (see http://p-nand-q.com/shicks.htm) | running on our server, and in general it has worked flawless (since | about nov 2001). However, in the recent week that dreaded linux OOM | killer twice killed the python process. [The machine has 768mb ram - | call me oldfashioned but that SHOULD be enough for both Linux & Python | to get along, really. OK, its running KDE, and has only 256mb for | swap, but still...] i think you need more swap, also make sure you have your resource limits configured correctly. last i heard, the linux 2.4 kernel series had a "feature" where swap space only gave you (swapsize - physical memory size) more vm space. -- erno From hartmut.goebel at noris.net Sun Mar 31 18:19:38 2002 From: hartmut.goebel at noris.net (Hartmut Goebel) Date: Mon, 01 Apr 2002 01:19:38 +0200 Subject: ANN: bridgekeeper 0.0.1 - a Perl to Python source code converter Message-ID: goebel consult proudly announces bridgekeeper ============ 0.0.1 A Perl to Python source code converter http://www.crazy-compilers.com/ (N?rnberg/2002-04-01) While 2001 brought us Parott, pyperl and pyperlish, 2002 brings to you 'bridgekeeper', a Perl to Python source code converter. What 'bridgekeeper' does ------------------------ 'bridgekeeper' help converting Perl code to Python source. The quallity of the output Python source depents on the quallity of the input code. If there are constructs within the Perl code which are not possible in Python, you will get warnings. Eg. when using a name for both a hash and a scalar within the same scope (%foo, $foo). Converting Perl to Python will be a iterative process, see the TUTORIAL for more information about this. 'bridgekeeper' consists of * a Perl compiler back-end emitting Python-like source and * a runtime Python package which tries to emulate some perl build-in functions. The name was inspired be the bridgekeeper-scene in Monty Pythons 'Search for the Holy Grail'. Features -------- * Already converts a lot of Perl code-constructs into Python source: loops, special variables, function calls, lists, hashes, methods, etc. * Whenever there is no equivalent Python function for a Perl function, the function is emulated using the included Python library. * Includes a TUTORIAL 'How to convert Perl Code to Python Source' * Warns about variables with same name but different type within a scope, eg. when using a name for both a hash and a scalar (%foo, $foo). This included scalars, hashes, lists, arrays and (hopefully) filehandles. * Warns about mixing variables with same name but different Perl scoping within a Python scope, eg. using (global) $foo and my $foo in one scope. * Strips statements like 'my ($foo, %bar);'; this is: my and local declarations without assignment. * Special variables are renamed to their equivalent within the included Python library. * 'here-documnets' are supported. Limitations ----------- * Does not support 'use', 'BEGIN', 'END', etc. This is due how Perl handles these expressions: they get executed while parsing. See the Tutorial for solving this problem. * Does not handle 'bless', 'packages', etc. * References may or may not be resolved correctly. * Does not convert things like 'my ($self, arg1, arg2) = @_;' into a pythonic argument-lists. (Hey, this would be a great feature!) * In some rare cases Perl functions are converted to the nearly-equivalent Python function instead of using a emulated function. This is done for functions which return a value which is probly not often used. * The Python libary included contains all required functions, while many of them are not yet implemented. * Formats are not supported anyhow. (But I already have an idea how this could be done: use a class perl.Format thatfore.) This also includes the function 'write'. * Separate prototype declarations are not supported, whereas prototypes at function definitions are taken over (as comments). * Prefix/postfix operator are not resolved. * Esoteric execution orders are not supported (see test/weird_contexts.pl). * The Python libary included is not thread-save -- and probably will never become thread-save. * A lot more :-) Availablity ----------- 'bridgekeeper' is available for download at http://www.crazy-compilers.com/ From dale at riverhall.NOTHANKS.co.uk Wed Mar 27 19:12:57 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 28 Mar 2002 00:12:57 +0000 Subject: Slice objects. How to apply them to strings? Message-ID: I'm using Python 2.1 here but this still seems to apply on 2.2 I have a little string-based class which needs to emulate strings for most things. This includes slicing. So I need a __getitem__ magic method. This will get passed a slice object. How am I supposed to translate this into a string slice? This seems to be the tidiest I can come up with and it's a mess: def __getitem__(self, item): if item.step: return self.s[item.start: item.stop: item.step] if item.start: return self.s[item.start: item.stop] return self.s[item.stop] If 'item' is a slice object, shouldn't I just be able to say: self.s[item] ? Wouldn't this be really sensible? What's worse, is that I can't even do this: import operator operator.getitem(self.s, item) Somebody please tell me I'm being dim and I've missed something. How do you apply a slice object to a sequence? Thanks -- Dale Strickland-Clark Riverhall Systems Ltd From jeff at ccvcorp.com Tue Mar 26 14:08:37 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 11:08:37 -0800 Subject: running python on win2k References: Message-ID: <3CA0C734.59DB3CE3@ccvcorp.com> stclaus_imi wrote: > hi, all of you. > > i downloaded python for win2k. i wonder how to run it via the command > line and over the apache/iis web server. >From the command line, simply type "python", or "python myscript.py". If you have .py files registered as executable, you can simply type "myscript.py" as well -- I know that ActiveState's distribution will do this on installation; I haven't tested whether PythonLabs' installer automatically does this, but it's likely. Jeff Shannon Technician/Programmer Credit International From martin at v.loewis.de Thu Mar 28 05:02:19 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 28 Mar 2002 11:02:19 +0100 Subject: unicode experiments + questions References: Message-ID: "Irmen de Jong" writes: > See the other posting... PythonWin does strange things when printing unicode > directly?? Without checking, I'd say it doesn't do "strange things" - it just does the right thing, printing the Unicode object as-is (without converting it to a byte string first). Perhaps it does convert it to the "mbcs" encoding before passing it to the Window API - but it might even use the Unicode variant of the Windows API, which allows direct output of Unicode strings. You could find out by printing a string that has characters which are not supported in windows-1252 (e.g. GREEK SMALL LETTER ALPHA). Regards, Martin From dever at segsrv.shr.cpqcorp.net Mon Mar 18 16:15:22 2002 From: dever at segsrv.shr.cpqcorp.net (Dan) Date: 18 Mar 2002 13:15:22 -0800 Subject: Python on VMS? Message-ID: <33e9195e.0203181315.6d841d4a@posting.google.com> Is Python available on VMS? There are two links given in the FAQ. One points to a non-existant file and the other declares that the contents have been erased and not made available elsewhere. (Someone should really update the FAQ.) Thanks, Dan From benc1 at today.com.au Sun Mar 10 20:46:52 2002 From: benc1 at today.com.au (Ben C) Date: 10 Mar 2002 17:46:52 -0800 Subject: Porcess control on win32 Message-ID: <8beb91f5.0203101746.544e64dd@posting.google.com> Hi, I am trying to achieve this scenario on a Win32 machine ... a. create a lot of new processes (ie. open application 'x' a number of times with different args) b. each time 1 of the processes exits ... do something I have looked at using somehting like this ... project_lst = ['application1', 'application2', 'application3', etc] for application in project_lst: process, thread, pid, tid = win32process.CreateProcess( None, application , None, None, 0, win32process.NORMAL_PRIORITY_CLASS, None, None, win32process.STARTUPINFO()) win32event.WaitForSingleObject(process, win32event.INFINITE) print 'Application %s Has Just Exited) % (application,) ... The problem with this structure is it spawns each application in sequence ... how can I modify this sructure to spawn all applications simultaneously and still have the print statement executed only when one of the projects exits? thanks in advance Ben From logstx at bellatlantic.net Sun Mar 10 13:06:44 2002 From: logstx at bellatlantic.net (logistix) Date: Sun, 10 Mar 2002 18:06:44 GMT Subject: Use apply() or not, and raising multiple exceptions (co-routines?) References: Message-ID: > I could have also written this as: > > for check in self.checks: > apply (check, [data]) > > is there any particular reason to prefer one style over the other? It basically depends on how much you like functional programming. Generally people who make lists of functions will prefer using map, apply, and filter. Even more functional than this is to write your check function to analyze only one datum at a time. I imagine each check function currently has a "for datum in data:" loop as well. If you design them to analyze one piece of data at a time you can replace the above with: for check in self.checks: map(check, data) This will also cycle through the whole list if you handle an exception in the check function now. Map also creates a list of return values (this is actaully the whole point of map) so if you return error codes from the except: clause you can save them: def check(datum) try: # do check stuff except IntegrityCheckError, message: return message for check in self.checks: errors = map(check,data) for error in errors: if error != 0: print error And if you really want to go overboard on the functional code, replace the above with ;) def checkData(check, data): map(sys.stdout.write, filter(lambda x: x != 0, map(check, data))) [checkData(check,data) for check in self.checks] From matthias_j at lycos.com Mon Mar 11 01:23:55 2002 From: matthias_j at lycos.com (Matthias Janes) Date: 10 Mar 2002 22:23:55 -0800 Subject: Binary Register entries Question References: Message-ID: Thank You so much. Matthias Janes From mhammond at skippinet.com.au Sun Mar 3 01:49:39 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 03 Mar 2002 06:49:39 GMT Subject: wiin32clipboard "odd" behaviour?? References: Message-ID: <3C81C793.9030305@skippinet.com.au> Javier wrote: > So, what would I have to do to manage things "as usual"?? > > Ideas, pointers?? A quick groups.google search? A search for "win32clipboard" found http://groups.google.com/groups?selm=mailman.1013975848.15752.python-list%40python.org, which has a simple function that works fine for me. Mark. From pearu at cens.ioc.ee Sun Mar 31 16:26:33 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sun, 31 Mar 2002 23:26:33 +0200 (EET) Subject: PEP 285: Adding a bool type In-Reply-To: <3CA751EF.10F25F2D@ndh.net> Message-ID: On 31 Mar 2002, Stefan Schwarzer wrote: > bools and ints. For example, I consider it very unintutive that > "True == 1" should by true but "True == 2" should be false. I Just a random thought ... Theorem: ======== Assume specification of PEP 285. The following statements hold truth: True is One and False is Zero, where One and Zero represent integers 1 and 0, respectively. Proof: ------ According to PEP, True and False are instances of bool that is a subclass of int. Therefore True and False can be considered as integers and it makes sense to compare them with integers. If n is an integer then the following statements hold True == n only if n is 1 and False == n only if n is 0. Note that these statements still hold if n is varied within the set of all standard Python objects: {None} U Tuples U Lists U Strings U Numbers .. with ==-relation defined as the Python ==-relation when comparing objects of different types. Q.E.D. truth-is-True-is-One-is-1-is-integer-is-bool-really-necessary?'ly Pearu From jimd at vega.starshine.org Thu Mar 21 16:16:37 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 21 Mar 2002 21:16:37 GMT Subject: "Zope-certified Python Engineers" [was: Java and Python] References: Message-ID: In article , Laura Creighton wrote: >> ( Or maybe this begs for a Slashdot like system to >> distribute the review, grading and selection of projects. ) >> -- Steve > You want something more like the scientific reviewing of a technical > paper than slashdot's 'all you need to vote is a pulse'. Otherwise > the most popular wrong way to do something will generate the highest > marks. This is a very hard thing to do politically -- there is a > tightrope between the sort of eletism which exists to keep a lid > on new, good, creative endeavours (a flaw you can correct by inserting > more democracy into your process)and pandering to the worst base > instincts of humanity (a flaw you can correct by having higher standards > in your selection committee). The best way to do this is to provide > a certain amount of meta-data with your assessment -- so we can > find out not only that Steven Majewski thinks that XXX is cool, but > also that Steven Majewski has a reputation around here, and most > people think that Steven Majewski's opinion of something is valuable. It's a bit off-topic for this newsgroup, but relevant to this discussion: Advogato (http://advogato.org/ ) has a meshed reputation scheme. People vote on your level (from Apprentice through Journeyer to Master). However, the effect of their vote is heavily weighted by their level which is determined by how others voted on them. People/accounts are marked as "observers" until (non-Observer) vets them. Some key "seed" accounts are initially marked as "Masters" and, if they are chosen wisely, the whole system seems to work reasonably well. Of course you can read all about the trust metric If the seed users are careless, corrupt or incompetent then they system will be a mutual admiration society). Note that Raph (the creator of Advogato hasn't claimed that this solves any particular real-world problem. I seem to recall that his intent was to have a "slashdot with some quality control." > This doesn't stop Flaming Rabid Hamster from voting that Steven > Majewski is a fool and that every project that Steven Majerski finds > valuable is worthless, but if this is an minority opinion of 1, then ... > I think that this sort of metadata belongs in the sort of > cataloging system we should have to implement PEP 262, as well. > Of course, I am biased -- AB Strakt is building something to do > this, because we think that its a huge world problem that needs > fixing. > Laura Creighton You should read about the Advogato "Trust Metric" (http://advogato.org/trust-metric.html ). It's possible that this could be used at python.org as a community voting scheme. A few seeds (Tim Peters, Guido, etc) could select lieutenants (Journeyers, or even Masters). People who post intelligibly to that site and/or to this newsgroup might be deemed as "Apprentices" at least. Someone who's contributed to the FAQ, docs, or esp. the code corpus (modules, or core) should probably be given Journeyer or Master status. (Journeyer for a working published module and Master for anything that gets into the main distribution?). From david.abrahams at rcn.com Sat Mar 30 09:04:31 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sat, 30 Mar 2002 09:04:31 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> Message-ID: <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> ----- Original Message ----- From: "Guido van Rossum" To: "David Abrahams" Cc: ; Sent: Saturday, March 30, 2002 8:47 AM Subject: Re: [Python-Dev] PEP 285: Adding a bool type > [David Abrahams] > > 6) Should we eventually remove the inheritance relationship > > between Int and Bool? > > > > I hope so. Bool is-a Int doesn't seem like the right relationship to > > me, unless perhaps we make Int is-a Long... naah, not even then. > > Hm. In your favorite language bool is one of the integral types. > Doesn't that imply pretty much the same thing? Well, I try not to play favorites <0.002 wink>, but the implicit conversion rules in C++ are admittedly and unfortunately liberal. However, bool is detectably NOT derived from int in C++: void f(int const&); f(false); // error! assert(boost::is_base_and_derived::value); // fails! > Anyway, do you have a use case where it matters? Given that Bool is immutable, I have no cases other than examples of type introspection which can be written to account for the fact that Bool is-a Int. However, it does make certain things trickier to get right: numeric_types = [ Int, Long, Bool, Float, Complex ] for t in numeric_types: if isinstance(x, t): # Do something... This sort of thing could depend on getting the order of the list right (I didn't). -Dave From claird at starbase.neosoft.com Fri Mar 1 11:39:42 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 1 Mar 2002 10:39:42 -0600 Subject: Minor, minor style question Message-ID: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Why would I prefer string = "" string = string + "abc " string = string + "def " string = string + "xyz" over string = "abc " + \ "def " + \ "xyz" ? I see a lot of the former in contexts I associate with Visual Basic- or JavaScript-majority folkways. Is there an attraction to the redundancy (and fragil- ity!) I'm missing? Are \-s *so* deprecated? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From James_Althoff at i2.com Mon Mar 4 16:44:33 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 13:44:33 -0800 Subject: PEP 276 -- What else could iter(5) mean? Message-ID: Not clumsy at all. I like your rewording! Jim ============================= Jeremy Cromwell wrote: >>>>>>>>>>> Without trotting out ugly examples, it is cleaner than many of the current features in python. I'm still a relative newbie, but I remember it being a bit jarring to need to use range() just to iterate through numbers. It's so simple to explain and understand, that I doubt that it would be confusing. Here's my clumsy rewording of the tutorial: 4.3 For x in integer, and the range() Function When given an integer rather than a sequence, the for statement iterates over the numbers from 0 up to (but not including) the given number: >>> for i in 3: ... print i, i*3 0, 0 1, 3 2, 6 The given end point is never part of the generated list; for x in 10 iterates through a list of 10 values, exactly the legal indices for items of a sequence of length 10. To iterate over the indices of a sequence, use len() as follows: >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in len(a): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb If you do need to iterate over a more complex sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions. You supply the start and finish and it produces a list from start up to finish, incrementing by one: >>> range(5, 10) [5, 6, 7, 8, 9] It is possible to specify a different increment (even negative; sometimes this is called the `step'): >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] Calling range() with one number produces the same list that a for statement iterates over for that number: >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] --- end tutorial --- I like this proposal and would like to see it adopted. If others like it, they should speak up since about all we hear from are the detractors. Jeremy Cromwell ...now let's see........Hmmm, where's that key? <<<<<<<<<<<<<<<<<<<<< From donn at u.washington.edu Wed Mar 6 12:38:25 2002 From: donn at u.washington.edu (Donn Cave) Date: 6 Mar 2002 17:38:25 GMT Subject: Getting stdout and stderr from popen References: Message-ID: Quoth Jonathan Gardner : | Stefan Heimann scribbled with his keyboard: |> I want to launch an external process and have stdout and stderr |> redirected to one output stream, | | You are on Unix, right? | |> something like |> |> f = os.popen('cvs status 2>&1') |> |> does the right thing, but does not work on all platforms. Apparently he is not on UNIX? That's the right answer, as long as popen() runs the UNIX shell. |> If I write |> |> pin, pout, perr = os.popen3('cvs status') |> |> I get the output of stderr and stdout but not in the right order. | | What do you mean in the right order? Do you mean that it is returning in, | err, out or that err and out are spitting out stuff simultaneously? Probably not simultaneous, because the C I/O library probably has thread interlocks that prevent it, but if you want a single time ordered stream, you'd need time stamps to reassemble it out of two. For example, suppose you record the output of "make", which will be both output and error streams. If you read them separately, you won't be able to tell which compiler errors belong to which make commands. | Okay, let's talk about what is really happening deep underneath the hood. | | These popen functions are a shorthand for a very common thing in the world | of Unix. It goes something like this: | | 1) make three pipes (in, out, err) | 2) fork. I beg your pardon, but that's really not common at all. Most UNIX pipes are created using the shell, which makes a pipe for output only. If you want a separate pipe for error, you're in for some gymnastics - (cvs status 2>&3 | sed s/^/out:/) 3>&1 1>&2 | sed s/^/err:/ And there's no Bourne shell formula at all to get all three on pipes. More recent shells have features that could be exploited for that, but it gets hairy. This is not just nitpicking, because there are real good reasons why it isn't all that common. It's surprisingly difficult to get two processes to cooperate reliably over multiple pipes. That's my second point here - even if separate output and error streams are OK in terms of the data, they're distinctly more difficult to deal with if you don't make some simplifying assumptions about how the other process is going to behave. The shell syntax to route both streams into the pipe is really the right way to go, if it works. If it doesn't work, we'd have to know why not, before suggesting any answer. (If it doesn't work on Windows, then someone else is going to have to answer it - and the subject line probably should have included "Windows" in the first place.) Donn Cave, donn at u.washington.edu From deyke at yahoo.com Thu Mar 7 14:38:02 2002 From: deyke at yahoo.com (Dieter Deyke) Date: Thu, 07 Mar 2002 19:38:02 GMT Subject: [GERMAN] "ziegenproblem" References: Message-ID: stefan antoni writes: > sorry that i won't be able to explain this in english, i don't know the > name of this problem in english, and the website which is about this > problem is also in german. > > i want to write this basic code in python: > http://www.google.de/search?q=cache:Uugc3CH9SOQC:home.spektracom.de/ellrich/Ziegen.htm+ziegenproblem+basic+programm&hl=de > > i am still going to school, and we talked about this problem in a math > lesson. since i haven't got a basic-interpreter, i'd like to translate > this code into python, but i don't understand the code. > > anybody who knows basic and python as well? > > -- > stefan antoni Here you go: # Das Ziegenproblem, Gero von Randow # Denken in Wahrscheinlichkeiten, in Python (!) # Der Moderator darf nat?rlich weder die Auto- # noch die gew?hlte T?r ?ffnen import random print print "Von 2000 Wechseln waren " print for i in range(10): r = 0 f = 0 for j in range(2000): a = random.randrange(1, 4) w1 = random.randrange(1, 4) while 1: m = random.randrange(1, 4) if m !=a and m != w1: break w2 = 6 - m - w1 if w2 == a: r = r + 1 if w1 == a: f = f + 1 print "richtig:", r, "falsch:", f -- Dieter Deyke mailto:deyke at yahoo.com mailto:deyke at attbi.com Vs lbh pna ernq guvf, lbh unir jnl gbb zhpu gvzr. From martin at v.loewis.de Wed Mar 20 01:38:18 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 20 Mar 2002 07:38:18 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) writes: > - Magnus (who also is a bit baffled as to why distutils doesn't > include an "uninstall" command, such as the one implemented by > Thomas Heller.) That is not true. Both bdist_rpm and bdist_wininst do provide uninstallation support. Regards, Martin From garyr at fidalgo.net Sun Mar 31 11:00:04 2002 From: garyr at fidalgo.net (Garyr) Date: Sun, 31 Mar 2002 08:00:04 -0800 Subject: C-API, Tuple return value refcounts References: Message-ID: See the post by Edward C. Jones on 7/6/01. "Eric Merritt" wrote in message news:mailman.1017529670.5524.python-list at python.org... > Hello All, > > I have searched the archives fairly well and not > found an answer to this question, so I thought I would > post it to the list. I believe that this question > stems, to some extent, from a lack of understanding > concerning the reference counting system, so please > keep that in mind when you answer. > > I am using the C-API to interface with a library > function. Its a fairly simple interface in that it > makes a call and returns a PyTuple to the calling > process. It make no use of borrowed references. My > question is this; > > When I return the new tuple type, > > 1) Do I need to increment the reference count before I > return it (Keeping in mind that the tuple type is not > reference out side of this function, it is simply a > return value). > > 2) Do the PyObject values that make up the tuple type > need their reference counts incremented?. > > In the above case I do not believe that they need to > be incremented. Because according to the documentation > the reference counts are incremented automatically > when the PyObjects are created using the built in api > functions. This, of course, creates another couple of > questions. > > 1) Do I need to decref the tuple before it is > returned? > > 2) Do I need to decref the objects comprising the > tuple? > > > I truly hope this question is not considered list > clutter I have done my best to research the answers > before I posted, but I am uncomfortable with my > current understanding in this regard. > > Thank you, > Eric > > __________________________________________________ > Do You Yahoo!? > Yahoo! Greetings - send holiday greetings for Easter, Passover > http://greetings.yahoo.com/ > From jeff at ccvcorp.com Wed Mar 27 14:54:05 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 27 Mar 2002 11:54:05 -0800 Subject: Tkinter: Why won't it work? References: Message-ID: <3CA2235D.B803B0B9@ccvcorp.com> "A.Newby" wrote: > Hi. > > Below is an example exercise from "An Introduction to Tkinter" by Fredrik > Lundh. It simply creates a box with a quit button in it. Problem is, > everytime I click Quit, the program freezes. > > Is this a rare but well known bug with Tkinter, Python 2.2, or Windows 98? > Or is more probable that it's cuz my system is screwed? Are you running the script from within IDLE or PythonWin? Running a GUI program from within either of these environments doesn't work well. (It has to do with competing message loops within one process -- both run your scripts in the same process as their internal code.) The two possible solutions are to edit in the IDE but run your script from a DOS window (using DOSkey makes this relatively painless), or to switch to an IDE that runs your code in a separate process (most/all commercial IDEs do this; also check out IDLE-Fork on Sourceforge). Jeff Shannon Technician/Programmer Credit International From roy at panix.com Sat Mar 30 08:14:34 2002 From: roy at panix.com (Roy Smith) Date: Sat, 30 Mar 2002 08:14:34 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: What should the following examples print? >>> print {} == False >>> print {} is False I'm convinced the second one should print "False", but I'm not really sure about the first. I also assume that >>> print False is not True should print "True"? For those thinking ahead to obfuscated Python contests, I can see having lots of fun with this. The following, for example, is a valid Python program under this PEP: False is not True is not "False is not True" From bokr at oz.net Wed Mar 13 14:47:47 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Mar 2002 19:47:47 GMT Subject: Redirecting output in Windows NT References: <96e9dee5.0203120044.33a1e19c@posting.google.com> <3C8DC473.2070809@skippinet.com.au> <5cf809e9.0203121718.6d999426@posting.google.com> Message-ID: On Wed, 13 Mar 2002 02:26:06 GMT, Syver Enstad wrote: >peter.schwalm at epost.de (Peter Schwalm) writes: > >> > >It is a bug in the NT command prompt. Works OK in Win2k. I >> believe >> >> > >there is a FAQ on it too. >> > > >> You state that *output* redirection works OK in Win2k. I could verify >> that, but unfortunately it's not true for the redirection of *input*. >> If I want to redirect input, I still have to use the form >> >> python myprog.py > >> instead of the simpler >> >> myprog >Yes, this is a pain in the ass to say the least. Especially since >myprog.py has to be in the current directory(or be fully specified) in >the first version, while it just has to be situated in the os path in >the second. > If you wrap it in a .cmd file the myprog.cmd doesn't have to be fully specified, just on the path. It probably pays to specify the path to the script fully inside the wrapped command unless you want the other effect., since it avoids searches, might as well specify python.exe fully too. But I didn't in the following. Your "myprog < inputfile" works: -- >echo "This is text in inputfile." > inputfile >type myprog.py import sys sys.stdout.write(sys.stdin.read()) >type myprog.cmd @python myprog.py %* >myprog < inputfile "This is text in inputfile." >myprog < inputfile >outputfile >type outputfile "This is text in inputfile." -- >Has anyone pointers to any information regarding this problem, which >is an OS problem as far as I can see. It leads to Python programs not >being quite real executables under the win2k and probably other win32 >os'es, which is a shame since Python is such an intensely practical >tool. > I just use .cmd wrapping and put my utilities in c:\util and have that on the path. It's a minor pain, but then you can type normally. BTW, if you set the PATHEXT variable in NT4 (don't know others for sure) to include .PY, then you can type myprog without the .py and the search will go through the path for .py, .com, .bat, .exe, and whatever. set PATHEXT=.PY;.COM;.EXE;.BAT;.CMD will give priority to myprog.py over myprog.exe, etc. (though you don't want to put .PY first, because then you can't call a .cmd wrapper of the same name without using the extension, and you still have to wrap if you want to redirect i/o). I tried setting up a test association of .pyt to cmd.exe right in the ftype setting, and and it works, but still no redirection. Maybe it's possible to write a special launcher and associate to that, but if it is, it will probably take some horrible special-code-in-title-bar windows search for parent or something like that. IIRC, some Perl hackers facing the problem worked up some Rube Golberg thing to get the proper effect without wrapping, but I don't think it was 100.000%. Quite a while ago I wrote a win32 prog which read stdin fed by a pipe, and there were a lot of hoops to jump though in order to get all the data reliably and not get broken pipes, as I recall. It struck me as really ugly at the time, and I think they had some pipe problems, so maybe it's part of the same syndrome. If they finally fixed it in win2k, great (assuming the EULA is acceptable, and I can install w/o internet). Anyway, ISTM the windows legacy was about windows messages and polling loops, with stdio pretty much relegated to DOS programs accessing virtualized BIOS through c stdio library modules, running in a VDM. I'd guess stdio didn't get its share of attention outside of the DOS or pseudo-DOS environment, and wasn't a primary element in architecting cooperative processes at first. I.e., try to ignore Unix and you will be doomed to re-inventing it incrementally ;-) >I've tried some Google searches for this problem, but have not come up >with anything. How are other scripting languages doing? > It is the same for Perl, and will work the same for any interpreter or program started by file extension association, unless it is a native executable, I believe. Hm... I'd bet you could do what self-extracting zip files do, though. They have a native .exe part that gets run normally, and the data is incorporated in the .exe file. I'd bet you could make a python script launcher somehow that way (not by prefixing the whole interpreter, obviously, but exec-ing it). It might mean making the python interpreter recognize how to skip an .exe prefix when it gets control (new invocation option?) to avoid unnecessary copying, but it feels doable. Thinking via keyboard again... Regards, Bengt Richter From Answer.via.news.please.prikryl at skil.nospam.cz Wed Mar 27 07:04:41 2002 From: Answer.via.news.please.prikryl at skil.nospam.cz (Petr Prikryl) Date: Wed, 27 Mar 2002 13:04:41 +0100 Subject: Newbie: What the 'PEP' means? References: Message-ID: Oh, just found it... I wrote... > Just curious -- what the acronym PEP with a number means? Python Enhancement Proposal P. -- Petr Prikryl (prikrylp at skil dot cz) From NO_SPAM_jmpurser2 at attbi.com Tue Mar 12 18:05:35 2002 From: NO_SPAM_jmpurser2 at attbi.com (John Purser) Date: Tue, 12 Mar 2002 23:05:35 GMT Subject: struct.calcsize() giving odd results Message-ID: <3Rvj8.27781$af7.23161@rwcrnsc53> I'm reading from a binary file with a 180 byte record length. I created a format string using a seriously long stiring made up of: x c h i 15s, 31s, 2s And that's it. I tucked this into a variable (fmt) and ran it through struct.calcsize(fmt) and got 190. I assumed I'd made a typo so I went over my string. No problems there. So I assumed I added it up wrong in the first place. Nope, 180 bytes. I checked each charachter with struct.calcsize() to be sure it was giving the expected value. It was. Then I started removing charachters from the end of my format string. The first two 'c's reduced the count to 188 as expected. Then I removed an 'i' and the count dropped to 181!!! I took out another 'i' and the count dropped to 177. I've duplicated this on Debian Linux (Python 2.1) and Windows 2000 (Python 2.2) using the Idle interactive shell. Can anyone tell me what I'm doing wrong or is this a known bug? I'm new to python and working on my first project so I'd really appreciate the help. John Purser Idle session snapshot: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import struct >>> dog = 'x i 15s 15s 15s 15s 31s 2s c c c c c i i i i h i i i 31s c i c c c c c i c c' >>> struct.calcsize(dog) 190 >>> dog = 'x i 15s 15s 15s 15s 31s 2s c c c c c i i i i h i i i 31s c i c c c c c i' >>> struct.calcsize(dog) 188 >>> dog = 'x i 15s 15s 15s 15s 31s 2s c c c c c i i i i h i i i 31s c i c c c c c' >>> struct.calcsize(dog) 181 >>> From James_Althoff at i2.com Tue Mar 5 15:55:29 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 12:55:29 -0800 Subject: Status of PEP's? Message-ID: [James_Althoff] > Just keep in mind that indici/indices/indexes-type proposals don't > help in cases where __len__ is not defined. Two-dimensional > structures, for example. [Greg Ewing] > It does if we define an __indices__ protocol to > go with it. First look for __indices__, then fall > back on __len__. Again, the key point that I was trying to illustrate is that with the expanding world of Python (a very good thing, right?) -- into the realm of Java API's via Jython, for example -- it is not going to be possible to just insist that every class that one deals with be fixed to obey some new protocol. The various kinds of tables one deals with in Java via Jython, for example. Jim From martin at v.loewis.de Sun Mar 31 17:07:32 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Apr 2002 00:07:32 +0200 Subject: PEP 285: Adding a bool type References: <3CA751EF.10F25F2D@ndh.net> Message-ID: Stefan Schwarzer writes: > Regarding special uses such as RPC and databases it would suffice to > add a "boolean" module to the standard library. This would offer a > standard way to handle a boolean type for these special purposes, > wouldn't it? How would it be different from what the PEP proposes? Regards, Martin From sdm7g at Virginia.EDU Thu Mar 7 11:36:09 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Thu, 7 Mar 2002 11:36:09 -0500 (EST) Subject: Problem with popen() and a regular expression In-Reply-To: <3C84C4F3.4090205@bath.ac.uk> Message-ID: On Tue, 5 Mar 2002, Simon Willison wrote: > marduk wrote: > > You're better off using htmllib (and httplib for that matter). I haven't > > looked at your examples, but I can tell just by looking at your code that > > it will fail, for example, when "" and "" are on seperate > > lines in the HTML. Also, I might be mistaken, but it doesn't look like > > you are re search is case insensitive. > > > > Either way, try the htmllib. It takes care of all that stuff for you! > > I'd love to (mainly to avoid the averhead of running lynx about a > hundred times) - unfortunately my University web server doesn't have the > socket module properly installed which means nearly all of the web > related python modules won't run :/ You could install _socket.so somewhere under your own home directory and add it to PYTHONPATH. ( Although I'm not sure how they could get it inproperly installed -- all it takes is 'make install' -- unless there are some particular problems with the architecure you're on. ) -- Steve Majewski From rjk at grauel.com Thu Mar 21 10:50:57 2002 From: rjk at grauel.com (Richard J Kuhns) Date: 21 Mar 2002 15:50:57 GMT Subject: A question about generators References: Message-ID: Tim Peters writes: > [Richard J Kuhns] > > That's pretty much what I ended up doing -- I put a "while 1:" loop > > around the rest of the code in the generator, and I test a "reset > > generator" variable after each yield. If it's set, "continue" the > > while loop. It's kind of nasty-looking, but it seems to work. > > Make the generator a method of a class. Give class instances a "reset > generator" variable. Give the class a reset() method to set this variable. > Then it's all nice, abstracted, reusable, and self-contained. > > a-feature-in-isolation-is-a-feature-doomed-to-misuse-ly y'rs - tim > That's EXACTLY what I did :). The main reason I had problems to start with is that almost everything I've done with python feels more-or-less "elegant", and this doesn't. Like I said, though, it works and it's pretty much hidden from view. -- Richard Kuhns rjk at grauel.com PO Box 6249 Tel: (765)477-6000 \ 100 Sawmill Road x319 Lafayette, IN 47903 (800)489-4891 / ______________________________________________________________________ Posted Via Uncensored-News.Com - Still Only $9.95 - http://www.uncensored-news.com With NINE Servers In California And Texas - The Worlds Uncensored News Source From aahz at panix.com Sun Mar 3 23:34:12 2002 From: aahz at panix.com (Aahz Maruch) Date: 3 Mar 2002 20:34:12 -0800 Subject: PEP 234 little bug? References: <3c817238@nntp.server.uni-frankfurt.de> <3C817FC1.A155DBAB@earthlink.net> <3C82A23F.84C66941@earthlink.net> Message-ID: In article <3C82A23F.84C66941 at earthlink.net>, Hans Nowak wrote: > >Should it be? This may be a dumb question, but are there important >reasons to do this, besides conformance with the PEP? I mean, the >current situation does do the job; "for line in file" works. What >would be the additional benefit of making a file its own >iterator? The following code would work correctly: for line in file: if line == 'foo': break for line in file: pass -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From DavidA at ActiveState.com Thu Mar 28 17:48:38 2002 From: DavidA at ActiveState.com (David Ascher) Date: Thu, 28 Mar 2002 14:48:38 -0800 Subject: PEP262 - database of installed packages References: <20020328112544.A13176@ActiveState.com> <20020328200710.GA26312@crystal.mems-exchange.org> Message-ID: <3CA39DC6.AA3CF28A@activestate.com> Andrew Kuchling wrote: > Here's another question: is there any explanation of how version > numbers are handled? distutils/version.py has extensive examples in > the docstrings for the StrictVersion and LooseVersion classes, and I'm > wondering how they'd be mapped to PPD's version tuples. The PPD man > page on aspn.activestate.com gives an example version tuple as > "4,2,0,0", but it's not clear how that maps to a version number, or > what a version number such as 2.2.1a3 would be translated to as a > tuple. The current PPM3 does version comparison on the server using an algorithm which was designed for Perl (conversion to tuple is done through the equivalent of tuple(foo.split('.')). We could change it to do whatever makes sense for Python. There are lots of other questions which come up that I mean to bring up in the discussion of the PEP. For example, I don't particularly like the fact that bdist_wininst creates a separate "program" in the Add/Remove dialog on Windows. I know why it does, but it'd be nice to have something more granular and Python-specific, and that scaled a bit better. Having struggled with distutils/PPM interactions a fair bit in the last few weeks, I'm keen to help come up with a solution which works for distutils, Python and PPM. Let's continue this discussion on the distutils-sig? --david From john at yahoo.com Sat Mar 23 02:28:03 2002 From: john at yahoo.com (John Warney) Date: Sat, 23 Mar 2002 07:28:03 GMT Subject: Core Python Programming, chapter 5 exercises number 5-3, question on this exercise Message-ID: <8dbo9u8jv0j9p58h4dvhqojk2154m8vict@4ax.com> I have read pretty much every page of the book till now. On this question it says to take a test score input from the user and output letter grades acording th the following scale/curve...... The issue i am having is the book hasnt covered standard input yet. If i am wrong please correct me b/c i am stumped on this question and most like the others until i find out from reading the rest of the book. Rob From eppstein at ics.uci.edu Fri Mar 15 10:48:37 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 15 Mar 2002 07:48:37 -0800 Subject: ANN: Python Imaging Library 1.1.3 (march 15, 2002) References: Message-ID: In article , "PythonWare" wrote: > the secret labs proudly presents PIL 1.1.3: > > The Python Imaging Library (PIL) adds image processing capabilities > to your Python interpreter. This library supports many file formats, > and provides powerful image processing and graphics capabilities. > > Version 1.1.3 adds distutils build scripts, improved resampling, > screen grabbing support (windows only), and more. Any chance of adding box filters for higher quality downsampling? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From tchur at optushome.com.au Fri Mar 15 17:50:32 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 16 Mar 2002 09:50:32 +1100 Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: <3C927AB7.54B10227@optushome.com.au> Bengt Richter wrote: > > On Fri, 15 Mar 2002 12:26:30 -0800, "Nick Arnett" wrote: > > >Anybody have any experience generating word frequencies from short documents > >with Python and Perl? Given a choice between the two, I'm wondering what > >will be faster. And a related question... any idea if there will be a > It'll take 15 minutes to get a program working in Python ;-) > Ok, maybe a bit longer if your docs have tricky syntax to write > a splitting regex for ;-) > > >significant performance hit (or advantage?) from storing the data in MySQL > >v. my own file-based data structures? > > > If all you want is to be able to get it back within another (or the same, later) > Python program, check into the pickle module. You could just dump the directory > of directories I describe below, I believe. > > >I'll be processing a fairly large number of short (1-6K or so) documents at > >a time, so I'll be able to batch up things quite a bit. I'm thinking that > >the database might help me avoid loading up a lot of useless data. Since > >word frequencies follow a Zipf distribution, I'm guessing that I can spot > >unusual words (my goal here) by loading up the top 80 percent or so of words > >in the database (by occurrences) and focusing on the words that are in the > >docs but not in the set retrieved from the database. > > > >Thanks for any thoughts on this and pointers to helpful examples or modules. > > > I'd just code up a short Python program using a python dictionary with words > as keys and counts as values for each file, and put all these word frequency > dictionaries in a file dictionary with keyed by file name. > > I'd bet everything fits in memory, unless you have an incredible corpus of > words in your files, or small memory. > > Isolating words will depend on document syntax etc. You may be able to do it > by splitting with a compiled regular expression for a combination of white > space and punctuation. I concur with Bengt's suggested approach, plus you might want to use something like the Porter Stemmer algorithm to convert words to their "base" forms eg stepped -> step See http://www.tartarus.org/~martin/PorterStemmer/python.txt for a Python implementation. Tim C From eshorkey at rightbracket.com Wed Mar 20 23:38:41 2002 From: eshorkey at rightbracket.com (Eric Shorkey) Date: Wed, 20 Mar 2002 23:38:41 -0500 Subject: Embedded Python Requirements References: Message-ID: <3C9963D1.9050600@rightbracket.com> I think I found it. The first three lines are generated within getpath.c. Specifically, they show up when a directory named lib-dynload isn't found within the module path. On a normal install it is /usr/lib/python2.2/lib-dynload. It doesn't care if the directory is empty, just as long as it exists. I'm going to be changing getpath.c anyhow, so this won't impact my needs at all, but I thought I would share. The last error "'import site' failed; use -v for traceback" shows up when site.py fails to be properly imported. Either the file wasn't in the module path, or there was an error in the file. Both of these were corrected by setting the environment variale PYTHONPATH to a directory that contained an empty site.py and an empty lib-dynload directory. I'll probably end up looking for the default inclusion of the 'site' module. It's somewhere in the source, so grep and I will eventually find it. Still, I'd like to know what the site module is supposed to provide. It appears to do nothing but add to the search path and include a site customization module if it exists. Really, this appears to have no real use in an embedded environment. Truly embedding python would mean that a local python install would not be a requirement. All extension modules would be contained in directory separate from the usual python install base. Most likely it would be a subdirectory of the application python was embedded into. I'd be really nice to get a ./configure option to kill the auto include of the site module. Also, some functions for overiding the usual getpath.c activities would be nice as well. Perhaps allowing the embedding application to specify the search paths for modules before initializing the interpreter. Cheers, Eric Eric Shorkey wrote: > I'm having a little trouble making a self reliant embedded build of > python. > I've looked at Demos/embed/demo.c, and I understand it just fine, but > the python interpretter is generating errors on startup. > > Could not find platform independent libraries > Could not find platform dependent libraries > Consider setting $PYTHONHOME to [:] > 'import site' failed; use -v for traceback > > This occurs seemingly regardless of how I build libpython2.2.a. > From searching previous posts, I'm able to remove the first three > lines by simply setting PYTHONHOME in the environment. It doesn't > matter whether the path is valid or not. Alternatively I could > redefine my own Py_GetPath() Py_GetPrefix() Py_GetExecPrefix() and > Py_GetProgramFullPath(). I probably will do just that. So these are > not really the problem. > > It's the last error that really has me baffled. I understand that the > site module is always imported when the interpreter starts, but I > really need to build my app completely self sufficient. So the site > module will either have to be statically included, or it's necessity > will have to be removed. > > Is it possible to statically link in the site module? And what exactly > does the site module provide that is so important that it is included > by default? I'd like to know, because I may be able to simply do away > with it. > > Thanks! > From hamish_lawson at yahoo.co.uk Thu Mar 7 10:29:38 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 7 Mar 2002 07:29:38 -0800 Subject: Pep 276 - if 6 were 9 References: Message-ID: <915a998f.0203070729.5a6f0008@posting.google.com> Emile van Sebille wrote: > If, in the beginning, Guido opted to call 'in' 'of', would there be a > question of iterating over an integer? > > For example, > > for each of range(6): > for each of mylist: > for each of 6: I would expect 'for each of 6' to produce just 6, so my answer would be 'No'. Hamish Lawson From gerhard at bigfoot.de Sat Mar 2 11:12:18 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 2 Mar 2002 16:12:18 GMT Subject: Profiling extensions References: Message-ID: Greg Landrum wrote in comp.lang.python: > [Linux, python 2.1] > Hi All, > > > I've got a Boostified C++ class that I'm using from Python. The class > supports pickling, but restoring things from pickles seems to be really, > really slow. I figured that I'd profile the code and find out where the > time is being spent, but I ran into a wall. > > I built both my extension modules and python itself with -pg. Running a > test case and looking at the gprof output only shows me numbers for the > python interpreter itself. This is none too edifying. > > So, my question is: is there any way to trick gprof (or prof, I don't much > care) into gathering data for the extension modules as well as the > interpreter? I had that problem once, too. My "solution" was to embed Python and the extension library into a statically linked minimal test application. Then, I just set PYTHONPATH=. and called the init function of the extension module. In the minimal application I then just ran my test sript with Py_Run... This workaround did it for me, but I'd be interested in a proper solution to profiling extension modules as shared libraries nevertheless. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From cce at clarkevans.com Fri Mar 15 23:58:28 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Fri, 15 Mar 2002 23:58:28 -0500 Subject: [].keys() and [].items() (Was: Why I think range is a wart) In-Reply-To: ; from huaiyu@gauss.almadan.ibm.com on Thu, Mar 14, 2002 at 12:18:13AM +0000 References: Message-ID: <20020315235828.A9847@doublegemini.com> On Thu, Mar 14, 2002 at 12:18:13AM +0000, Huaiyu Zhu wrote: | On Wed, 13 Mar 2002 22:39:02 GMT, Terry Reedy wrote: | >> I would like to see: | >> .keys() | >> .items() | | Question: Which is better: items(x) or x.items()? Does it have to be mutually exclusive? Python has a tradition of enabling both mechanisms. | I think items(x) can just piggy-back on the current iterator protocol, and | can be made to work on any iteratable objects. Would "keys()/items()" be compatible with the iterator proposal? It would be extending the iterator to return pairs... this might be a bit divergent... | On the other hand, x.items() has to be implemented by each and every | list-like classes. Their subclasses need to override them whenever | necessary. I like x.keys() and x.items() since it is _currently_ how maps work already... extending the behavior to lists makes sense to me and I don't have to "think about it". As for the implementation difficulty, a generic "mix-in" implementation can be provided; or even more simply one could just assign self.items = items; self.keys = keys. | So else being equal, I'd prefer items(x) to x.items(). I don't see why we can't have our cake and eat it too. ;) | Question: Which is better name: keys or indices? items or indexed? I have a strong opinion here... use the same function names as used by a map! A list is really just a map such that the domain is limited to positive integers. Having a different set of names isn't a good idea. | I think the latter two (indices, indexed) are more descriptive of sequence | types. This is especially true if one ever want to use a seqdict type. Ick. | Question: Which name is better: iterkeys or xkeys? Which ever works for maps; the decision should be shared as a list is a special map with a limited domain. Best, Clark From greg at cosc.canterbury.ac.nz Sun Mar 24 22:41:40 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 25 Mar 2002 15:41:40 +1200 Subject: 2.2 open References: <1UtsCLAcngn8EwWc@jessikat.fsnet.co.uk> Message-ID: <3C9E9C74.781B3911@cosc.canterbury.ac.nz> Robin Becker wrote: > > So the question now is, how do I tell if __import__ is the built in one > even if the import system is not fully initialized. You could compare its type with what you really should have been comparing it with in the first place: import types if type(__import__) == types.BuiltinFunctionType: ... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From gcordova at hebmex.com Wed Mar 13 16:01:11 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 13 Mar 2002 15:01:11 -0600 Subject: sorting nested dictionary Message-ID: <19650FF08A99D511B19E00B0D0F0632301D6894C@SRM201002> > > thanks. the following solution was also sent, seems to work, > but i don't know why ... > > --------------------------------------------------------- > from pprint import pprint > h = {'ids': {'2778xxxxx': {'weighted': 4.6, 'raw': 5.0}, > '3059xxxxx': {'weighted': 6.1, 'raw': 6.0}, > '3188xxxxx': {'weighted': 3.2, 'raw': 4.0}, > '3216xxxxx': {'weighted': 10.1, 'raw': 7.0}, > '3257xxxxx': {'weighted': 9.7, 'raw': 9.0}, > '3266xxxxx': {'weighted': 4.8, 'raw': 3.0},}} > > def compare(a, b): > return cmp(a[1]['weighted'], b[1]['weighted']) > > pairs = h['ids'].items() > pairs.sort(compare) > > pprint (pairs) > > ---------------------------------------------------------- It works because.... >>> pairs = h['ids'].items() Now, "pairs" contains a list of tuples, in the form: pairs = [ ( '2778xxxxx', {'weighted': 4.6, 'raw': 5.0} ), ( '3059xxxxx', {'weighted': 6.1, 'raw': 6.0} ), ( '3188xxxxx', {'weighted': 3.2, 'raw': 4.0} ), ( '3216xxxxx', {'weighted': 10.1, 'raw': 7.0} ), ( '3257xxxxx', {'weighted': 9.7, 'raw': 9.0} ), ( '3266xxxxx', {'weighted': 4.8, 'raw': 3.0} ) ] The expression "a[1]['weighted']" returns tne value of the item "weighted" of the second element of a tuple, so the function def compare(a,b): return cmp(a[1]['weighted'],b[1]['weighted']) returns the comparison of the "weighted" sub-element of tuples a and b. So now, you simple sort the list, specifying this function as the comparison function to use: pairs.sort(compare) ta-daa. Ain't Python the best? damn... so powerful, and so easy to understand. -gustavo From emile at fenx.com Thu Mar 28 18:03:44 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 28 Mar 2002 15:03:44 -0800 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <001d01c1d67f$2eb81090$445d4540@Dell2> Message-ID: "Charl P. Botha" wrote in message news:slrnaa6uf4.d4j.cpbotha at crabtree.cpbotha.net... > In article , > David Ascher wrote: > > Thanks for all the interest in ActivePython. We hope to not have these > > kinds of delays in the future. > > Just remember not to split your infinitives in the future. ;) > There is no longer consensus that splitting infinitives is wrong due to the awkward constructs avoiding it often gives rise to. -- Emile van Sebille emile at fenx.com --------- From peter at engcorp.com Sun Mar 3 23:37:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 03 Mar 2002 23:37:04 -0500 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> Message-ID: <3C82F9F0.2A2DBF16@engcorp.com> Brian wrote: > > z = [MyClass() for i in xrange(y)] > > Is there a way to do this without the use of i? The big advantage being? (I'd suggest if you're just trying to save typing five keystrokes that you find more critical things to work on first.) -Peter From cjensen at bioeng.ucsd.edu Tue Mar 5 12:33:39 2002 From: cjensen at bioeng.ucsd.edu (Curtis Jensen) Date: Tue, 05 Mar 2002 09:33:39 -0800 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> Message-ID: <3C850173.4050004@bioeng.ucsd.edu> The only disappointing parts for me were: The cover, definitly didn't seem targeted to the college crowd, but more to highschoolers. No chapters on extending Python with C. The XML chapters seemed to be an attempt to jump on the band wagon and sell books. All in all, I think the book is well written. The examples are usefull enough to figure out what is going on without reading the chapter (good for lazy programmers). I lent it to a (non-programmer) friend and he found it more useful than the O'Reilly Python book. Also, if your main intent for reviewing the book was for the money, I'd suggest playing the lotto instead. Don't be so arogant that you think that your time is so precious as to complain about a temporary, predeterimined, pay scale. They were upfront in their monatary compensation. If you don't like it, don't review the book. -- Curtis Jensen cjensen at bioeng.ucsd.edu http://www-bioeng.ucsd.edu/~cjensen/ FAX (425) 740-1451 From bernie at 3captus.com Wed Mar 13 19:20:39 2002 From: bernie at 3captus.com (Bernard Yue) Date: Thu, 14 Mar 2002 00:20:39 GMT Subject: Zope Message-ID: <3C8FED4D.A8C0470@3captus.com> Hi, Are there anybody using Zope 2.4.3 with Python 2.2 in production environment? Problems? Thanks in advance! Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From gargravarr at whoever.com Sat Mar 30 17:47:25 2002 From: gargravarr at whoever.com (gargravarr at whoever.com) Date: Sat, 30 Mar 2002 22:47:25 GMT Subject: CGI/modpython ??? References: Message-ID: <3ca63f80.30910126@news.tiscali.no> If you are using Linux, there's a mod_snake for the Apache web-server server. Haven't tried it though, since I realized I could use Python with CGI instead. Much simpler for my taste. Mod_python has some 'handler' thing, which I couldn't really get working. You sort of had to use mod_python this way: http://somewhere/test.py/test2 where test2 had to be a function in the in the test.py script. On Sun, 31 Mar 2002 10:49:44 +0930 (CST), Michael Hall wrote: > >I've got to stop replying to my own emails ... > >Anyway, further to my last two posts (see below), I have another question >or two: > >- modpython hasn't been updated for a while ... is it still being >developed? > >- where is HTML-embedded Python at? modpython's author refers to several >different systems in circulation and a lack of consensus on how to do it. > >Thanks again > >Mick From tanzer at swing.co.at Thu Mar 7 12:48:13 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Thu, 07 Mar 2002 18:48:13 +0100 Subject: Order of constructor/destructor invocation In-Reply-To: Your message of "Thu, 07 Mar 2002 15:09:42 +0100." <3C8774A6.52CF7F3A@spam.nada.kth.se> Message-ID: Bj?rn Lindberg wrote: > > void a_function () > > { > > sentry1 s1, s2; > > ... > > } > > > > ? Will s1 be destructed before s2 by all compilers? Guess, I never > > cared about that because I tend to use multiple declarations myself. > > The destruction order is always opposite of the construction order. Agreed. I relied on that. > In this example s1 will be constructed first followed by s2. And here I am wary. Does the standard prescribe this? For normal expressions at least, you can't rely on evaluation order. But then, in comma separated expressions you can. So maybe this is safe after all. Don't-really-want-to-refresh-my-C++-ly yr's, -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From jlh at cox.net Wed Mar 6 22:04:42 2002 From: jlh at cox.net (Jeff Hinrichs) Date: Thu, 07 Mar 2002 03:04:42 GMT Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: "Geoff Gerrietts" wrote in message news:mailman.1015439904.7322.python-list at python.org... > Quoting Ramkumar Kashyap (rkashyap at sympatico.ca): > > This is extremely non-intuitive to most people. Most 5,6,7 year olds > > can speak fluently in their native languages, but how many of them could > > tell you about vowels, consonants, nouns, verbs, adjectives. In fact > > quite a few of them speak multiple languages, can easily differentiate > > sentence structures in those languages, but would be hard-pressed to > > give defintions of the above. > > > > So how come in programming, we ALWAYS jump into the constructs of a > > language, rather than just doing, gaining proficiency and then > > understanding how it is put together? > > I think the analogy here is interesting and useful, and bears > consideration. I think that what you're asking for -- a reexamination > of the pedagogy surrounding computer programming -- is useful. > > I would hesitate to suggest that your methodology is exactly > appropriate, though. Here's why: > > - Go speak to a five or six year old child for a few hours. Engage > them in any conversation you like, but make them talk, make them use > the language for an expressive purpose. Their facility with the > language is reasonable at this age, but far from mastery. Only the > mentally disabled standardize at this level; even the stupid > standardize at grade 5 or older. > > - Observe a two or three year old. Engage this child in conversation. > It won't last long, but try it. > > For the space of around three years, a child is immersed almost > constantly, from waking to sleep, and even sometimes while asleep, in > language. For those first three years, the child is almost completely > incapable of making him or herself understood. *BUZZ* Sorry, but as a parent I can firmly say that children can make a point well before 3 years. In fact, by 12-16 months they have the ability to utter rudimentary words, associate action and reaction and are deeply focused on interpersonal relationships, among other things. First words are normally, familial (i.e mom/dad/et al), then "NO," then "More" with a slew of words of interest to them come next. > Some of this is the challenge of spoken language, the challenge of > making your voice modulate to form the right sounds. Much research > exists to show how young children can learn to sign long before they > can learn to speak; if you eliminate the difficulty of speaking, you > might get it down to age 2 or so. That's still 2 years in which the > child can barely be understood if at all, and another three before the > most basic constructs are reliably produced. > > People don't get smarter as they get older, they just have a better > foundation for building on. It would be just as difficult for someone > to learn programming through reading or transcribing lots of text as > it would be for someone to learn French by riding the Metro all day > long. This depends on how you define "smart." I refer to smart as the mixture of wisdom + experience + ability to intuit. > People don't get "smarter" as they get older, though they do develop > strategies for learning that enable them to learn things more quickly. > Most of those strategies revolve around identifying patterns early, > and spending most of the learning time exploring the "borderline > behavior" that describes the limits of the pattern. > > That's why we go into constructs early, because those are the > patterns. The next step for the educated learner is to explore the > limits of these patterns -- what they can and can't do. This is where > a great deal of practice can be immensely useful. > > A heavily practice-based pedagogy could be a very good thing, > especially if the practical applications were designed to explore > recently-introduced concepts to show when the pattern applies, and > when it does not. > > My belief is that most people find computer programming to be > difficult because logic is not the natural way people think; it is a > forced mode. People tend to think intuitively, using "gut feelings" > and good guesswork. That's the way we tend to summarize the knowledge > of our experiences: as gut feelings. I agree with you here. > Expressing things in a purely logical fashion is consequently > difficult for people, and very few ever receive formal training in > logic. What's worse is that trying to teach logic at the fundamental > level doesn't immediately apply. Logic itself is a tool that a person > must learn to use, and could easily fill several courses by itself. > > -- > Geoff Gerrietts "Punctuality is the virtue of the bored." > --Evelyn Waugh I do believe that Ramkumar's point is valid. Children, especially the young, suffer from fewer of the social pressures that retard adult learning. The most salient, is the disregard for being wrong. Adults, I believe, hamper their own learning process by limiting their questions or not asking them if they feel that by exposing their "knowledge holes" they are negatively impacting the social surroundings. (i.e. Don't want to look stupid in front of the class.) Unfortunately, the fastest way to learn something new is to expose your limited knowledge to the teacher/instructor/peers so that they can more effectively rid you of misconceptions and fill-in those "knowledge holes." I have a strong suspicion this is why adults have a relatively more difficult time learning new spoken languages than children do. (vocabulary that is, pronunciation is another issue) From huaiyu at gauss.almadan.ibm.com Tue Mar 5 14:16:33 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 5 Mar 2002 19:16:33 +0000 (UTC) Subject: map-like function on dict values? References: Message-ID: On Sat, 2 Mar 2002 03:46:52 -0500, Raymond Hettinger wrote: > >def tunedmap(f, d): > return map( d.__setitem__, d.keys(), map(f, d.values()) ) > Yes, that's a good point. Since there are so many variations on this theme, I decided to do it thoroughly last weekend. It turns out that the most traditional approach (iterkv) is the odd one out - It is many times slower than the rest, which are all similar. Why? #!/usr/bin/env python from time import clock def emptyloop(f, d): for i in xrange(len(d)): pass def emptyloopcall(f, d): for i in xrange(len(d)): f(None) def iter(f, d): for k in d: d[k] = f(d[k]) def iterk(f, d): for k in d.keys(): d[k] = f(d[k]) def iterik(f, d): for k in d.iterkeys(): d[k] = f(d[k]) def iterkv(f, d): for k, v in d.items(): d[k] = f(v) def iterikv(f, d): for k, v in d.iteritems(): d[k] = f(v) def mapv(f, d): map(d.__setitem__, d, map(f, d.values())) def mapiv(f, d): map(d.__setitem__, d, map(f, d.itervalues())) def mapkv(f, d): map(d.__setitem__, d.keys(), map(f, d.values())) def mapkiv(f, d): map(d.__setitem__, d.keys(), map(f, d.itervalues())) def mapikv(f, d): map(d.__setitem__, d.iterkeys(), map(f, d.values())) def mapikiv(f, d): map(d.__setitem__, d.iterkeys(), map(f, d.itervalues())) def timeit(test, f, d): _time = clock() test(f, d) print test.__name__, clock() - _time if __name__ == '__main__': def f(x): pass d = {} for i in xrange(1000000): d[i] = None timeit(emptyloop, f, d) timeit(emptyloopcall, f, d) timeit(iterik, f, d) timeit(iter, f, d) timeit(iterikv, f, d) timeit(iterk, f, d) timeit(mapikv, f, d) timeit(mapv, f, d) timeit(mapkv, f, d) timeit(mapikiv, f, d) timeit(mapiv, f, d) timeit(mapkiv, f, d) timeit(iterkv, f, d) """ Output emptyloop 0.83 emptyloopcall 2.81 iterik 3.58 iter 3.62 iterikv 3.72 iterk 3.92 mapikv 4.63 mapv 4.64 mapkv 4.93 mapikiv 5.68 mapiv 5.76 mapkiv 5.91 iterkv 25.57 """ From michael at stroeder.com Thu Mar 14 08:09:57 2002 From: michael at stroeder.com (=?ISO-8859-15?Q?Michael_Str=F6der?=) Date: Thu, 14 Mar 2002 14:09:57 +0100 Subject: Python-DB2 module and DB2 Connect Message-ID: <3C90A125.4020208@stroeder.com> HI! Anyone here which had success with using DB2-Python-0.991 (see ftp://people.linuxkorea.co.kr/pub/DB2/) build against DB2 Connect? Ciao, Michael. From jeff at ccvcorp.com Thu Mar 21 15:45:35 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 21 Mar 2002 12:45:35 -0800 Subject: #define equivalents and config files References: <3C9963BD.1040304@verizon.net> <3C9964FF.46805590@engcorp.com> Message-ID: <3C9A466F.7D6D6AE9@ccvcorp.com> Dave Swegen wrote: > > Rich Salz wrote: > > > > > > > Is there a pythonic way of doing something similiar to Cs #define? > > > >... are globals the only way to go? > > > > > > You can at least make them class attributes > > > class constants: > > > pi = 3.14159 > > > e = 2.71828 > > > adding your own setattr can serve to make them read-only. > > I'm basically after a single file where such values can be stored, and > then used in various parts of the program without having to pass extra > configuation variables around. One option that I have used, is to create a separate module called constants.py, and defined my constants/configuration variables there. Then, every module in my project can simply do something like: import constants area = constants.pi * (radius ** 2) You can use some interesting hacks to make the constants module read-only, if necessary (see the ASPN Python Cookbook), but since I'm typically the only person using my code I've decided to simply trust myself. ;) Jeff Shannon Technician/Programmer Credit International From loewis at informatik.hu-berlin.de Fri Mar 15 08:32:19 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 15 Mar 2002 14:32:19 +0100 Subject: how do i get xml.sax.make_parser() to work on solaris and cygwin python References: Message-ID: ayinger1 at pacbell.net (andrew) writes: > it looks like neither cygwin nor solaris python installation includes > expat libraries. any idea how i can get this working? You need to obtain a copy of expat from expat.sf.net. Regards, Martin From guido at python.org Sun Mar 31 18:00:37 2002 From: guido at python.org (Guido van Rossum) Date: Sun, 31 Mar 2002 23:00:37 GMT Subject: PEP 285: Adding a bool type References: Message-ID: <3CA79606.A0C1B055@python.org> > What do you think of `truth(x)' for all the good reasons listed > elsewhere in the thread? You used truth yourself instead of Boolean > above. I didn't see any good reasons for calling it truth(). :-) I am reminded of ABC, Python's predecessor. Its designers were very concerned about newbies being confused by traditional computer science terms like "function", "procedure" and "variable", so they invented all new terminology. Functions ended up being called YIELDs, procedures were HOW-TOs, statements became commands, and variables became locations. The main effect this had was to confuse the died-in-the-wool programmers; it didn't make any difference for the newbies because they had to learn the concepts anyway. When you come in with a blank mind it doesn't matter if a particular concept is called "variable" or "waffle" -- you have to learn a new meaning for an existing word either way, and the previous meaning you knew for the word is barely relevant in the new context. So, I am adamantly against using "truth" for the new type -- many languages (all the way back to Algol-60 and Pascal) call it Boolean or bool. Given 'int', 'def' and 'dict', 'bool' feels more Pythonic than 'boolean'. --Guido van Rossum (home page: http://www.python.org/~guido/) From nanacyfinkle at sympatico.ca Wed Mar 20 23:11:25 2002 From: nanacyfinkle at sympatico.ca (Nancy Finkle) Date: Wed, 20 Mar 2002 23:11:25 -0500 Subject: Sociologist uses Python to help prove Slobodan Milosevic's part in Kosovo atrocities... Message-ID: Impressive. http://www.wired.com/news/politics/0,1283,51106,00.html From MaximilianScherr at T-Online.de Thu Mar 7 12:32:25 2002 From: MaximilianScherr at T-Online.de (maximilianscherr) Date: Thu, 07 Mar 2002 17:32:25 -0000 Subject: hexstring to string? Message-ID: i made a function to convert a hex string containing character to a normal string. it looks like this: class ConversionHandler: def ConvertHexToStr(self, hex): letter = 0 str = '' while len(str) < len(hex) / 2: nextletter = letter + 2 str = str + chr(int(hex[letter:nextletter], 16)) letter = nextletter return str hex looks like: 414243 but why does it not work? From erno-news at erno.iki.fi Wed Mar 13 08:04:39 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 13 Mar 2002 15:04:39 +0200 Subject: zlib vulnerabilities and python References: Message-ID: In article , "Fredrik Lundh" writes: | Robin Becker wrote: || Does the recent zlib double free vulnerability impact zlib.pyd? | only if the guys implementing your C library decided to inter- | pret "undefined behaviour" as "force the operating system to | run code designed to take over the computer". | | dunno about MSVC; the CRT documentation only says that | things like this may "cause errors". many malloc implementations use doubly linked lists in a way that could make them vulnerable to this sort of exploit. for the general idea see eg http://security-archive.merton.ox.ac.uk/bugtraq-200010/0084.html -- erno From robin at jessikat.fsnet.co.uk Fri Mar 1 08:21:30 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 13:21:30 +0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7F6765.94A82394@engcorp.com> Message-ID: In article , Thomas Heller writes ..... >> Is there a proper way to get the 8.3 name? > >>>> import win32api >>>> win32api.FindFiles(r"c:\Program Files") >[(49, , , >, 0, 0, 100, 1244528, ' >Program Files', 'PROGRA~1')] >>>> win32api.FindFiles(r"c:\Program Files")[0][-1] >'PROGRA~1' > >Thomas > > thanks, but it would still be better to get the popen methods to work properly wouldn't it? -- Robin Becker From skip at pobox.com Wed Mar 20 13:46:15 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 20 Mar 2002 12:46:15 -0600 Subject: Message bug? In-Reply-To: <9peh9u81e5722mbtgaei2grngvcgu7g2al@4ax.com> References: <99dh9us1b4d8r9u7p5ltt41g34vlun4kjj@4ax.com> <9peh9u81e5722mbtgaei2grngvcgu7g2al@4ax.com> Message-ID: <15512.55543.795874.459018@beluga.mojam.com> Dale> It would be nice to include the module name, though. Patch submitted to SF: https://sourceforge.net/tracker/index.php?func=detail&aid=532638&group_id=5470&atid=305470 Please give it a try. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From BPettersen at NAREX.com Wed Mar 6 13:37:17 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 6 Mar 2002 11:37:17 -0700 Subject: PEP 284, Integer for-loops Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192215151@admin56.narex.com> > From: David Eppstein [mailto:eppstein at ics.uci.edu] > Subject: PEP 284, Integer for-loops Thanks for writing the PEP. I see this as a general proposal for a range syntax, and I disagree with it because: - it doesn't handle the general range issues, i.e. step value, and if we had to add yet another syntax to get general ranges it would be too confusing. - I would like range objects to be first class, ie. I would want to be able to pass ranges to functions, return them from functions, and do all the other things one can do with first class objects. This proposal only adds syntactic sugar to the for loop. - It doesn't make the general case trivial, i.e. for 0 <= i < len(mySequence) is not much better than for i in range(len(mySequence) and is more verbose than for i in len(mySequence). -- bjorn From sjh at shic.co.uk Wed Mar 27 05:44:26 2002 From: sjh at shic.co.uk (Steve) Date: 27 Mar 2002 02:44:26 -0800 Subject: calldll and threads... References: <3CA0F1B4.9060306@skippinet.com.au> Message-ID: Mark Hammond wrote in message > This is a common problem, not just with calldll. Although you released > the lock OK, you will probably find that you did not re-acquire the lock > as calldll made callbacks into your code. What was the callstack when > you crashed? I won't bother you with the call stack (which was most uninteresting - depth 2 in the pre-compiled python.exe when it had an address exception)... I hadn't realised that the C-API calls to PyArg_ParseTuple() or Py_BuildValue() constituted call-backs into Python in the context of the global lock. (I think it would be an improvement if the manual made this point explicitly.) Anyhow... my trivially modified calldll module is now happily allowing me to make blocking calls in spawned threads without blocking all my python threads. All's cheerful this bright spring morning - thanks... Steve From emile at fenx.com Thu Mar 28 18:57:15 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 28 Mar 2002 15:57:15 -0800 Subject: Exceptions and modules / namespaces question References: <1136f745.0203281521.76a1a62c@posting.google.com> Message-ID: Preston Landers > The problem, in a nutshell, is that I can't seem to catch an exception > in the same module it was defined in if the function that raised the > exception is in a different module, because of naming issues. > It seems to me that you have a __main__ vs module1 issue. When module2 imports module1, it gets a new copy, not __main__. > -------module2.py: > > import module1 > > def raise_foo_exception(): > raise module1.FooException("HELLO") > > -------module1.py: > > import exceptions, sys > > class FooException(exceptions.Exception): > pass > > def main(): > > try: > import module2 if you import module1 here > module2.raise_foo_exception() > except FooException, e: then except module1.FooException it may work. Better perhaps to define your exceptions in a separate module and import it into both. -- Emile van Sebille emile at fenx.com --------- From eric.brunel at pragmadev.com Mon Mar 4 09:03:23 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 4 Mar 2002 14:03:23 +0000 Subject: The Text Widget References: <5Hzg8.72869$vP.290047@rwcrnsc51.ops.asp.att.net> <3C82E8C4.24531DE7@tds.net> <3C833DB8.6A4EB165@tds.net> Message-ID: Edward K. Ream wrote: > Are you sure? Yep. Definitely. In fact, we were doing the same thing than you: a syntax highlighting text editor. And we never did any after_idle in it, so you can do it just via regular bindings. > Note that my main testing was done on Windows, if that > makes any difference. It should not: our editor works the same on Windows and Unices. > If you have an example of fancy bindings for Text widgets I'd love to > see it. Thanks. We had indeed to do some bizarre things to be sure that we were informed of anything that happened to the text. This included for example a custom management of the X selection (which has a pre-defined binding under X Windows, but is really hard to catch), and a few other things. We decided that we would work at the line level: changes are identified on lines (not at the character level or for the whole text...). Here is a very simplified example of what we did, just showing how you can catch almost everything that happens on a Text (a few things may have slipped by in the simplification, but hopefully not much): --------------- from Tkinter import * root = Tk() t = Text(root) t.pack() oldSel = 0 ## Prints the current line number and contents def printCurrentLine(prefix=''): l, c = t.index(INSERT).split('.', 1) print '%sCurrent line is %s: "%s"' % \ (prefix, l, t.get("%s.0" % l, "%s.end" % l)) ## Called when a key is pressed def keyPress(event): global oldSel printCurrentLine("Before: ") ## Put a custom tag on the selection at the key press oldSel = 0 t.tag_delete('oldSel') sel = t.tag_ranges(SEL) if not sel: return start, stop = sel[0], sel[1] t.tag_add('oldSel', start, stop) oldSel = 1 ## Called when a key is released def keyRelease(event): printCurrentLine("After: ") ## If the custom tag was set and doesn't exist anymore, ## the selection disappeared if oldSel and len(t.tag_ranges('oldSel')) == 0: print "Selection was deleted" t.bind('', keyPress) t.bind('', keyRelease) root.mainloop() --------------- As I said, there's certainly a few things missing, but starting from that, you should be able to actually identify every single change that happened to your text. HTH - eric - From mnations at airmail.net Fri Mar 22 14:48:45 2002 From: mnations at airmail.net (Marc) Date: 22 Mar 2002 11:48:45 -0800 Subject: Formatting dilema using Grid option Message-ID: <4378fa6f.0203221148.7a01cc4@posting.google.com> I am trying to lay things out with a grid. Here is the code I have right now: ... for testgroup, titles, groupRow, groupCol in testGroups: self.newGroup = Pmw.Group(modFrame, tag_text=titles) for module, row, col, status, color in testgroup: setattr( self.modVar, module, IntVar() ) self.modButton = Checkbutton(self.newGroup.interior(), text=module, state=status, anchor=W, variable = getattr( self.modVar, module)).grid(row=row, col=col, sticky=W ) self.newGroup.grid(row=groupRow, col=groupCol, sticky=NSEW ) ... Basically I have two lists of tuples, testGroups and another list contained in testGroups.All of this works very nicely and I get the layout almost like I want. It more or less looks like this: aaaabbbbcccc bbbbccccaaaa ccccaaaabbbb The only problem is that all of the groups are centered in the middle. The elements in the groups are checkboxes that I want to be aligned on the left side of the boxes. I've fiddled around with as many different options as possible, and finally got the boxes to be equal sizes within the grid. However, I just can't pull everything to the left side of the boxes. How can I do this? Thanks, Marc From maxm at mxm.dk Mon Mar 4 06:49:26 2002 From: maxm at mxm.dk (Max M) Date: Mon, 04 Mar 2002 11:49:26 +0000 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> Message-ID: <3C835F46.2060002@mxm.dk> Siegfried Gonzi wrote: Nice report from the trenches! But your code seems a little verbose. Maybe I have misunderstood the requirements but how about something like (untested): def readInFloats(file,nHeader=0, whatDel=',',NaN='NIL',NaN_NumPy=-1.0): result = [] f = open(file,'r') rows = f.readlines() f.close() for row in rows: resultCol = [] columns = row.split(whatDel) for col in columns: try: col = float(col) except: col = NaN_NumPy resultCol.append(col) result.append(resultCol) if len(result[-1]) == 0: # empty row in the end? return result[:-1] else: return result That should return a list of rows, that are lists of numbers. > def readInFloats(file,nHeader=0, whatDel=',',NaN='NIL',NaN_NumPy=-1.0): > f = open(file,'r') > s = f.readlines() > # > cols = 1 + s[nHeader].count(whatDel) > rows = len(s) > ergArray = zeros((rows,cols), Float) > count_rows = nHeader > for x in range(nHeader,rows): > start = 0 > floatString = s[x] > if not floatString.isspace(): > count_rows = count_rows + 1 > for y in range(cols): > if y < (cols - 1): > indx = > floatString[start:].find(whatDel) > dummy = > floatString[start:(start+indx)] > if dummy == NaN: > ergArray[x,y] = NaN_NumPy > else: > ergArray[x,y] = float( dummy > ) > start = start + indx + 1 > else: > dummy = floatString[start:] > if dummy == NaN: > ergArray[x,y] = NaN_NumPy > else: > ergArray[x,y] = float( dummy ) > print 'fertig' > return ergArray[nHeader:count_rows,] From barry at zope.com Fri Mar 22 11:36:21 2002 From: barry at zope.com (Barry A. Warsaw) Date: Fri, 22 Mar 2002 11:36:21 -0500 Subject: Still same bug even with email ver. 1.2 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> <5018757AF2@kserver.org> <15510.52003.132317.429577@anthem.wooz.org> Message-ID: <15515.23941.31919.372322@anthem.wooz.org> [re: a bug in Python 2.2's email package...] >>>>> "BAW" == Barry A Warsaw writes: BAW> The workaround is simple, if you're creating a multipart/* BAW> you need to make sure that the payload is a sequence BAW> (typically, a list). But this is an unsatisfying answer. I BAW> haven't decided yet what, if any, proper fix there should be. BAW> Maybe the Generator should be more forgiving. Indeed, this is what I decided to do for Python 2.2.1. This bug should now be fixed in the Python 2.2.1 cvs branch. I will be working out separate patches for the standalone email package, and for Python 2.3. Thanks to everybody who helped with this! -Barry From joonas at olen.to Sat Mar 23 13:14:07 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Sat, 23 Mar 2002 20:14:07 +0200 Subject: MySQLdb References: Message-ID: <3C9CC5EF.EB0CF7D1@olen.to> Michael Hall wrote: > > G'day All: > > I've been writing PHP/MySQL for a couple of years now and am now > cross-skilling into Perl and Python. I'm interested in web database > integration for Python CGI scripts. > > Is this the right list for general questions about using the MySQLdb > module? > > If so: > > I have installed the MySQLdb module but find the docs pretty sparse. Can > anyone suggest a good tutorial that demonstrates the basic moves in > extracting and printing data using MySQLdb? I guess I'm looking for a > `translations' of PHP routines like: > > $query = mysql_query("$sql"); > while ($row = mysql_fetch_array($query)) > { > $data0 = $row[0]; > $data1 = $row[1]; > } > > Also, a newbie-friendly discussion of MySQL modules (history/variety) > and things like MySQLdb versus _mysql would be helpful. > > If not: > > Where do I go? Check out the DB-API docs at http://www.python.org/topics/database/ From laz at strakt.com Tue Mar 5 11:09:53 2002 From: laz at strakt.com (Fredrik Juhlin) Date: Tue, 5 Mar 2002 17:09:53 +0100 Subject: ICU wrapper for Python? In-Reply-To: References: Message-ID: <20020305160953.GE15135@strakt.com> On Tue, Mar 05, 2002 at 04:30:41PM +0100, Martin von Loewis wrote: > Fredrik Juhlin writes: > > > However, I'm relying on the fact that since Python uses UCS-2 and ICU uses > > UTF-16 for their respective internal format, any Python unicode string can > > be used as an ICU unicode string. So for the collation I don't need to do > > any conversion between the two. To expose the codecs, one would have to > > convert the resulting strings from UTF-16 to UCS-2. > > I'm a bit slow here: Why do you think Python uses UCS-2 and not > (simultaneously) UTF-16? What kind of conversion would you perform? Maybe I'm the one that's slow, or possibly horribly confused. Actually, I'm pretty damn sure that the docs I read at home said that Python used UCS-2 rather than UTF-16. But looking at the online docs they're saying UTF-16. So what I thought would be a problem apparently won't be. Which is good news :) > > If you're interested in what I have so far, I'll stick it on a web server > > for downloading. That'll have to wait until tonight though, since my > > latest version is at home. > > That would be nice. If you don't mind, I'd also incorporate it into > the CVS of the i18n SIG (python-codecs.sf.net - it's a bit more > general than just codecs, hope that doesn't cause problems). I'm not sure if you're wondering if I will have a problem with that or if the i18n-sig will. But I want to be able to continue work on it so as long as I can access the CVS I don't have a problem with it. I just don't know how to go about incorporating it :) //FJ From d95-bli.no at spam.nada.kth.se Mon Mar 25 06:52:37 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-1?Q?Bj=F6rn?= Lindberg) Date: Mon, 25 Mar 2002 12:52:37 +0100 Subject: Debugging on windows via print statements -- reliable? References: <3C9EA59A.D3F76D2F@engcorp.com> Message-ID: <3C9F0F85.345200F2@spam.nada.kth.se> Peter Hansen wrote: > By the way, how can Python code get "stuck"? Is it a logic flaw, > or are you talking about the kind of "stuck" that used to happen, > in the "old days", when we were always writing code in languages > which would actually crash the computer? Which language has ever been known to crash the computer? Perhaps you are referring to earlier MS operating systems, which were known to crash themselves? Bj?rn From gerhard at bigfoot.de Wed Mar 6 08:04:47 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 6 Mar 2002 13:04:47 GMT Subject: [ANN] istring 1.0.1 released; announce list created References: <3C86047F.1080601@stroeder.com> Message-ID: Artur Skura wrote in comp.lang.python: > Michael Str?der wrote: >>>>>>s = i("Value is $n") >> >> Maybe it's me but I can't see the advantage over using >> >> >>> s = "Value is %s" % (n) >> >> How about providing a more complex example illustrating the benefits >> of istring? > > Should I paste from their page? ;) > > Why would I want to interpolate variables when I could use %s > notation? > > Ask yourself which query is clearer: > > (1) db.query("""SELECT foo, bar > FROM %s > WHERE rsrc_id = %s > AND name = '%s'" % (table, rsrc_id, name)) > > Or: > > (2) qry = istring("""SELECT foo, bar > FROM $table > WHERE rsrc_id = $rsrc_id > AND name = $.name""") ^^^^^^^ There's a reason for cursor.execute(query_string, parameters) being in the DB-API. Only the DB module can know how to put the parameters there correctly with quoting and all. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From dietmar at bronko.fh-wedel.de Wed Mar 20 19:40:10 2002 From: dietmar at bronko.fh-wedel.de (Dietmar Lang) Date: 21 Mar 2002 00:40:10 GMT Subject: Attachments to the list/group - OK? (Was Re: Popular style document?) References: Message-ID: Hello, Grant Edwards wrote: > I wasn't aware that the "attachment" concept was even > applicable to Usenet articles. Well, there are things such as binaries or images groups where people constantly exchange files. Can't you simply attach them, or do they post them inline? Greetings, Dietmar -- I haven't lost my mind -- it's backed up on tape somewhere. From piet at cs.uu.nl Thu Mar 7 09:02:48 2002 From: piet at cs.uu.nl (Piet van Oostrum) Date: 07 Mar 2002 15:02:48 +0100 Subject: regular expression for nested matching braces References: <3C8337AB.2080806@geneva-link.ch> Message-ID: >>>>> Boris^2 (B) writes: B> Darrell wrote: >> Tim Peters Explains it here. >> http://groups.google.com/groups?th=ed6a75bc5eed7ee9&seekm=000401be9e6d%2427a98ec0%24029e2299 >> Searched on "tim peters match" >> It's result 203$ B> Tim expounds there that : >>> "Regular expressions can't count" -- nested brackets are beyond their B> abilities. B> Nevertheless, searching google groups with "context-free expressions" turns B> up : B> http://groups.google.ch/groups?q=context-free+expressions&hl=de&selm=1v35mpINNl78%40uwm.edu&rnum=1 B> that tells a slightly different (and interesting) story. Not different. First it is as its subject says, about context-free expressions rather than regular expressions. Moreover: * Regular expressions are characterized as degree-0 context free expressions * Degree 1 context free expressions are exactly those that can be processed by counter automata (a finite state automaton that uses a counter instead of a stack) I.e to count you need at least a degree-1 context free expression, you can't do it wqith a degree-0 context-free expression (a.k.a. regular expression). In fact python's regular expressions are a little bit stronger than the theoretical ones because of the allowed \n constructs, but still can't count. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From i.linkweiler at gmx.de Fri Mar 8 06:58:00 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Fri, 08 Mar 2002 12:58:00 +0100 Subject: PyQT: QString to String Problem if ASCII>128 Message-ID: <3C88A748.2F95D854@gmx.de> Hi, I get an error if i want to convert a QString with characters >ASCII 128 to a string: >>> from qt import * >>> s=QString("Hallo") >>> s=QString("Hallo") >>> print s Hallo >>> t=QString("G?lleg?lle") >>> print t Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) Any Idea how to avoid this? Ingo From peter at engcorp.com Wed Mar 6 20:04:51 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 06 Mar 2002 20:04:51 -0500 Subject: Web scripting with Python (1st post here, also :-) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: <3C86BCB3.22C1BE4B@engcorp.com> Skip Montanaro wrote: > > Julio> I am used to do web scripting using PHP. As a new adventure, I am > Julio> trying to learn Python.... > > Julio> So, I am looking for examples that might help me. Yes, I saw > Julio> Zope. Waaaaay too much.... > > Julio> .... Where do I start? It's for a weblog (Kuro5hin-like) system. > > I'm experimenting with Webware's WebKit > for a new website for my nascent consulting company. It seems pretty easy > to grok, is nicely object-oriented and has several "adapters" - ways of > connecting between your web server and its AppServer. My other app-server > type experience is with Mason, which I love except it uses the other > P-language (the one that ends in "l", not the one that ends in "P" ;-) Pascal? ;-) From rshivs at nospam.hotmail.com Wed Mar 27 22:15:06 2002 From: rshivs at nospam.hotmail.com (Shiv Shankar Ramakrishnan) Date: Wed, 27 Mar 2002 19:15:06 -0800 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: <3ca28aba$1@news.microsoft.com> > > behind now? Or is ActiveState not bothered about Python at all and more > > bothered about other things like Perl, Komodo etc? Thats their preorgative > > of course but I like the PythonWin IDE and now I can only get that with > > ActivePython since Mark Hammond moved there. > > He is no longer there. Huh! This is news to me. When did this happen? Hmm ... by the looks of it and the way ActiveState seems to be neglecting things looks like there has been some falling out between them ... But then I shouldn't be doing such idle speculation here ... > > Shouldn't there be some > > alternative source for getting PythonWin? How about the main Python > > distribution also doing PythonWin from CVS? > > the "alternate source" for PythonWin is Mark's home page > http://starship.python.net/crew/mhammond/ Great! Thanks. Of course I knew this website. Its just that I had stopped visiting it a long ago after Mark moved to ActiveState and his website just pointed one to ActiveState. Well I guess in some ways it is a change for the better I guess. Would it be considered too impolite to ask as to what happened? Thanks, Shiv From theller at python.net Fri Mar 22 18:07:43 2002 From: theller at python.net (Thomas Heller) Date: Sat, 23 Mar 2002 00:07:43 +0100 Subject: PEP262 - database of installed packages (Was: Re: Binary generation with distutils? References: Message-ID: A.M. Kuchling wrote in message news:slrna9kb27.nme.akuchlin at ute.mems-exchange.org... > In article , Thomas Heller wrote: > > Are you interested in my remarks to the XXX comments *now*? > > Of course! > > --amk Ok, here we go. I've written my comments into a checked out version of PEP262, ran cvs diff -c8 on it and here is the result (These are only comments, I do not suggest to update the PEP according to this diff). Thomas Index: pep-0262.txt =================================================================== RCS file: /cvsroot/python/python/nondist/peps/pep-0262.txt,v retrieving revision 1.1 diff -c -8 -r1.1 pep-0262.txt *** pep-0262.txt 9 Jul 2001 14:26:26 -0000 1.1 --- pep-0262.txt 22 Mar 2002 23:00:00 -0000 *************** *** 21,36 **** --- 21,50 ---- should be supported are: * Is package X on a system? * What version of package X is installed? * Where can the new version of package X be found? XXX Does this mean "a home page where the user can go and find a download link", or "a place where a program can find the newest version?" Perhaps both... + + THE (= Thomas Heller) thinks the first option. IMO a home + page for the user is much more useful until we get something + like to CPAN. Source distributions are platform and version + independent, but binary distros may come in an awful lot of + different formats and filenames. + + "a place where a program can find the newest version" could + or should IMO implemented in a way where an extended + "package information file" would first be downloaded, which + would contain URLs for binary and source distributions + depending on platform and version and so on. + + * What files did package X put on my system? * What package did the file x/y/z.py come from? * Has anyone modified x/y/z.py locally? Database Location The database lives in a bunch of files under *************** *** 54,69 **** --- 68,91 ---- XXX is the actual filename important? Let's say the installation data for PIL is in the file INSTALLDB/Numeric. Is this OK? When we want to figure out if Numeric is installed, do we want to open a single file, or have to scan them all? Note that for human-interface purposes, we'll often have to scan all the packages anyway, for a case-insensitive or keyword search. + THE: IMO typically a few dozen packages are installed, so we + probably have less than, say, one hundred files in the 'database', + which should reside in a single directory. Also it is not very + helpful to have the data for PIL in a file named Numeric. The + filename should be the package name. Performance: I would guess + that reading the PKG-INFO section of these few dozen files would + typically take one or two seconds, so no database is needed. + Database Contents Each file in INSTALLDB or its subdirectories describes a single package, and has the following contents: An initial line listing the sections in this file, separated by whitespace. Currently this will always be 'PKG-INFO *************** *** 76,126 **** --- 98,184 ---- containing the package information for a file, as described in PEP 241, "Metadata for Python Software Packages". A blank line indicating the end of the PKG-INFO section. An entry for each file installed by the package. XXX Are .pyc and .pyo files in this list? What about compiled .so files? AMK thinks "no" and "yes", respectively. + + THE comments: The uninstall 'database' (which is a simple text + file) which bdist_wininst installers create, contain entries + for *every* file to be removed, this includes .pyc and .pyo + files. On the other hand, MD5 digests or CRC checksums are + probably not so useful for .pyc/.pyo files. + Each file's entry is a single tab-delimited line that contains the following fields: XXX should each file entry be all on one line and tab-delimited? More RFC-822 headers? AMK thinks tab-delimited seems sufficent. + THE: tab-delimited is fine. + * The file's size * XXX do we need to store permissions? The owner/group? + THE: no, not on windows. * An MD5 digest of the file, written in hex. (XXX All 16 bytes of the digest seems unnecessary; first 8 bytes only, maybe? Is a zlib.crc32() hash sufficient?) + THE: If the MD5 digest is calculated, which throw away + the first bytes? A quick test shows that the MD5 digest + calculation takes about twice as long as zlib.crc32(), + so it could be used. * The file's full path, as installed on the system. (XXX should it be relative to sys.prefix, or sys.prefix + '/lib/python?' If so, full paths are still needed; consider a package that installs a startup script such as /etc/init.d/zope) + THE: Only full paths should be in the database file. * XXX some sort of type indicator, to indicate whether this is a Python module, binary module, documentation file, config file? Do we need this? + THE: No, we don't need this. There is no mechanism (now) how + this could be specified, also I cannot think of a use case + where it would be needed. A package that uses the Distutils for installation will automatically update the database. Packages that roll their own installation XXX what's the relationship between this database and the RPM or DPKG database? I'm tempted to make the Python database completely optional; a distributor can preserve the interface of the package management tool and replace it with their own wrapper on top of their own package manager. (XXX but how would the Distutils know that, and not bother to update the Python database?) + + THE: Maybe I don't understand what you are talking about here. I + have absolutely no idea how RPM or DPKG is working, so I'm only + talking about bdist_wininst or maybe other windows installers + here. win32all and wxPython are examples of very popular packages + *not* distributed with distutils, but with windows installers + (WISE for win32all, InnoSetup for wxPython?). + + 1. The main purpose of the database discussed here is to determine + if package is installed, and which version - so IMO it should + *not* be left optional to update this database, even for platform + specific installers like RPM or windows installers. My idea would + be to create the database file at build time, and simply copy it + into the database. + + 2. The existing python package managers I have seen so far (mainly + ciphon and pyppm) each have their own database (both have chosen + an XML based format), but they are certainly incompatible. Deliverables Patches to the Distutils that 1) implement a InstallationDatabase class, 2) Update the database when a new package is installed. 3) a simple package management tool, features to be added to this PEP. (Or a separate PEP?) From st-newsgroups at thomas-guettler.de Thu Mar 7 09:18:56 2002 From: st-newsgroups at thomas-guettler.de (Thomas Guettler) Date: Thu, 07 Mar 2002 15:18:56 +0100 Subject: mword2text on win32 Message-ID: <3C8776D0.3040200@thomas-guettler.de> Does someone know how I can convert msword to plain text in python on win32? I tried wvware from gnuwin32.sf.net (with popen3) but it fails with complex documents. Since I am on windows I could use COM. Has someone examples, or other ideas? thomas From jgardn at alumni.washington.edu Fri Mar 8 00:51:27 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Fri, 08 Mar 2002 14:51:27 +0900 Subject: reporting spam? (was RE: 5 dollar emails) References: Message-ID: <_7Yh8.118$_Z4.1115@news.hananet.net> Gerhard H?ring scribbled with his keyboard: > Most spam I get recently comes from these providers > kornet.net (most) > hananet.net > thrunet.com > Urk... I'm in Korea and I'm using hananet. =( Please, block the spam servers. If the ISPs don't do anything about it, eventually their customers will. I am working with the ISP because I can't send email to my friend in America. Maybe they'll wake up and realize that they have to be as serious about this stuff as everyone else. Jonathan From usenet at thinkspot.net Thu Mar 7 23:51:20 2002 From: usenet at thinkspot.net (Sheila King) Date: Thu, 07 Mar 2002 20:51:20 -0800 Subject: ANN: Python User Groups page at python.org References: <2AWh8.478$eT3.149538@news.uswest.net> <3C883D30.1030905@attbi.com> Message-ID: On Fri, 08 Mar 2002 04:17:55 GMT, Pete Shinners wrote in comp.lang.python in article <3C883D30.1030905 at attbi.com>: > Kevin Altis wrote: > > Python User Groups now have their own page on the Python web site: > > > > http://www.python.org/UserGroups.html > > sadly nothing ever in the southern california area. anyone in OC or LA > who enjoys this crazy python? Me. Actually, about 6 months ago or so, someone was going to start up one (like at UCI) and went so far as to set up a time and place and got a few responses, but then it fell through somehow. I don't really have the time or facilities to be an organizer, so I laid low when it fell apart. But if someone else organizes it, I will come. (Assuming I can make my schedule work, of course.) I'm in the Pomona/Chino/Brea area. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From fredrik at pythonware.com Mon Mar 4 15:49:58 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 04 Mar 2002 20:49:58 GMT Subject: Problem with SRE's regular expressions References: <3C83D5C6.7010303@free.fr> Message-ID: Christophe Delord wrote: > I'm using regular expressions in python in a parser generator. I have > some troubles with the module named 're'. In fact it uses the 'sre' > module. When I explicitly use the old 'pre' module it works fine. > So my problem is when big strings are scanned using non greedy operator > (for example ".*?") 'sre' seems to be recursivle and python stack limit > is exceeded. the SRE engine is trying to tell you that you're using the wrong tool for the task, and probably should think of a better way to do the right thing... > big_string = "<" + "that's a very very big string!"*1000 + ">" > > if re.match('<.*?>', big_string): here's the same thing, without any backtracking: if re.match('<[^>]*>', big_string): under PRE, it's about an order of a magnitude faster than your version. and SRE is over twice as fast as PRE on this one... From brian at sweetapp.com Sun Mar 31 16:17:54 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Sun, 31 Mar 2002 13:17:54 -0800 Subject: Replace high-bit characters in file. In-Reply-To: Message-ID: <001701c1d8f9$87c6e5e0$445d4540@Dell2> Mikke wrote: > I'm stuck! > > I need a script that replaces national characters in a (dBase)file. > > The original file is encoded in Latin-1 but I need it to be in CP850 > instead. # This is not tested, of course file_contents = open('dbasefile', 'rb').read() file_contents = unicode(file_contents, 'latin-1').encode('cp850') # file_contents is now a string containing the contents of the # file in cp850 format. You can write that string to a file, if you # want. open('dbasefile.out', 'wb').write(file_contents) Is that what you wanted? From gerhard at bigfoot.de Thu Mar 14 21:58:50 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 15 Mar 2002 02:58:50 GMT Subject: Dear Guru, I have added def and it doesnt work Sincerly, F References: Message-ID: Oscar wrote in comp.lang.python: > I have added > > def joinsplit = (join(split(lines, '"'), ' ')) > return joinsplit This is no valid Python, so you're getting syntax errors. > to watch.txt in an effort to replace " and / with " " to no avail. Old > watch.txt works fine, without my new def. A function to replace " and / with spaces would look like this (Python 1.5 compatible): def replace_them(s): import string return string.replace(string.replace(s, '/', ' '), '"', ' ') > [...] > > formatted = str(list[0]) + str(list[1]) + fixdate(list[2]) + > joinsplit.fixnumeric(list[3],10) + joinsplit.fixnumeric(list[4],10) ^^^^^^^^^ Apparently, the original joinsplit is a module and not a function. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From siegfried.gonzi at kfunigraz.ac.at Sat Mar 16 05:19:15 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Sat, 16 Mar 2002 11:19:15 +0100 Subject: basic statistics in python References: Message-ID: <3C931C23.B0B2BF75@kfunigraz.ac.at> Tim Churches wrote: > Note that stats.py also returns the 2-tailed p-value as well (which can > also easily be obtained from R via RPy). > > Tim C As a side note (but not related to the above problem): there exists also some peculiarities with the R-language: For example: > data <- c(0.23,1.0023,1.223,1.235,5.6,9.0,23.3456,34.458,34.56,78.9) > summary(data) delivers: Min. 1st Qu. Median Mean 3rd Qu. Max. 0.230 1.226 7.300 18.960 31.680 78.900 Everything is correct, except the 1st quantile and 3rd quantile. First, I could not believe it and fired up XLispStat: (setf data (make-array 10 :initial-contents '(0.23 1.0023 1.223 1.235 5.6 9.0 23.3456 34.458 34.56 78.9))) (quantile data 0.25) and (quantile data 0.75) respectively: delivers: 1.229 and 28.9018 The R-language calculates not only on Windows the values wrong; even on Unix: the values are the same as on Windows. Maybe they use some other method for calculating the quantiles. Personally: I can not cope with the R-language. It is rich of many build-in functions; but most of the time I am not successful in finding what I am searching for. The graphics are good; but I would always prefer Dislin as long as I do not need any specialized graphics from the field of statistics. In R one can even read in binary files (you can even swap the binary order). But plotting a large array is a pain in the neck. In Dislin it is very fast and one can overlay maps (e.g. coastlines) without any problems (you get even the x- and y-axis annotation right: -180E....+180W,...). S. Gonzi From martin at v.loewis.de Thu Mar 21 01:01:03 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Mar 2002 07:01:03 +0100 Subject: Chewing international (unicode) filenames on windows? References: <3C97FC23.1030702@skippinet.com.au> Message-ID: "Neil Hodgson" writes: > I may be in an over-design mode but I've seen large modules (posixmodule > is 150K of fairly dense code) go bad through poor redesign before. An important observation is that significant parts of it won't be used on nt (all the Posix functions that NT does not provide). Likewise for Posix systems (all the Win32 wrappers). So after merely duplicating it, and removing then-dead code, it won't be 300k. > BTW, I'm not volunteering to redesign posixmodule. My original change was > just to allow the file constructor to take a Unicode string which is to me > the biggest gain in functionality. Given recent comments, I'd argue that most users would disagree. The only complaints about the status quo I've seen are "you can't list the directory; you'll get question marks". Users wouldn't even worry about not getting the names, if they wouldn't be calling stat() to find out file information. So far, nobody has complained that opening a file with "funny characters" is not possible. So I'd say os.listdir and os.stat are the functions that most desperately need full Unicode support. Regards, Martin From bokr at oz.net Tue Mar 19 22:26:44 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Mar 2002 03:26:44 GMT Subject: Passing command line arguments when debugging with IDLE References: Message-ID: On Tue, 19 Mar 2002 20:43:33 -0500, "Nigel-Fi" wrote: >A newbe question from someone more familiar with devstudio type >environments... > >I have a python program which takes command line arguments and i'd like to >debug it with IDLE but I cant see how to specify them when I open the py >file or run it within IDLE. > I'd just make a temporary assignment to sys.argv right after the import sys, e.g., import sys sys.argv = ['arg0', '-opt', 2, 'etc.'] and then pretend it was set normally. Comment out when ready to run from command line or other starting method that passes cmd line parameters. HTH Regards, Bengt Richter From brueckd at tbye.com Fri Mar 8 14:39:42 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 8 Mar 2002 11:39:42 -0800 (PST) Subject: Is current integer for-loop syntax a wart? In-Reply-To: Message-ID: On Fri, 8 Mar 2002, Cromwell, Jeremy wrote: > PEP 276 (Simple Iterator for ints) and PEP 284 (Integer for-loops), among > others, are written from the perspective that the current integer for-loop > syntax > > for i in range(10): > > is a wart. Is this true? That is, where does the Python community stand on > this issue? -Wart? Who cares, really, anyway? :) It's not a major source of bugs, productivity drainage, etc. Seeing range() in the code doesn't force you to pause and figure out what it means (at least no more so than any of the proposed alternatives); you learn it the first time and don't really think about it again. Put another way, if somebody discovers the One Perfect Range Replacement Idiom and adds it to Python, will it make a difference in anything important? I don't think so. Especially in light of Skip's recent plea for more community help, it seems silly to spend too much time on issues like this when there are bigger fish to fry. Even if I concede that this *is* a wart, it's really hard to argue that fixing it is more beneficial than fixing actual bugs, improving Python's performance, improving the documentation, maturing the modules in the standard library, developing supporting projects (e.g. CPAN replacement), teaching others to use Python, etc. -Dave From irmen at NOSPAMREMOVETHISxs4all.nl Tue Mar 26 02:10:19 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Tue, 26 Mar 2002 08:10:19 +0100 Subject: Client/Server Tutorial? References: Message-ID: [about Pyro] > it's good, but i'm not sure if that can do what i want:) though i > probably asked the wrong question. > i need a tutorial for a server (not only a simple one, one with > client handlers, and info on clients..., like in games) > cause i want to create a server emulator for an online game, and > therefor i need at first a 'server engine' to accept the packets > handle them... I'm not sure why you think Pyro is not right. The 'server engine' you're talking about is right there, the Pyro Daemon! To reiterate, you don't have to do any network programming when using Pyro, could that be why you're confused? Pyro does all the gory client-server-socket- network-packet-marshalling-threading-reconnect stuff for you. Irmen From sholden at holdenweb.com Fri Mar 29 17:40:29 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 17:40:29 -0500 Subject: string copying References: Message-ID: "Robin Becker" wrote in message news:AZ3xhtAObNp8EwwK at jessikat.fsnet.co.uk... > Is there some special reason why python inhibits string copying. I > suppose there's some attempt being made to make these constants. To make > differing versions of 'abc' one has to resort to silliness like 'ab'+'c' > Strings are immutable, and therefore cannot be changed once created. So there's no point in creating copies, since a copy could never be changed either. What would be the point of creating copies? regards Steve From kendall at monkeyfist.com Mon Mar 18 18:13:26 2002 From: kendall at monkeyfist.com (Kendall Clark) Date: Mon, 18 Mar 2002 17:13:26 -0600 Subject: Declare list of large size In-Reply-To: ; from aaron.ginn@motorola.com on Mon, Mar 18, 2002 at 03:44:14PM -0700 References: Message-ID: <20020318171326.A29227@ntlug.org> On Mon, Mar 18, 2002 at 03:44:14PM -0700, Aaron Ginn wrote: > which will give me a list 100 elements long with all values > initialized to 0, but I'm assuming there has to be an easier way to do > this? Am I correct in this assumption? >> l = [0 for i in range(100)] >> print l >> len(l) 100 List comprehensions are everyone's friend. Best, Kendall From sjmachin at lexicon.net Thu Mar 28 15:30:11 2002 From: sjmachin at lexicon.net (John Machin) Date: 28 Mar 2002 12:30:11 -0800 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: philh at comuno.freeserve.co.uk (phil hunt) wrote in message news:... > On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen wrote: > >Jim Dennis wrote: > >> freq = {} > >> if word in freq: freq[word] += 1 > >> else: freq[word] = 1 > > >Something like freq[word] = freq.get(word, 0) + 1 > > IIRC in Awk you can just say: freq[word] ++ and it works > correctly even when there is no pre-existing index of word in freq. > > IMO it's a pity Python isn't like that. Python *could* be made like that with the explict dict() constructor ... something like: freq = dict(default=0) ... freq[word] += 1 From syver-en+usenet at online.no Thu Mar 28 12:56:02 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 28 Mar 2002 17:56:02 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: "A.M. Kuchling" writes: > In article , > Dale Strickland-Clark wrote: > > Absolutely. All of Mark's Win32 stuff are pretty much essential to > > many Windows users now, I would guess. > > Any volunteers? I could help out with things, but I don't feel that I can take responsibility for it. That seems to much for me to handle at the time being. I would be glad to help out on something though. -- Vennlig hilsen Syver Enstad From usenet at thinkspot.net Mon Mar 18 17:08:49 2002 From: usenet at thinkspot.net (Sheila King) Date: Mon, 18 Mar 2002 14:08:49 -0800 Subject: Still same bug even with email ver. 1.2 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> Message-ID: On Mon, 18 Mar 2002 16:05:43 -0500, "David Rushby" wrote in comp.lang.python in article : > I checked the release22-maint branch of Python out of SF CVS at approx > 15:00 GMT on March 18. I took the next to last example in email.tex > (the program that mails the contents of a directory) and ran it for > three cases: > A) the target directory contains no files > B) the target directory contains exactly one file > C) the target directory contains more than one file > > Here is the stderr ouput for case A: [rest snipped] I would report this as a bug, if you believe it is a bug. (I read your message, but don't know enough about the underlying email module code to definitively say whether it is a bug.) Also, you may want to send a "heads-up" email to Barry Warsaw. I found, myself, that the types of error tracebacks you were showing sometimes occur if: * A message Object is instantiated that has no Content-type or other headers. * A message Object is instantiated whose value evaluates to 'false' Possibly this is what is occurring in your sample tests? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dale at riverhall.NOTHANKS.co.uk Wed Mar 20 08:32:56 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Wed, 20 Mar 2002 13:32:56 +0000 Subject: Develop-test-debug cycle Message-ID: I can't believe I'm doing this this best way. I am debugging a large system written in Python with modules spread over 4 directories. I'm using PythonWin under Win2K to set-up the environment and run the code. Setting up the environment typically involves the following commands: import sys sys.path.append("x:\\whereever") from wibbleModule import wibble wibs = wibble(args) wibs.methods(args) At this point, I fix the error. Now, I haven't figured out a way of continueing past this point without quiting and starting from scratch because there appears to be no way to get Python to reload a module. The reload() function doesn't do it. I've tried stuff like this: del wibs reload(sys.modules['wibbleModule'] but I still seem to have the old version loaded. I've also tried using PyCrust for this but it suffers from the same problems. I assume IDLE does too. How do others go about interactively debugging large Python OO-based systems? Thanks for any pointers. -- Dale Strickland-Clark Riverhall Systems Ltd From msx at crs4.it Fri Mar 15 03:09:59 2002 From: msx at crs4.it (Federico Caboni) Date: Fri, 15 Mar 2002 09:09:59 +0100 Subject: Dear Guru, I have added def and it doesnt work Sincerly, F References: Message-ID: On 15-03-2002 4:01, in article slrna92leq.6n5.gerhard at lilith.my-fqdn.de, "Gerhard H?ring" wrote: [SNIP] >>> No wonder this doesn't work, as you've apparently haven't made very >>> much effort to understand what you're doing here. >>> >>> Sorry to be so blunt, but you can't write software just by guessing >>> about the syntax. >> >> Really? I do some of the time, when I don't remember it and can't be >> bothered to look in the manual. > > Me too, mostly by trying stuff out at Python prompt, for instance if I > forgot the semantics of slicing again. > I discovered "eval" by guessing.... I thought something like "It would be cool if existed a statement like that". I guessed the name too =). Well...I agree that this is not the right way to learn Python anyway ;) > Gerhard ____ ____ ____ _ _ ____ _ _ ____ / ___)| __ \/ ___)/ /| | / ___)| \| |/ ___) Federico Caboni (msx at crs4.it) | (___ | /\___ \\__ | * \___ \| |\___ \ Software & Network Solutions \____)|_|\_\(____/ |_| (____/|_|\_|(____/ Phone: +39 070 2796 368 CRS4, Center for Adv. Studies, Research and Development in Sardinia From gwachob at wachob.com Sun Mar 10 12:58:22 2002 From: gwachob at wachob.com (Gabriel Wachob) Date: 10 Mar 2002 09:58:22 -0800 Subject: PyBEEP Project References: <4e72770c.0203092131.457ad7@posting.google.com> Message-ID: <4e72770c.0203100958.31393b4c@posting.google.com> It was pointed out to me that not everyone may know what BEEP is. BEEP is an IETF spec (RFC 3080/3081): " BEEP, the Application Protocol Framework, ... offers advanced features such as: * a standard application layer that supports dynamic, pluggable application "profiles" (protocols) * peer-to-peer, client-server, or server-to-server capabilities * multiple channels over a single authenticated session * support for arbitrary MIME payloads, including XML " and from RFC 3080: a generic application protocol kernel for connection-oriented, asynchronous interactions called the BEEP (Blocks Extensible Exchange Protocol) core. BEEP permits simultaneous and independent exchanges within the context of a single application user-identity, supporting both textual and binary messages. HTH -Gabe gwachob at wachob.com (Gabriel Wachob) wrote in message news:<4e72770c.0203092131.457ad7 at posting.google.com>... > Just a reminder (or a notice!) that the PyBEEP project (open source > implementation of BEEP in Python) is marching forward and would like > any help anybody would like to give. > > The project is hosted at sourceforge. > > http://pybeep.sf.net > > -Gabe From huaiyu at gauss.almadan.ibm.com Mon Mar 18 17:04:57 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 18 Mar 2002 22:04:57 +0000 (UTC) Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: James_Althoff at i2.com wrote: > >[huaiyu] >|What I meant was that if you define items(A) to return an iterator, >|and write a program using 'for i,x in items(A)', it will work for >|any sequence A. Users who supply A do not need to do anything. > >They have to do *something*. They have to make sure that A supports >whatever protocol is assumed in the implementation of the "items" function. >That is, A *has* to be a "sequence" or whatever is assumed by items(). Well, if you assume that the domain of items(*) is the same as that of iter(*) and that they use exactly the same protocol, then it's already covered. So I guess it comes down to the question of whether items() and iter() are semantically connected in practice. If in most cases they have the default semantical connection, then items(A) is more convenient to A.items(). If not, then A.items() is better as it is more flexible. On second thought, even in the latter case, I don't see any negative point in providing items(A) that's hooked on A.__items__. You only need to implement A.__items__ if the semantics is different from that derived from iter(A). Huaiyu From SBrunning at trisystems.co.uk Tue Mar 12 04:52:35 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 12 Mar 2002 09:52:35 -0000 Subject: Has Mark Hammond attained pariah status yet? Message-ID: <31575A892FF6D1118F5800600846864DCBCDD1@intrepid> > From: Tim Churches [SMTP:tchur at optushome.com.au] > > So asks an article on Mark in the IT section of today's Sydney Morning > Herald - see > http://www.it.mycareer.com.au/news/2002/03/12/FFXMFP3LOYC.html Not with those of us who use the Win32all package which he has so generously donated to the community, no. I-know-you-were-joking-but-a--wouldn't-have-been-out-of-place-ly y'rs, Simon Brunning sbrunning at fuckmicrosoft.com ----------------------------------------------------------------------- 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 amuys at shortech.com.au Mon Mar 4 23:23:45 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 4 Mar 2002 20:23:45 -0800 Subject: functional programming with map() References: <918bc22f.0202241902.2160b75a@posting.google.com> <7xd6yu42j6.fsf@ruckus.brouhaha.com> <7xbseeayxk.fsf@ruckus.brouhaha.com> <7934d084.0202251545.5fb4bbf3@posting.google.com> Message-ID: <7934d084.0203042023.439d6d13@posting.google.com> "Raymond Hettinger" wrote in message news:... > "Andrae Muys" wrote in message > news:7934d084.0202251545.5fb4bbf3 at posting.google.com... > > Paul Rubin wrote in message > news:<7xbseeayxk.fsf at ruckus.brouhaha.com>... > > > "Emile van Sebille" writes: > > > > > > > "Paul Rubin" > > > > > Both of those build up a new list of the results, instead of > > > > > discarding the values. If the f function takes an integer and > > > > > computes a 20-megabyte structure, you've got a problem. > > > > > > > > If you know it's coming, throw it away first: > > > > > > > > [x.f() and None for x in items] > > > > > > OK, but that buidls a list of None as long as the item list. Not > > > so bad, since it gets reclaimed right away, but still unsatisfying. > > > > > > > filter(None,[x.f() and None for x in items]) > > > > > > > > returns an empty list vs 0 for the reduce. > > > > > > Again there's this intermediate list that's as long as the original > list. > > > > > > Do you see a way around that? > > > > > > > filter(lambda x:x.f() and 0, items) ? > > > > It's identical to the the reduce method posted previously, but avoids > > the tuple indexing required by reduce's use of a binary operator vs. > > filter's unary. > > > > Of course my first preference would be the list comprehension, > > discarding the redundant list, and if that was prohibitively expensive > > falling back to the original imperative style. > > > > Are you sure that you don't prefer the PEP 279 alternatives: > xmap(), xfilter(), xzip() or generator comprehensions? > > [ yield f(x) for x in items ] > > or > > xmap( f, items ) > Well while I'm drooling with anticipation with the approach of lazy builtin's and generator comprehensions, they aren't much help here where the problem was to "call f on x for x in items", compared to what you suggest which is "call f with x for x in items". Andrae From gerson.kurz at t-online.de Sat Mar 2 14:25:17 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sat, 02 Mar 2002 19:25:17 GMT Subject: ANN: experimental patch to allow importing from file-like objects References: <3c7fcbe6.7419921@news.t-online.de> Message-ID: <3c81245c.47694421@news.t-online.de> On 02 Mar 2002 12:30:42 GMT, Gordon McMillan wrote: >Most people doing something like this don't use imp.load_module. > >First you need a code object for the module. If it's source: > > co = compile(open(srcfile, 'r').read()+'\n', srcfile, 'exec') > >If it's already compiled (and still fresh etc.) > > stuff = open(bytecodefile, 'rb').read() > co = marshal.loads(stuff[8:]) > >Then you need a module object > > mod = imp.new_module(nm) > >(You need to set up mod.__file__, mod.__name__ etc. here). >And finally > > sys.modules[fqname] = mod > exec co in mod.__dict__ > Hey, thats' cool! I didn't know that. I must say, though, that the documentation on this in the Python reference manual is *quite* rudimentary. Well, at the very least I learned something about python internals and PyTokenizer ;) But I still feel that the python core should be more "pythonesque". There are a gazillion (ok, more like 40) places in ./Include, that use a "FILE *" as argument. As this is the external interface of python, I think it would be better if it expected PyFile-like objects instead. For example, look at marshal.dump(). You cannot pass a file-like object if you wanted to (because, alas, the implementation expects FILE*). You have to use dumps() and write that. Is this just a decision dictated by "the need for speed", or is there any motivation behind it? On a related note, (I've asked this before to no avail) - how do I successfully subclass files & open them? The problem is - where to I subclass a file returned from open()? open() always returns the builtin file class. Attempting to do this ----------- (snip here) ------------- raw_file = open(...) my_file = my_file_class() raw_file.read = my_file.read ----------- (snip here) ------------- I'll get an error that read is a read-only method. From neal at metaslash.com Wed Mar 27 07:39:13 2002 From: neal at metaslash.com (Neal Norwitz) Date: Wed, 27 Mar 2002 07:39:13 -0500 Subject: overwrite bytes in file References: <3ca1c344.16256546@news.easynews.net> Message-ID: <3CA1BD71.FFF2D9AA@metaslash.com> Marcus Stojek wrote: > > Hi, > how can I overwrite certain bytes in a file (Win NT) and > keep the rest unchanged. > All open options are truncating the file. The mode should be 'r+'. On windows it would probably be better to use 'rb+'. >>> f = open('nn') >>> print f.read() test >>> f = open('nn', 'r+') >>> f.seek(2) >>> f.write('a') >>> f.close() >>> f = open('nn') >>> print f.read() teat Neal From jeff at ccvcorp.com Fri Mar 22 14:47:24 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 11:47:24 -0800 Subject: mutlifile inheritance problem References: <9896e047.0203211303.741f695a@posting.google.com> <3C9A680A.F00216D2@hotmail.com> Message-ID: <3C9B8A4C.F7FB97FD@ccvcorp.com> Marc wrote: > > So here is my basic question: should I be able to > inherit class from another file. Yes, you can do this. I do it all the time. And the way that you're doing it is indeed correct -- just refer to the base class by its properly qualified name. I have no idea why you're having a problem, but then, I missed your initial post. Are you getting an exception? If so, you might try posting the stack trace... Jeff Shannon Technician/Programmer Credit International From mike at dlogue.net Fri Mar 22 07:29:59 2002 From: mike at dlogue.net (Michel Pelletier) Date: Fri, 22 Mar 2002 13:29:59 +0100 Subject: __* name mangling documentation Message-ID: <200203221231.g2MCVvd73940@frosch.logivision.net> http://www.python.org/doc/current/ref/id-classes.html sort of left me hanging on why __ name mangling exists and why it would be used. I'm curious because I'm looking at some code right now that uses it in a somewhat tricky way and I want to know why. If someone would be so kind to enlighten me on the reasons for __ name mangling, I will submit a documentation patch for the above page that explains it. Thanks! -Michel From mwh at python.net Mon Mar 11 06:44:12 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 11 Mar 2002 11:44:12 GMT Subject: Newbie question References: Message-ID: "Nick" writes: > How do you get the ordinal value (ASCII) of a character? For example, to > make a ROT13 program. with 2.2: >>> 'yvxr jr arrq gb obgure jvgu beq()'.encode('rot-13') Cheers, M. -- if-you-need-your-own-xxx.py-you-know-where-to-shove-it-ly y'rs - tim -- Tim Peters dishes out versioning advice on python-dev From cliechti at gmx.net Sun Mar 17 19:47:45 2002 From: cliechti at gmx.net (Chris Liechti) Date: 18 Mar 2002 01:47:45 +0100 Subject: Old File Purge Suggestions? References: <1W9l8.176946$Dl4.19853391@typhoon.tampabay.rr.com> Message-ID: Didjit wrote in news:1W9l8.176946$Dl4.19853391 at typhoon.tampabay.rr.com: > I'm using sys.stdin.readlines(): getting the date passed in from > from "ls -l" (linux). Then compare dates using the mxDateTime i think os.stat gives you the same information as "ls -l" and you don't have to parse strings (use os.listdir to get the names and then stat on them) > module after > shoving dates into a format I can use. Am I on the right track or > is there a better way to accomplish what I need. Functions or other > modulesI should be using. > > TIA > > Chris dito ;-) -- Chris From infinitystwin.SPAM at IS.BAD.yahoo.com Mon Mar 18 01:47:51 2002 From: infinitystwin.SPAM at IS.BAD.yahoo.com (Greg Krohn) Date: Mon, 18 Mar 2002 00:47:51 -0600 Subject: Creating a module that uses itself References: <2yfl8.113994$nl1.19520473@typhoon.nyroc.rr.com> Message-ID: "Asheesh Laroia" wrote in message news:2yfl8.113994$nl1.19520473 at typhoon.nyroc.rr.com... > I'm writing a PageMaker-to-specialized-HTML module (henceforth > "pm2html"). In the module, I define the classes Article, Headline, and > Photo, among others. > > In the Article class, I want to have a Headline object. Is this > possible? Right now, ActivePython's PythonWin spits a syntax error at me > because the Headline class is not defined. You should post your code and the actual error traceback. What you're describing should work -- at least they way that you've described it. Could there be a typo in your code? This works for me: class Article: def __init__(self): self.headline = Headline() class Headline: pass class Photo: pass a = Article() greg From James_Althoff at i2.com Fri Mar 1 17:33:44 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 14:33:44 -0800 Subject: Status of PEP's? Message-ID: [Bjorn Pettersen] > with this syntax you have different semantics for: > > for start <= i < end: > > And > > if start <= i < end: [David Eppstein] > Different in what sense? > > "for something" loops over all values of the variable that make > "something" true. Which part of "something" is the variable is determined > by its location in the overall expression. > > That is true with the current "for x in y" syntax as well as > the suggested "for start <= i < end" syntax. > Well, except that by "all values" substitute "all integer values" > since it doesn't make sense to loop over all floats. But that kind of definition isn't comprehensive enough because, for example, it says nothing about the order of the variables as processed by the for-loop. If you define the for-loop in terms of an iterable object (matching the implementation) the order is covered. And if you stick with an iterator-base view, then the two constructs above start to look different since that latter is clearly based on relational operators not iterators. Jim From bokr at oz.net Fri Mar 29 23:17:28 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Mar 2002 04:17:28 GMT Subject: Newbie: List of instances? References: <3CA4D52E.C2067419@bellsouth.net> Message-ID: On Fri, 29 Mar 2002 15:57:18 -0500, Jeff Layton wrote: [...] >> a.append(Bob('localhost')) > >This works! If I create a list a that has five elements where >are just instances of Bob, can I "call" a method for a specific >element of the list? I take I can (Jeff sneaks off to experiment >while his wife is napping). > Sure. >>> class Bob: ... def __init__(self,last_name): ... self.last_name = last_name ... def a_method(self): ... return 'The name is ' + self.last_name ... >>> a = [] >>> for name in ['Smith', 'Jones', 'Layton', 'the Fourth', 'Last']: ... a.append(Bob(name)) ... >>> a[1].a_method() 'The name is Jones' >>> for x in a: ... print x.a_method() ... The name is Smith The name is Jones The name is Layton The name is the Fourth The name is Last >>> a[2] = Bob('Jeff Layton') >>> for x in a[2:4]: print x.a_method() ... The name is Jeff Layton The name is the Fourth >>> Regards, Bengt Richter From borcis at geneva-link.ch Sat Mar 30 15:41:19 2002 From: borcis at geneva-link.ch (Boris Qaré) Date: Sat, 30 Mar 2002 21:41:19 +0100 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> <3CA5F90F.BF37B528@engcorp.com> Message-ID: <3CA622EF.B7C84035@geneva-link.ch> Martin v. Loewis wrote: > > > expect for those return values, such as the ability to use as > > indices into a sequence, then I'm still very -1. > > Their type changes, and their repr. Apart from that, nothing changes. How's that ? What's the point of making bool a type if we can't subclass methods for __and__, __or__, __or_not__, etc ? (we could still save the shortcut semantics by having the other parameter appear as a generator, e.g., one should call other.next() to get at the value) Regards, Boris -- Python >>> filter(lambda W : W not in "ILLITERATE","BULLSHIT") From tim.one at comcast.net Sat Mar 2 01:14:09 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 02 Mar 2002 01:14:09 -0500 Subject: pickle, cPickle, zlib, and the future In-Reply-To: <79b2b0bb.0203011329.79469c5b@posting.google.com> Message-ID: [Scott Gilbert] > ... > So can I rely on the first character 'x' being reserved for zlib, and > cPickle/pickle strings never starting with 'x'? I sure wouldn't. > ... > (BTW: In cases somebody asks why I don't just prefix my dump strings > saying where they came from: The dumps can be rather large (maybe 10's > of megabytes), and I really don't want to have to create a multiple > megabyte substring from the original.) This part I didn't follow. Surely you're writing your dumps to a file? f.write('pick') - or - f.write('zlib') f.write(the_dump_string) when writing then dumpkind = f.read(4) if dumpkind == 'pick': # read next pickle from f elif dumpkind == 'zlib': # let zlib chew on the next part else: # etc when reading. A parallel file of kind-codes also comes to mind. Etc. From gminick at hacker.pl Wed Mar 20 10:41:59 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Wed, 20 Mar 2002 15:41:59 +0000 (UTC) Subject: Python and Daemons References: <02022215115601.01886@localhost.localdomain> <8b3354da.0202270849.6b994141@posting.google.com> <87wuwy26wf.fsf@bunty.ruud.org> Message-ID: ** Since micro$oft is stupid it doesn't mean ** that you should be stupid too - do NOT toppost. Dnia 27 Feb 2002 12:04:16 -0500, ruud de rooij napisa?(a): >http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 >3. fork() again so the parent, (the session group leader), can > exit. This means that we, as a non-session group leader, can never > regain a controlling terminal. It's there for the sake of portability (to IIRC SVR4). -- [ Wojtek gminick Walczak ][ http://hacker.pl/gminick/ ] [ gminick (at) hacker.pl ][ gminick (at) klub.chip.pl ] From skip at pobox.com Fri Mar 29 15:47:30 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 29 Mar 2002 14:47:30 -0600 Subject: [ANN] PYNOSPAM 0.1 (and some Embedded-Python-Questions) In-Reply-To: <3ca4b9e8.10558859@news.t-online.de> References: <3ca4b9e8.10558859@news.t-online.de> Message-ID: <15524.53986.616113.336433@12-248-41-177.client.attbi.com> Gerson> Can a python script change the import path at runtime? Yup, just append directories to sys.path. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From logiplexsoftware at earthlink.net Tue Mar 12 17:26:56 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 12 Mar 2002 14:26:56 -0800 Subject: trouble testing for existance of variable In-Reply-To: <4bbaa6d6.0203121352.4358f14@posting.google.com> References: <4bbaa6d6.0203121352.4358f14@posting.google.com> Message-ID: <20020312142656.7bcdc51f.logiplexsoftware@earthlink.net> On 12 Mar 2002 13:52:01 -0800 googlePoster wrote: > if I want to know if a variable exists before > testing it, what do I do? How about try: colors_name except NameError: print "it doesn't exist" else: print "it exists" -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From m.hadfield at niwa.co.nz Wed Mar 20 21:02:58 2002 From: m.hadfield at niwa.co.nz (Mark Hadfield) Date: Thu, 21 Mar 2002 14:02:58 +1200 Subject: How Can I Determine the Operating System with Python? References: Message-ID: "Jill Obsidian" wrote in message news:cc779aae.0203201733.3717f882 at posting.google.com... > How can I put a check in my script which will allow me to determine > whether I'm running on Windows or Linux at execution time? >>> import sys >>> sys.platform 'win32' >>> import os >>> os.name 'nt' -- Mark Hadfield m.hadfield at niwa.co.nz Ka puwaha et tai nei http://katipo.niwa.co.nz/~hadfield Hoea tatou National Institute for Water and Atmospheric Research (NIWA) From martin at v.loewis.de Sun Mar 24 04:10:48 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Mar 2002 10:10:48 +0100 Subject: Memory sizes of python objects? References: Message-ID: "Clark C . Evans" writes: > Hello. I'm trying to figure out how much memory overhead > is used with using strings, tuples, lists, and maps. > In particular, say I have a nested structure like... To find out such things, I recommend to study the source code of Python, in particular the header files. To see such a computation, please read http://groups.google.de/groups?hl=de&selm=j43d3m93iu.fsf%40informatik.hu-berlin.de > etc. Is there some rule of thumb that I can use to estimate, > for example, take the character data you have and multiply by > a factor of 4 to find the in-memory footprint of tuples, and > each map is 1K plus 64 bytes per entry.. For a rule-of-thumb, you should be aware of the per-object overhead, and the pointer size on your system. The per-object overhead consists of three pieces (assuming a 32-bit system): - the Python per-object overhead: 8 bytes for fixed size objects (e.g. integers), and 12 bytes for variable-sized objects (strings, tuples) - the garbage collector overhead: 8 bytes for containers (e.g. tuples), nothing for non-containers (strings) - the malloc overhead: varies widely by platform, but it is 8 bytes in most cases. In addition, malloc will usually round up the object size to a multiple of 8. In addition, you have the per-content overhead, which varies with the type of object: - 4 bytes for an integer - 1 byte per character in a string, plus one for the terminating 0 - 4 bytes per element in a list or tuple (notice that lists allocate space for more elements in advance) Dictionaries are more difficult to count; their size also varies with the Python version. The dictionary object itself is one memory block, including gc and object overhead (not counting the malloc overhead), the dictionary takes 144 bytes (in Python 2.2). The array of entries is another memory block, which takes 12 bytes per entry. Notice that dictionaries overallocate entries, so you'll always need space for more entries than you have in the dictionary. Also, "small dictionaries" (less than 9 entries) don't need any extra space, since they store their entries in the 144 bytes. Regards, Martin From deltapigz at telocity.com Sat Mar 9 17:33:32 2002 From: deltapigz at telocity.com (Adonis Vargas) Date: Sat, 9 Mar 2002 17:33:32 -0500 Subject: Tkinter + Button widget Message-ID: <3c8a91ed$1_2@nopics.sjc> when i start a button widget, it automatically fires the command? def HideNewClient(self, frame): frame.configure(bd=0, width=0, height=0) return pdb_btnSearch = Button(pdb_frmCommands, text="Search", relief=GROOVE, font=("Tahoma", 10), width=16, command=self.HideNewClient(pdb_frmNewClient)) any help would greatly be appreciated. Adonis From nospam at [127.0.0.1] Sat Mar 16 11:25:51 2002 From: nospam at [127.0.0.1] (Chris) Date: Sat, 16 Mar 2002 16:25:51 +0000 Subject: This may seem a slightly strange problem ... References: Message-ID: <3QXDl$IPI3k8EwfV@[127.0.0.1]> In article , Dean Goodmanson writes >> But, aside from that, any advice on thinking up programs to write? > >Try Useless Python: http://www.lowerstandard.com/python >for a community of similar folks.. > >..and the Python Challange: >http://www.lowerstandard.com/python/pythonchallenge.html >for inspiration. Thanks - I'll try now, when I connect to send this. -- Chris From aahz at panix.com Mon Mar 11 18:02:34 2002 From: aahz at panix.com (Aahz Maruch) Date: 11 Mar 2002 15:02:34 -0800 Subject: python and haskell for fun References: Message-ID: In article , Kendall Clark wrote: > >I've been daydreaming for about a year of a Python implementation >written in Haskell, which would obviously make writing Python >extensions in Haskell easier (and more elegant, IMO, than writing them >in C or Java). > >However, John Paul Skaller did something similar with Ocaml, which he >called Vyper, and that went over in the Py world like a leaden balloon >-- actually it went over about as poorly as Stackless Python did; >which does cause me to wonder what it is about Python culture, if >anything, that's resistant to unusual alternative implementations?. A >Python implementation in Haskell is probably a fool's task. Though >given the various Haskell compilers, including some pretty impressive >parallelizing stuff, it is an interesting idea. The main problem with Vyper was that it wasn't finished, and Skaller mysteriously vanished. Stackless has in fact been moderately popular, given the problems inherent in requiring a special patched version of Python and lagging a version or two behind. I'm hopeful that the latest lighter-weight version of Stackless will win new converts -- but I won't be one of them because I'm lazy. ;-) -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From ljohnson at resgen.com Thu Mar 7 11:41:47 2002 From: ljohnson at resgen.com (Lyle Johnson) Date: Thu, 7 Mar 2002 10:41:47 -0600 Subject: SWIG and abstract base class References: Message-ID: > I want to use SWIG to create a Python module for > a C++ class hierarchy using abstract base classes: > > class Base // Abstract base class > { > public: > // many common methods > .. > }; > > In the created C++ code, I get error messages like > > "cannot instantiate abstract class due to following members:" > > Is there any possibility to tell SWIG that > Base should be treated as abstract class? Are you declaring a (public) constructor for the "Base" class in your SWIG interface file? Or maybe passing the "-make_default" flag to SWIG, to tell it to create default constructors for classes that don't already declare one? It sounds like there's a function declared *somewhere* in your SWIG interface that leads SWIG to believe it can directly create instances of the "Base" class. From mwh at python.net Sat Mar 9 11:38:01 2002 From: mwh at python.net (Michael Hudson) Date: Sat, 9 Mar 2002 16:38:01 GMT Subject: why is python slow? References: <3c8937e0$1_10@news.newsgroups.com> Message-ID: "Brad Clements" writes: > Not to segue myself but.. I have patch (505846) sitting in the list since > January 19th. That's not so long, in context. Unfortunately. > After a flurry of give and take activities (i.e. submitting better versions > of the patch), nothing has happened since January 28th. > > I have other patches that depend on this one first (For Windows CE and > NetWare) that I have not submitted. If you're not submitting them because your first patch hasn't gone in, that doesn't sound like a particularly good reason to me. > I've tried to be good and just wait.. But how long should I expect > to wait? Well, if it hasn't been looked at before 2.3 alpha time, I'd start making a fuss. It's not really going to make much difference before then, is it? > I've begged a few times for a response.. Either a rejection or a "be > patient" would be nice, but haven't received either. "be patient" Does that help? I think one of the PythonLabs crew probably has to look at this patch before it can go in, and they're even busier than the rest of us. Cheers, M. -- Hmmm... its Sunday afternoon: I could do my work, or I could do a Fourier analysis of my computer's fan noise. -- Amit Muthu, ucam.chat (from Owen Dunn's summary of the year) From philh at comuno.freeserve.co.uk Tue Mar 19 17:03:57 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Tue, 19 Mar 2002 22:03:57 +0000 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> Message-ID: On Tue, 19 Mar 2002 06:33:48 GMT, Ahmed Moustafa wrote: >1. Where can I find an unbiased comparison between Java and Python? Python is easier to write programs in than Java, but they might run slower. >2. Will Python dominate? No programming language will; they all have strengths and weaknesses. >3. Who does support Python? I'm happy to, if you want to pay me my usual consulting rates. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From brobbins333 at shaw.ca Sat Mar 9 21:19:25 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Sun, 10 Mar 2002 02:19:25 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> <3C8AA5E4.982FC689@mega-nerd.com> <3c8aae24.156616153@news> <3C8AB6ED.D7869109@mega-nerd.com> Message-ID: <3c8ac1bc.161633120@news> OK, that's pretty much what I had in mind too. Thanks for your help. Bruce On Sun, 10 Mar 2002 01:29:18 GMT, Erik de Castro Lopo wrote: > > erikd at coltrane > python > Python 2.1.2 (#1, Jan 18 2002, 18:05:45) > [GCC 2.95.4 (Debian prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> x = 56.78923 > >>> x_as_string = "%.2f" % x > >>> print x_as_string > 56.79 > >Just what you want. Remember however that if you want to operate on the >number using standard arithmetic you need to work on x rather than >x_as_string. > >Erik >-- >+-----------------------------------------------------------+ > Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) >+-----------------------------------------------------------+ >"The whole principle is wrong; it's like demanding that grown men live on >skim milk because the baby can't eat steak." >- author Robert A. Heinlein on censorship. From philh at comuno.freeserve.co.uk Wed Mar 27 19:39:43 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 28 Mar 2002 00:39:43 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <8gv3au47846mgol398j4oc5t0ufoi274b4@4ax.com> Message-ID: On Thu, 28 Mar 2002 00:17:11 +0000, phil hunt wrote: >On Wed, 27 Mar 2002 17:05:58 GMT, Courageous wrote: >> >>>And then, when you begin to flesh out your code, you would have to >>>get rid of the extraneous passes you didn't want to add (assuming >>>you are like me) in the first place. So the with-pass version >>>requires more effort, and is more verbose, for no good reason. >> >>The reasons are related to the implementation and not the design >>of Python, I believe. > >Oh? > >Can it really be hard to modify python so that pass is optional? > >The relvant file is grammar, line 68 of which reads: > > suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT > >I wonder if I could change this to something like: > > suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT | NEWLINE > >(It's current;ly compiling; i will get back on this) I've just tried: suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT | NEWLINE suite: simple_stmt | NEWLINE INDENT stmt* DEDENT suite: simple_stmt | NEWLINE [INDENT stmt+ DEDENT] None of which work. Mind you, I don't know the language of the python parser-generator, having never seen it before, and so I am just guessing things that looks like they might work. No doubt someone more familiar with it could do better. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From obsidian_genius at yahoo.com Wed Mar 20 20:33:44 2002 From: obsidian_genius at yahoo.com (Jill Obsidian) Date: 20 Mar 2002 17:33:44 -0800 Subject: How Can I Determine the Operating System with Python? Message-ID: I have need to write some Python scripts that run on Windows as well as Linux/Unix. In some instances I will be making os.system() calls to execute applications installed locally on the machine. How can I put a check in my script which will allow me to determine whether I'm running on Windows or Linux at execution time? Thanks, Jill From python at rcn.com Thu Mar 21 02:07:56 2002 From: python at rcn.com (Raymond Hettinger) Date: Thu, 21 Mar 2002 02:07:56 -0500 Subject: [ANN] PEP 279 -- Updated to version 1.8 Message-ID: PEP 279 has been reposted with the following changes: -- Fixed indentation error in the logger() function. -- Changed variable names in indexed() to start and stop. -- Generator parameter passing proposal moved to a separate PEP (not yet posted) -- Added comments and voting results from the community. -- Revised the author response to comments Note, this PEP has been submitted to GvR for pronouncement. Raymond Hettinger From max at alcyone.com Wed Mar 6 16:21:31 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 06 Mar 2002 13:21:31 -0800 Subject: Dictionaries in Lists References: Message-ID: <3C86885B.A8C36C86@alcyone.com> Avi Homes wrote: > Am I approaching the idea the wrong way? i > would like to keep the data organized as dictionaries.. No, there's nothing wrong with the approach that you describe, provided that it's appropriate to the problem you want to solve. > ... the code looked > something like > > Info{'IName':"Voodoo2",'IDescription':"blahblah} > Listing=[] > Listing.append(Info) This code contains at least one type; there's a missing assignment on the first line. This illustrates the essential nature of asking for programming help; you have to be able to provide the _exact_ code that you tried to use and the _exact_ error that you got, or your would-be benefactors will not be able to help you. I can't tell whether that missing assignment is in fact your problem or is just a typo that you made while posting. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From python at rcn.com Sat Mar 2 03:06:06 2002 From: python at rcn.com (Raymond Hettinger) Date: Sat, 2 Mar 2002 03:06:06 -0500 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: "David Eppstein" wrote in message news:eppstein-EBDEA3.22522001032002 at news.service.uci.edu... > In article , > "Raymond Hettinger" wrote: > > > There is a pair of ideas that are intuitive, clean, and routinely useful: > > for i in indici(seqn) > > for i, item in indexed(seqn) > > Isn't this in PEP 212? > Maybe it should be undeferred? > -- > David Eppstein UC Irvine Dept. of Information & Computer Science > eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ PEP 212 pre-dates generators and iterators. Back then, a list method seemed more attractive because there weren't that many things that could be iterated over. Hence, the argument for a built-in function was weaker. Since there were no generators, the idea of a lazily produced sequence wasn't in mind. Hence, the memory and time cost of building a separate items type list made the whole idea seem less attractive. Further, generatorless version of the idea was weak because its equivalent could be directly and simply coded: for i, item in zip(xrange(sys.maxint),seqn). So maybe this is PEP 212 re-incarnated in generator form and perhaps now the arguments for are much more compelling and the arguments against no longer matter. It doesn't matter to me whether we call it PEP 212, PEP 276, or PEP 279. Let's all just vote +1 and beg Guido to put it in ver 2.3. Raymond Hettinger P.S. If 212 can get revised in generator form, then YES, let's undefer it. From cfelling at iae.nl Fri Mar 1 23:49:28 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 2 Mar 2002 05:49:28 +0100 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: James_Althoff at i2.com wrote: Jim, I think I finally solved the riddle. >From your first post on this subject I had this voice in the back of my head telling me: think objects. The post I'm responding to now reinforced that voice, so I finally gave in:) [[ I've always found explainig things in writing difficult, I much rather talk to a participating audience. When I write, so many side tracks pop up that my point easily gets blurred. I do my best to constrain myself, though the posting doesn't show this, and I do think I've a point to make here, so bear with me ]] To me the world of objects in programs stops at the level of integers. That used to be the case for python1.5.2 too: >>> dir(1) [] >>> (1).__add__(2) Traceback (innermost last): File "", line 1, in ? AttributeError: 'int' object has no attribute '__add__' I know that under the hood integers can be objects too, but to me that isn't fundamental. I see it more as an implementation decission. In 2.2 we happily see the type/class split healed. And one of the consequences of that is that we now *see* that integers have methods, we can even call them: >>> (1).__add__(2) 3 To you, comming from smalltalk, that's just how it's supposed to be, but to me it looks a little awkward. Probably because to me integers are a mathematical abstraction, and I don't see how it could know how to add. Addition is something that's not inherent to integers but a layer that's put on top of integers. I guess this just goes to show my ignorance on mathematical issues:( And now you're stretching this object oriented view of integers even further. You ask an integer to iterate or, if you like, to count. The funny thing however is that I don't have this reservation with strings:) Strings to me have always been a programmers construct, there are no character strings in the real world, but they sure come in handy in a program. When I made the switch to OO I saw that it was practical and sound to put the actions and the data together. So the same for strings. I ask a string whether it has uppercase chars, I ask it to split itself, to count itself (len). I'm even prepared to ask it to translate itself. No problem. I just never made that step for numbers. And I'm not alone in that. I remember from the 80's that there were heated discussions whether to go `all the way' and define integers to be objects or stop at the level of some primitive types when defining the object hierarchy. There were implementation issues but also filosofical and usability considerations. Some language designers choose to hide the object nature of integers from the programmers and provided a bunch of syntactic sugar solely to make number manipulation look more like ordinary math. To conclude, you propose to go `all the way' with treating integers as objects, and some of use haven't been exposed to such a thing long enough to either be blind for its pecularity or to finally appreciate its soundness. I think given enough time and exposure I can get to appreciate it, I don't know for the public in general. And though we hardly hear off it these days, Guido is aiming at `programming for everybody'. ... > This has been suggested and is fine for one-dimensional, > indexed-collections that are written in Python and obey the standard > protocol for sequences -- specifically that they implement __len__. But > how is such a function going to work for a two-dimensional Java table > (accessed via Jython)? PEP 276 is more general. And doesn't preclude such Ah, I remember you making this point before. I'm not familiar with Java (I shun the C-family like the plague:) so I've to take your word for that. When true (and I don't mean to imply I doubt your word on it) then it's a valid argument in favour, I guess. >> But I do think that dismissing our point as a matter of >> preference misses our point. > The PEP says this: > - Some feel that iterating over the sequence "0, 1, 2, ..., n-1" > for an integer n is not intuitive. "for i in 5:" is considered > (by some) to be "non-obvious", for example. > How does that miss your point? What should it say? You could mention that some view the `for x in y' construct to imply that y is some kind of sequence and have problems seeing a number turned into a sequence just because a sequence is expected there. That's why we think it non-obvious and not intuitive. [From the PEP] Response: This seems to be largely a matter of preference. Some like the proposed idiom and see it as simple and elegant. Some are neutral on this issue. Others, as noted, dislike it. But it's what came after it, the `preference' thing that made me react in the first place. I don't perceive it being a mere prefence, but as a fundamental different view of what integers are and what the for construct is about. And being over-sensitive, you ditching the opposition as simply being a matter of taste and preference hurted. Having rethought the whole thing, I'm not sure what my final verdict is. Integers are objects, and in concordance to objects in general, know to do `integer' things. They know how to add, multiply, divide and ... count. The integer 10 knows how to count from 0 to 10. Like a `dict' knows to iterate over its keys. And that's precisely what is requested in the `for' construct. On the other hand, people are not used to think of integers being capable of doing their own adding and counting. And when this was prominently visible in a language it could alienated them from it. I'm actually interested in studies from smalltalk usage telling how easy or problematic it was for its users to come to terms with sending messages to integers to create a loop. Maybe it's a non-problem in general, only felt by us programmers raised prior to the OO flood. Just in case I switch position:) let my propose an enhancement to your proposal. Why not be able to count down? You specify that the integer to iterate over should be possitive, why not allow for negative values and do the sensible thing, like: >>> [i for i in -3] [-1, -2, -3] >>> s = "spam" >>> "".join([s[i] for i in -s.len()]) 'maps' I feel this would enhance the usability of the idiom as it would cover two frequent usages of iterating over a sequence: up and down. And especially for the down variant, the proper `range' incantation is bud ugly. range(-1, s.len() - 1, -1) yack. -- groetjes, carel From wealthychef at mac.com Fri Mar 15 13:07:12 2002 From: wealthychef at mac.com (wealthychef) Date: 15 Mar 2002 10:07:12 -0800 Subject: how to check how many bytes are available to read() ? References: <2b57f654.0203142026.68ec3fc7@posting.google.com> Message-ID: <2b57f654.0203151007.446f600a@posting.google.com> grante at visi.com (Grant Edwards) wrote in message news:... > In article <2b57f654.0203142026.68ec3fc7 at posting.google.com>, wealthychef wrote: > > > I have a file object f. I want to know if there are any bytes > > to read from it. > Call select.select([f],[],[]) Yes, I was doing it backwards! The manual is confusing in this respect. Thanks for the help! Works perfectly now just as I wanted it to. From sholden at holdenweb.com Thu Mar 28 12:57:02 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 28 Mar 2002 12:57:02 -0500 Subject: vwait in Python? References: <1017315455.8141.1.camel@lewis> Message-ID: "Ken Guest" wrote in message news:mailman.1017331196.5311.python-list at python.org... > On Thu, 2002-03-28 at 11:37, Ken Guest wrote: > > Anybody know if there's an equivalent to TCL's vwait keyword in Python? > > So is there no way, short of a 2 line while statement, to have code > hang around until the value of some variable has been changed? > > I have tried using variations of the simple while statement, but they > only result in the application hanging (going into an infinite loop > no doubt). > Now you've explained the REAL problem, of course it's easier to see how to solve it. There are various synchronization primitives which you might use for this purpose. The simplest is mutex, but that doesn't support threading and your question kind of implies that the variable will be changed in another thread. Something else you haven't explained is whether the code which changes the variable's value is aware that there is another component waiting for it to change (in other words, are you working with code you can modify, or must you just wait for the value to change). In multi-threaded applications the Queue module allows you to synchronize different threads quite effectively. regareds Steve From wurmy at earthlink.net Sun Mar 3 17:21:40 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Sun, 03 Mar 2002 22:21:40 GMT Subject: PEP 234 little bug? References: <3c817238@nntp.server.uni-frankfurt.de> <3C817FC1.A155DBAB@earthlink.net> Message-ID: <3C82A23F.84C66941@earthlink.net> Just van Rossum wrote: > > In article <3C817FC1.A155DBAB at earthlink.net>, > Hans Nowak wrote: > > > Michael 'Mickey' Lauer wrote: > > > > > > Just read through some of the already implemented PEPs. > > > > > > PEP 234 (iterators) states: > > > > > > > - It has been proposed that a file object should be its own > > > > iterator, with a next() method returning the next line. This > > > > has certain advantages, and makes it even clearer that this > > > > iterator is destructive. The disadvantage is that this would > > > > make it even more painful to implement the "sticky > > > > StopIteration" feature proposed in the previous bullet. > > > > > > > > Resolution: this has been implemented. > > > > > > I can't see a next() in a file object. Shouldn't it be > > > "Resolution: this has not been implemented." ? > > > > Hm, I don't think so. I think it does not say that the *file* > > object should have a next() method... rather, it says that > > it's its own iterator, and the iterator has the next() > > method. Maybe the wording could have been a bit more careful, > > but essentially it's true what is says. And iterating over > > files has indeed been implemented in 2.2. > > Just yesterday I've filed a bug about the current behavior that is > caused by the fact that the file object is *not* its own iterator: Should it be? This may be a dumb question, but are there important reasons to do this, besides conformance with the PEP? I mean, the current situation does do the job; "for line in file" works. What would be the additional benefit of making a file its own iterator? -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From aahz at pythoncraft.com Sun Mar 31 09:19:53 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 09:19:53 -0500 Subject: string copying References: Message-ID: In article , Steve Holden wrote: >"Tim Peters" wrote ... >> [Bengt Richter, on consuming vast quantities of memory quickly] >>> >>> s = 'x'*2**30 would be a quick gig too. But it made me think >>> maybe one could write a sort of memory test (to exercise the >>> available python space, anyway). Does python run out of memory >>> gracefully? >> >> Very. You should get a clean MemoryError exception if you try. >> >> >>> 'x' * 2**30 >> Traceback (most recent call last): >> File "", line 1, in ? >> MemoryError >> >>> >> >My laptop upgrade clearly takes my platform beyond the timbot conceptual >limit: it took about three minutes to start printing (I'm not thinking of >letting it finish) with no error message in sight. How many gigs in your swap file? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From logiplexsoftware at earthlink.net Tue Mar 5 13:02:54 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 5 Mar 2002 10:02:54 -0800 Subject: swap In-Reply-To: References: Message-ID: <20020305100254.77d8354b.logiplexsoftware@earthlink.net> On 5 Mar 2002 02:26:24 -0500 Computer Exams Info wrote: > If you know you have some stuff very useful that I haven't, we can swap. > There are my collected stuff: > > CIW (Certified Internet Webmaster) STUDY PACKAGE > CIW Foundations (365pages, pdf, 4Mb) > CIW Study Guides: Foundations, Internetworking, JavaScript, Perl, Security [snip...] > SCJP(SUN Certified Java 2 Programmer) > SCJD(SUN Certified Java 2 Developer) > SCAJ (SUN Certified Enterprise Architect for J2EE) > SCSA 7, 8, (SUN Certified Solaris Administrator) > > more than 100 Training Books > - Java Programming Language, Java Programming Language Workshop, Solaris > Network Administration, Solaris 2.6, 7, 8, Administration, Operating > Enviroment Network Admin, Enterprise JavaBeans. Programming, Mastering > Enterprise the Java. 2 Platform Enterprise Edition and so on. > I've got a slightly worn (only installed once!) copy of Python 2.1 if you're interested ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From claird at starbase.neosoft.com Thu Mar 21 08:31:44 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 21 Mar 2002 07:31:44 -0600 Subject: MySQL's applicability (was: Java and Python) References: <3C96DBB4.6040109@pobox.com> <3C9887B9.6090603@thinkware.se> <82B3E32A4EFF0E57.126AAAECC4E2B809.F8613C4251DB7A4B@lp.airnews.net> <3C999C77.3010801@pobox.com> Message-ID: <3B60DBA0567258CC.2D1920C635D59D07.BECBFEB54871D6AF@lp.airnews.net> In article <3C999C77.3010801 at pobox.com>, Ahmed Moustafa wrote: >Cameron Laird wrote: >> Undeniably. That's certainly the conclusion of "the first time >> a computer publication has published database benchmark results >> ...", as *eWeek* did in its 25 February 2002 issue. The subtitle >> of the article was "Oracle9i and MySQL top the field ..." >> >> So, no, MySQL is NOT "related to small to mid-size web applica- >> tions". > >They were measuring the response times. A file-based application may do >the function with a response time in the same order which doesn't imply >that a file-based app is comparable to Oracle 9i. Their test generated >200,000 orders, that is a small-size web application, right? Also, parts >of the test used the nontransactional engine of MySQL! > >-- >Ahmed Moustafa > You're right. I agree that comparison has plenty of flaws. >From your original posting, I couldn't tell whether such subtleties were meaningful to you. There certainly are many people who believe that 200,000 orders is ... well, at least not "small-size". Now I know that you know better. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From geoff at gerrietts.net Thu Mar 7 15:18:28 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 7 Mar 2002 12:18:28 -0800 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <3C87C057.4040902@sympatico.ca> References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> <20020307035851.GA23955@isis.gerrietts.net> <3C87C057.4040902@sympatico.ca> Message-ID: <20020307201828.GG29379@isis.gerrietts.net> Quoting Ramkumar Kashyap (rkashyap at sympatico.ca): > Somebody in this thread raised the point that the logic involved in > programming in not intuitive. I agree with that. The point I want to > make is that there are programs like Hooked-on-Phonics, and other > remedial language programs that are quite effective in raising the > literacy levels among adults. Yes! And I'm interested in getting to the point of at least some general pointers toward how to go about teaching languages. In my professional capacity, I'm often called on to teach programming concepts to my peers, or to provide training on various aspects of a project's architecture. Some of that is because of my background, some of it is because I don't mind doing it nearly as much as the average engineer. > Another point (this is purely from observation and others with children > may want to corroborrate) is that children tend to learn faster and > retain longer with repetition. I don't know if there are any people on > CLP who are also conversant with the human brain and can shed light on > the formation of new neural pathways etc. I know just enough to spout off like I know a lot, but I think others can talk more. I think I'll refrain from spouting too much.... I will say that I think the gender thing is a biological difference, though. Women, especially when younger, have better cooperation between their "left" and "right" brain. This makes them great at a lot of things. Men have less cooperation, which makes them better at focussing on a single task. This is (of course) a gross overgeneralization. When you actually trace into the neuroscience around it, all the "except" and "but you hafta understand" conditions mitigate this down to a discernable trend but nothing like an absolute. I think that maybe there's a way to build in appeal for highly coordinated thinkers, too -- I learned to program largely by thinking of it as a more challenging form of poetry -- but I'm not sure how to make that appeal broad. (Maybe saying something about gender differences is too controversial, so if you're feeling like I need a good flaming, consider how your flame will contribute to the development of teaching strategies, please!) > I should also confess that I have an ulterior motive in this > discussion, which is to teach my kid to program, (which is still a > few years away). Hee! Me too. I think the best advice I've gotten so far is to do it and enjoy it and make it accessible. I'm personally thinking that I'm going to use Lego Mindstorms as a starting point. He likes Legos, likes robots, and in a few years, he might be able to put them together.... --G. -- Geoff Gerrietts "Punctuality is the virtue of the bored." --Evelyn Waugh From ffjhenon at club-internet.fr Sat Mar 16 06:28:01 2002 From: ffjhenon at club-internet.fr (Fabien =?iso-8859-1?Q?H=E9non?=) Date: Sat, 16 Mar 2002 12:28:01 +0100 Subject: Linux endline Message-ID: <3C932C41.2974C1DA@club-internet.fr> I am writing a POV-RAY editor which can be used with Windows or Linux. 1? When I use it under Linux I would like to get rid of the \r which appears at the end of each line. ( I know there is a difference of endline between Windows, Mac and Linux). I added a slice, but it doesn't seem to work. I tried to use self.text.insert(END, line[:-1]) But it does not help In short how do I get rid of endline in *nix ---- def enter_text(self): if plat=="win32": l=1 self.filename = askopenfilename() if self.filename: self.text.delete(1.0, END) fd = open(self.filename) for line in fd.readlines(): l=l+1 self.text.insert(END, line) fd.close() elif plat=="linux-i386": l=1 self.filename = askopenfilename() if self.filename: self.text.delete(1.0, END) fd = open(self.filename) for line in fd.readlines(): l=l+1 self.text.insert(END, line) # self.text.insert(END, line[:-1]) fd.close() ----------- 2? One more thing, I'd like to add syntax highlighting with braces, parentheses,.... matching. I'd like to know it is feasible to implement it. 3? Is there a way to fire up an external application (like POV or a modeler) in background or as a sub-thread : When I start POV from within the application, I have to wait for the raytracing to be over to use the editor again. I use os.system("application_to_run") Thanks for any help From marklists at mceahern.com Sat Mar 30 06:01:36 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 30 Mar 2002 05:01:36 -0600 Subject: PEP 285: Adding a bool type In-Reply-To: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Message-ID: [Guido] > 1) Should this PEP be accepted at all. +1 [Paul Rubin] > I don't see much need for it. There's no need to turn Python into Java. > Python, C, and Lisp have all done fine without bools. What kinds of > programming tasks in Python are bools supposed to make easier? I view the proposal not as 'making programming tasks easier' but as improving the readability of Python code. If the proposal can achieve the latter without 'making programming tasks harder', it seems like an obvious win. // mark From tim at vegeta.ath.cx Tue Mar 12 05:29:25 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Tue, 12 Mar 2002 10:29:25 GMT Subject: Is Python an object based programming langauge? References: Message-ID: Christopher Browne graced us by uttering: > Tim Hammerquist wrote: >> Graz Bukanoff graced us by uttering: >> > Is Python an object based programming langauge? >> >> According to Smalltalk enthusiasts, definitely not. >> >> According to some Pythonistas, yes. >> >> IMNERHO, Python is object _oriented_, but not object _based_. I don't >> fault Python for this; it was a design decision, and probably a good >> one. >> >> If the question were "Can Python model my OOP idea?", the answer is an >> emphatic yes. > > That depends somewhat on your OOP idea. > > If the OOP idea is to use classes to define a hierarchy of methods, > then sure. > > If your "OOP idea" is to have generic functions ala CLOS, or to do > FLAVORS-style mixins, then possibly not. ...that's if _you_ asked if Python could model _your_ OOP idea. I felt comfortable assuming the OP's ideas would fall well within Python's very wide range of applicability. I took the risk. Tim Hammerquist -- One should always be in love. That is the reason one should never marry. -- Oscar Wilde From gerhard at bigfoot.de Wed Mar 27 07:39:59 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 27 Mar 2002 12:39:59 GMT Subject: Python IMAP proxy Message-ID: Is one available somewhere that I can reuse? Gerhard From jeff at ccvcorp.com Wed Mar 27 14:46:01 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 27 Mar 2002 11:46:01 -0800 Subject: Dealing with python version References: Message-ID: <3CA22178.CAE46492@ccvcorp.com> Andrei Kulakov wrote: > Hello, > > Correct me if I'm wrong, but it seems like if python1.6 or 2.0 are > already installed and you install a newer version, python command still > points to the old interpreter. Depends on the OS you're using. > I think it would be sensible to use the newest installed python to run > a program. Is there some elegant way to do that? Depends on the OS you're using. > I would ideally prefer it to run using newest interpreter available > unless it's older than some minimum requirement. It's not very > user-friendly to put #!/usr/bin/env python2.1 bang line and then say in > a README that if user gets an error, he has to somehow find out what's > the latest version he's got and change the bang line to it. > > What's the proper way to deal with all of this? Depends on the OS you're using. ;) Seriously, though... you're obviously using some sort of *nix (this particular issue isn't a problem on Windows). In general, on *nix, /usr/bin/python should be a symbolic link to the version you want to use, and it wouldn't be difficult to change that to point to the new version. The problem comes when you're using, say, Red Hat, which has system utilities that rely on Python 1.5.2 and break under 2.*, so that you effectively cannot change /usr/bin/python to mean anything other than 1.5.2 (RedHat "solves" this by symlinking 2.* as /usr/bin/python2). However, there isn't an easy way to identify which Python version a given script should be run under. Typically, the most practical way to deal with this is to use plain "python" in the shebang line, and then document that your package requires a certain minimum version. Jeff Shannon Technician/Programmer Credit International From daves_spam_dodging_account at yahoo.com Fri Mar 29 15:42:25 2002 From: daves_spam_dodging_account at yahoo.com (David Brady) Date: Fri, 29 Mar 2002 12:42:25 -0800 (PST) Subject: [XP] Code Complete: Things were Scary Back Then In-Reply-To: Message-ID: <20020329204225.46643.qmail@web21110.mail.yahoo.com> > -----Original Message----- > From: Peter Hansen [mailto:peter at engcorp.com] > > I don't remember any of the BASICs that I used, > whether Apple II, > PET, C-64, MS, or other having modules at all. Are > you sure the Apple II > had modules? Since it wasn't compiled, I assume > there was some way > to load other modules into memory while the program > was running. I did this a lot. There was no enforcement of "modules" in BASIC, but you could still do modular programming. You only had the one big program to work with, but you mentally divided it up into sections. For example, a hotel reservation program I wrote had a logical layout as follows: Starting at line 100 was the "bootstrap" code. It initialized my globals, read in the config files, etc., then around line 350 or so fell through to line 1000. Line 1000 was the beginning of the code that displayed the main menu, let the user navigate the menu and make a choice. Depending on your choice, the code would GOSUB to line 2000, 3000, 4000, etc. Line 2000 was the beginning of the code that let you enter a new reservation. Line 3000 let you delete reservations. Line 4000 let you search for a reservation. You get the idea. Each section was only 10-50 lines long, and there was a lot of space between the end of a section and the beginning line of the next section, but you knew when you were browsing the code that if you were looking at, say, line 3120, you were in the "delete a reservation" section. (Yes, using the RENUM command was a serious pain.) That was in 1986. Ironically, I never properly learned the concept of "modular programming" as a separate concept until 1996 or so, after programming C for 4 years. In BASIC, we called it "Structured Programming", but I didn't really understand "tight cohesion, loose coupling" until I read McConnell's book a decade later. *shrug* IIRC, Kent Beck says he started learning the principles of XP programming in assembly. You can *do* it, but sometimes a lot of your organization is external to the program or language itself, and lives only in the habits you practice while developing. Cheers, -dB ===== David Brady daves_spam_dodging_account at yahoo.com I'm feeling very surreal today... or *AM* I? __________________________________________________ Do You Yahoo!? Yahoo! Greetings - send holiday greetings for Easter, Passover http://greetings.yahoo.com/ From sakkinen at cs.jyu.fi Thu Mar 28 02:38:59 2002 From: sakkinen at cs.jyu.fi (Markku Sakkinen) Date: Thu, 28 Mar 2002 07:38:59 +0000 (UTC) Subject: Inheritance workshop Message-ID: Second and last call for contributions: The Inheritance Workshop at ECOOP 2002 ====================================== - The first ECOOP workshop focusing on inheritance since 1992 - Full information is available at the web site: http://www.cs.auc.dk/~eernst/inhws/ A convenient LaTeX template has just been included. The DEADLINE is near already! ----------------------------- Position papers due: April 8, 2002 Notification of acceptance: April 29, 2002 Deadline for early ECOOP registration: May 6, 2002 Final version of accepted papers due: May 27, 2002 Workshop: June 11, 2002 (Tuesday) From rjones at ekit-inc.com Tue Mar 12 17:16:08 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Wed, 13 Mar 2002 09:16:08 +1100 Subject: Homepage of Gadfly not available? In-Reply-To: <20020311233409.A30846-100000@palanthas.neverending.org> References: <3C8C8DA1.5040901@med.uni-tuebingen.de> <20020311233409.A30846-100000@palanthas.neverending.org> Message-ID: <200203122216.WAA18579@crown.off.ekorp.com> On Tue, 12 Mar 2002 15:39, Frank Tobin wrote: > Oleg Broytmann, on 2002-03-11, wrote: > > > Are the sources available somewhere? > > > Is there a new home page for Gadfly? > > > Is there anybody who will maintain such a page? > > > > My answer is no better than http://sourceforge.net/projects/gadfly/ > > Except for the fact that that project was registered over 2 years ago, and > has had 0 activity... That's mostly because the code works and the original author doesn't have the time to do any enhancements. Feel free to put your hand up if you feel it is deficient in some way. Richard From bernie at 3captus.com Fri Mar 1 20:13:27 2002 From: bernie at 3captus.com (Bernard Yue) Date: Sat, 02 Mar 2002 01:13:27 GMT Subject: string to dictionary References: Message-ID: <3C8027BB.1FEA6419@3captus.com> les ander wrote: > > Hi, > i have a list of strings like this: > > aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3',...] > > i want to convert this to a dictionary with a_i -> b_i without > using loops (it is trivial to do it with loops) > i tried this > > dict={} > map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList) map(lambda x,d=dict: c=string.split(x), d[c[0]]=c[1], aList) ^ ^ First, assignment is not allowed within lambda. Secondly, the scope of lambda ends at the first comma (correct me if I were wrong). Hence d[c[0]=c[1] become a list and since c is not defined outside lambda, the error message resulted. The following code should work: >>> aList=[ 'a_1 b_1', 'a_2 b_2', 'a_3 b_3'] >>> dict = {} >>> map( lambda x, d=dict: d.update( {x.split()[0] : x.split()[1]}), aList) [None, None, None] >>> dict {'a_1': 'b_1', 'a_2': 'b_2', 'a_3': 'b_3'} >>> I would like to see a better solution as I find using split() twice ugly > > but it complains that "keyword can't be an expression" > can someone please help me get this right? > thanks > les Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. So far as I can remember, there is not one word in the Gospels in praise of intelligence. -- Bertrand Russell From philh at comuno.freeserve.co.uk Sun Mar 31 14:07:38 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sun, 31 Mar 2002 20:07:38 +0100 Subject: PEP 285: Adding a bool type References: Message-ID: On 31 Mar 2002 09:33:53 -0500, Aahz wrote: >In article , >phil hunt wrote: >> >>That *is* a valid reason. However, it must be decided whether >>Python's primary goal is to be easy to learn or easy to use. > >It must? Much of why I love Python so much is because it's *both*. There are bound to be some cases where both goals collide. The fuss over / is a good example, IMO. >using lots of simple, orthogonal constructs, Python manages that unusual >feat. That's the main reason I was (and am) unhappy with the "print >>" >proposal, but on the whole, I can't argue with Guido's ability to find >solutions that promote the goals of both "easy learn" and "easy use". That's true. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From arturs at iidea.pl Sat Mar 9 06:54:04 2002 From: arturs at iidea.pl (Artur Skura) Date: Sat, 9 Mar 2002 11:54:04 +0000 (UTC) Subject: Tokenize a string or split on steroids References: <4lpj8u4nbsoqjf2h4upadti62jh4sf4i59@4ax.com> Message-ID: Fernando Rodr?guez wrote: > > I need to tokenize a string using several separator characters, not just one > as split(). > > For example, I want a function that returns ['one', 'two'] when given the > string '{one}{two}' . Normaly you would use the re module, but in this case... >>> import string >>> a="{one}{two}{three}{four}" >>> string.split(a[1:len(a)-1],'}{') ['one', 'two', 'three', 'four'] ;) Regards, Artur -- http://www.wolneprogramy.org From logstx at bellatlantic.net Mon Mar 4 17:25:53 2002 From: logstx at bellatlantic.net (logistix) Date: Mon, 04 Mar 2002 22:25:53 GMT Subject: OT - file permission checks on Windows References: Message-ID: Yeah, Windows permissions are totally different than Unix and alot more robust, assuming you don't go with the default install ;) There are 13 (I believe) different "flags" that can be applied to files. Each of these is attached to a user or group in an Access Control List. The list size is entirely arbitrary, so you're not tied into User, Group, Other levels. Then in W2K you can even specify explicit Denies that override permissions. This allows you to do all sorts of goofy stuff like preventing the Administrator (root) from even being able to view files, or granting all "RESEARCH" users change control unless that "RESEARCH" user is "JOE" xcacls is the command line equiv. of chmod if you want to get a quick idea of how different things are. -- - "Skip Montanaro" wrote in message news:mailman.1015266376.28131.python-list at python.org... > > Sorry for the off-topic post. My entire C programming world these days is > in the Python community, so I'm completely disconnected from other C > programming resources. (Pointer to information about porting Unix code to > MSVC would be much appreciated.) > > Given this simple file access permission code: > > mode_check(struct stat *buf, uid_t uid, uid_t gid, > unsigned int umask, unsigned int gmask, unsigned int omask) > { > /* root always gets to go */ > if (uid == 0) return 1; > > if (uid == buf->st_uid) return buf->st_mode & umask; > > if (gid == buf->st_gid) return buf->st_mode & gmask; > > return buf->st_mode & omask; > } > > how would I do this under Windows? Is the permission model there even > remotely similar to what I'm used to on Unix systems? I poked around > posixmodule.c, but it makes next to no use of uids and gids. As far as I > can tell, Windows doesn't know about uid_t or gid_t, though it has a struct > _stat type whose st_uid and st_gid fields are shorts, so I can work around > the missing types. > > Thx, > > -- > Skip Montanaro (skip at pobox.com - http://www.mojam.com/) > From loewis at informatik.hu-berlin.de Fri Mar 1 05:04:06 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 01 Mar 2002 11:04:06 +0100 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: bokr at oz.net (Bengt Richter) writes: > I'm not sure what you mean by 'encoding cookies' but I assume you > mean something analogous to browser cookies, where some data of > interest is stored separately but related to some other data and > processing, like HTML form sumbissions etc. I took the term from Stephen Turnbell, and I understood him to mean the coding: variable that Emacs recognizes, i.e. some declaration inside the file - quite unlike a browser cookie. > Perhaps we could just use a file to contain extra file metadata, > letting a file of metadata govern other files it names in the same > directory as itself. Probably a dot file in *nix. Nice idea, different PEP. > For PEP 263 purposes, it would only need to be a text file with file > names tab delimited from keyword=encoding-info, with the first line(s) > perhaps with a glob pattern for a compact way of specifying encoding > for a lot of files in a directory at once. I don't think the file encoding information should be stored in a different file; the risk of the two files becoming disassociated is just to big to be acceptable. > To provide international encoding for file-associated info, like > a local dialect/special characters name etc., in a system whose > native file naming is more restricted, perhaps this directory of > file attributes could be standardized to UTF-8 for its own encoding. We are not talking about file names here, but about file contents. > There are some changes as to legality checks, apparently, > as of last May. I'm wondering if this affects PEP 263 > and/or the unicode implementation in Python. That doesn't affect this PEP; as for the Unicode 3.1 conformance, I believe the current CVS implements UTF-8 correctly. Regards, Martin From philh at comuno.freeserve.co.uk Sat Mar 9 08:05:56 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 9 Mar 2002 13:05:56 +0000 Subject: Is current integer for-loop syntax a wart? References: Message-ID: On Sat, 9 Mar 2002 00:29:02 +0000 (UTC), Huaiyu Zhu wrote: >- Not a wart: > > 1. It is very clear what it does. > 2. range() can be used elsewhere. No new syntaxes. > 3. In most situations you loop over list of items instead of counters. > > >- Wart: > > When you do need the index, neither of the following is very nice looking: > > for i, x in zip(range(len(a)), a): > b[i] = x > > for i in range(len(a)): > b[i] = a[i] What you sohuld be able to do is say: for i in a.keys(): b[i] = a[i] You can get a dictionary's keys, so you ought to be able to do so with sequence types, in the same way. (Actually I'd say it is a failing in Python generally that the collection typers are not as well-integrated-together as in e.g. Smalltalk). >the solution is too broad: it produces iterators in many uninteded places. > > >Two ideas that I do like: > > for i, x in items(a): > b[i] = x That's nice. > for i in indices(a): > b[i] = a[i] Instead of indices(a) use a.keys() for consistency with mapping types. This could return an xrange. >They address the right problems at minimum cost. They can be extended to >xitems and xindici, of course. Indeed. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From bernie at 3captus.com Tue Mar 5 02:44:26 2002 From: bernie at 3captus.com (Bernard Yue) Date: Tue, 05 Mar 2002 07:44:26 GMT Subject: Python Refactoring Browser References: Message-ID: <3C8477DD.F28F6F54@3captus.com> Hi Mathew, Mathew Yeates wrote: > I am in desperate need of a refactoring browser for python. I've written a > fairly large program and now am trying to clean it up. I change a member > variable and WHAM I break my code in 95 different locations. > > I'm aware of Bicycle Repair Man http://bicyclerepair.sourceforge.net/, > which, when better developed will be exactly what I want. There is also > PyIDEA http://sourceforge.net/projects/pyidea/, but it's just starting up. > And Boa ( http://boa-constructor.sourceforge.net/ ) doesnt seem designed > for refactoring although I have been using its automatic UML generation to > give me ideas on how to reorganize classes. > > When I'm programming in C, I have cscope which I use with a VIM interface. > Its not much but at least I can locate variables easily. > > Has anyone else refactored a large Python program? How did you do it? > I used pyunit. It is now a standard library in python (check module unittest). I know Zope use it too. Bernie > > Mathew -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. -- Robert A. Heinlein From uwe at rocksport.de Tue Mar 26 16:40:17 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 26 Mar 2002 21:40:17 GMT Subject: wxPython and wxFlexGridSizer problem References: <3C9FBE22.A72B4A27@ccvcorp.com> Message-ID: Cliff Wells wrote: | That may be the case, but Jeff brought up some good points. It looks odd | to create a window in this fashion (it looks procedural rather than OO). A | more typical approach would be something like: I know what you mean, but I'd like to write a general procedure which generates an input/output mask based on a relational database describption. And this mask may appear in a wxFrame *or* a wxDialog. So I use the "parent" of the mask as a parameter of my function... Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From Ken.Peek at SpiritSongDesigns.comNOSPAM Thu Mar 28 10:52:45 2002 From: Ken.Peek at SpiritSongDesigns.comNOSPAM (Ken Peek) Date: Thu, 28 Mar 2002 07:52:45 -0800 Subject: Another stab at a "switch/case" construct (for Python 3000): Message-ID: <3ca33c88@news.mhogaming.com> Well-- OK, my new ISP doesn't have a news server, but I found one that I could use to post this with. If you reply to my email, do the 'nospam' thing first to my email address... I really am interested in what people think about this. I have looked at all the other c.l.py posts on this construct, but I don't think anyone proposed this format. BTW-- the 'until' thing in the original letter was already posted, so please disregard that part of this post- (I left it in for accuracy.) -----Original Message----- From: Guido van Rossum Sent: Thursday, March 28, 2002 04:45 To: Ken.Peek at SpiritSongDesigns.NOSPAM.com Cc: Marc-Andre Lemburg Subject: Re: PEP 0275 If you really want to discuss this, it's better to post to c.l.py. --Guido van Rossum (home page: http://www.python.org/~guido/) -----Original Message----- From: Ken Peek [mailto:Ken.Peek at SpiritSongDesigns.NOSPAM.com] Sent: Thursday, March 28, 2002 01:05 To: Marc-Andre Lemburg Cc: Guido van Rossum Subject: PEP 0275 How about: match some_object: ("I dream of Jeanie",): print "with the light brown hair" (1,3,5,7): print "some odd numbers" # 'break' leaves the entire match structure if (time_to_leave): break # 'continue' jumps to the first # statement in the next clause continue (123,456,789): print "some bigger numbers too" (19,56,22): print "some random numbers" (1001,2002,3000): # YES! It IS possible we want to do NOTHING! pass any: print "we got here because there were no matches" This is kind of a neat construct because you can put multiple tests on one line, and it doesn't look too messy (like C's 'switch' would look.) Also-- we are not limited to matching up only integers. This is very clean code compared to a long string of "if/elif/elif/elif/else" clauses... I like READABLE code-- which is why I like Python! Note that the aggregate of the tuples must have unique values and types-- (this allows for efficient implementation, and for future optimization.) A match is found only when BOTH the type and value are the same. 'some_object' can be any object, but it would be wise to not use floating point numbers or other things that do not guarantee a valid '==' compare. I suppose these ambiguous types could be flagged with an error from the compiler, but I would hate to see a run time check (which would slow things down, just to accommodate a bad programmer.) The match clauses do not 'fall through' automatically like a "C - switch" statement-- (this is the source of many errors in 'C'.) A clause can be forced to 'fall through' with the use of a 'continue' statement, which jumps to the first statement in the next match clause (because 'falling through' IS useful sometimes.) I suppose the interpreter/compiler could flag an error "UnreachableCode" (or 'BadIndentation') if 'continue' was used by itself, and there were statements after it at the same indentation level... The 'any' keyword could be changed to 'else' I suppose, but I think the word 'any' "just plain sounds better when you say it", and I like the 'match' keyword better than anything I have seen or can think of... ================================= I have also been mulling over a new 'until' keyword-- it works the same as 'while', but the body of the loop is executed first before the conditional test is made the first time, and the sense of the test is opposite (ie- the test must be FALSE for the body of the loop to be executed again.) 'continue' jumps directly to the conditional test, and 'break' jumps out of the loop (as expected): until something_becomes_true: print 'here we are in the body of the loop' print 'which was executed at least once' print "before the 'something_becomes_true'" print 'test was made.' # we can skip to the test now with a 'continue': if bad_programming_practice == TRUE: continue print 'nope-- no continue' # we can get out of the loop with a 'break': if another_bad_programming_practice: break # we probably need to stop the loop someday: something_becomes_true = do_some_check() ================================= I doubt if any of this will ever make it into Python (well-- maybe Python 3000)-- but it's fun to think about. Well, what do you think? --Ken Peek Ken.Peek at SpiritSongDesigns.NOSPAM.com (This letter is released to the public domain-- KP.) From olav.viken at kmss.no Wed Mar 6 03:54:47 2002 From: olav.viken at kmss.no (olav.viken at kmss.no) Date: 6 Mar 2002 08:54:47 GMT Subject: Pyhon and PIL References: Message-ID: >Maybe this would work? > > import Image > Image.open('yellow.bmp').convert('L').point(255*[0] + [255]) \ > .convert('1').save('yellow.bmp') Yes, it did! Thanks a lot Fran?ois Pinard Best regards Olav From bokr at oz.net Sat Mar 23 22:09:36 2002 From: bokr at oz.net (Bengt Richter) Date: 24 Mar 2002 03:09:36 GMT Subject: load html frameset out of Python script References: <30cf5082.0203221039.791cab07@posting.google.com> Message-ID: On 22 Mar 2002 10:39:43 -0800, news.Andreas at gmx.net (Andreas) wrote: >Hello everybody, > >I am trying to set up a html site with frames. I want to load the >frameset out of a Python script. Meaning what? Do you want to run a python cgi script and generate the frames and content dynamically? Or what is the role of Python in this? You don't need a script to load the file below. You just need to put it in a directory that a web server serves from (along with the specified src files, if you want to see content in the frames). >Frameset definition: > > "http://www.w3.org/TR/html4/frameset.dtd"> > > >right frame > > > noresize marginheight="0" marginwidth="0"> > noresize marginheight="0" marginwidth="0"> > noresize marginheight="0" marginwidth="0"> > marginheight="0" marginwidth="0"> > > > No frame support of your browser! > > > > > When the above is served one way or another from the web server, the browser sees just that much at the first. It sees that there a src= for each frame, so it will request whatever is specified from the server, to fill in the initial pages. If you want control back to a cgi script for the initial content, those sources would typically be something like src="/cgi-bin/some_script.py", of there would be such hrefs in some links in the initial static page set. >From the above, the browser will lay out empty frames and ask for control.html, customer.html, buttons.html, and empty.html from the same base directory it loaded the frameset.html from. They either have to be available as files, or you have to have urls at some point that cause a cgi program to run. >I load this with the following code: > >File = "%s" % ('frameset.html') >PageHandle = open(File, "r") >PageInput = PageHandle.read() >PageHandle.close() >Display(PageInput) > >...the html file will be found but I can see just an empty page. > Empty, or error messages in the frames? What is "Display" and what is the execution environment ?? >What can I do to realize this problem? >Is it possible to write in a specific frame from my scripts? > If you set up a separate cgi program for each frame, then they don't have to know where it's going. The browser will make the initial calls according to the frameset definition. If you want clicks in one frame to generate ouput in another, one way to control the destination is in the target attribute of links, e.g., click for customer stuff could be part of a control frame and would call on sfx.py to generate content in another frame. You could also control stuff with javascript and DOM. BTW, I couldn't find a "Display" method or function in any of the *py or *.c on my hard disk python trees, so I assume it's in a module you imported. If so, which? It helps to let people know a little about the context of your problem ;-) If you are just running interactively, and Display essentially just sends one page to the local browser by writing a temp file and invoking the browser, then what should the browser think? It fill be looking for the other pages in the same temp file area. If you are running a script, and Display basically just writes stdout, I'm still surprised you just get a blank page. What does the browser show if you view source? What are you actually doing? ;-) Regards, Bengt Richter From python at rcn.com Mon Mar 11 23:15:41 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 11 Mar 2002 23:15:41 -0500 Subject: Ho to use a regular expression group reference as hash key References: Message-ID: Maybe the % substitution operator will help. >>> person={"entry1":"value1","entry2":"value2"} >>> target = 'A sample sentence with %(entry1)s and %(entry2)s' >>> print target % person A sample sentence with value1 and value2 Another method would be to attempt to substitute every word and if the word is not is the hash replace it with itself. >>> import re >>> target = 'A sample sentence with entry1 and entry2' >>> person={"entry1":"value1","entry2":"value2"} >>> re.sub( r'b\w+\b', lambda word: person.get(word,word), target ) 'A sample sentence with entry1 and entry2' Raymond Hettinger "Andreas Martin" wrote in message news:f2dbb0ed.0203111447.31eddd81 at posting.google.com... > Hallo ! > > I'm a Python newbie and I have the following problem: > > A hash person={"entry1":"value1","entry2":"value2"} > > and I would like to do a substitution with regular expression (an easy > example) > like this: > > pat = re.compile(r'(entry1)') > t = pat.sub(person[\1],"something...entry1...something") > > I would like to substitute the "entry1" string by the respective hash > element with the group reference \1 as hash key, that is to say > t="something...value1...something". > > Similar in Perl: > > s/(entry1)/%person($1)/ > > I hope my problem is understandable. > Thanks From sandskyfly at hotmail.com Wed Mar 13 03:17:11 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 13 Mar 2002 00:17:11 -0800 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: Martin v. Loewis wrote in message: > Certainly true; there is little interest in Python.NET in the Python > community (just as there is little interest in other branches, such as > Stackless, Psyco, and, to some degree, Jython). I'm somewhat bewildered by this statement. You are surely underestimating the interest of the community in the above projects. perhaps-the-subject-is-smiley-enough-ly-yrs, Sandy From phr-n2002a at nightsong.com Thu Mar 14 09:07:13 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 14 Mar 2002 06:07:13 -0800 Subject: SF vs. Lynx (was Re: zlib vulnerabilities and python) References: Message-ID: <7xr8mnfdke.fsf@ruckus.brouhaha.com> aahzpy at panix.com (Aahz) writes: > OTOH, I still can't submit my stupid bug report AFAICT. Is there anyone > who uses Lynx to access SF? Yes, I do sometimes. From amuys at shortech.com.au Sun Mar 3 23:23:29 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 3 Mar 2002 20:23:29 -0800 Subject: Apology to Bill Gates (was Re: ASV module, CVS modules) References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: <7934d084.0203032023.712a6e37@posting.google.com> sjmachin at lexicon.net (John Machin) wrote in message news:... > Michael Hudson wrote in message news:... > > Skip Montanaro writes: > > > > > John> Python, starting from a Unix background, where there is evidently > > > John> no such thing as an invalid character in a file name, ... > > > > > > I believe "/" is not allowed in Unix filenames. Not sure if this is > > > escapable or not. > > > > Don't think so. NULLs are out, too. > > It is not a case of "not allowed". You simply can't supply a file name > containing a "/" or a NUL (not a *NULL*) because "/" is interpreted as > a path separator and NUL as a string terminator. > > My point was that Unix doesn't proactively check to see if you are > trying to create a file whose name you may never see again. Or more precisely, the unix creat/open syscalls don't take a filename as a parameter, rather they take a pathname which is interpreted with the above definitions in place. As character escaping are considered a UI issue, not an OS issue, all other characters are interpreted literally. If there are good UI reasons for forbidding the use of non-printing characters in filenames, then the UI is responsible for enforcing that. The unix OS takes the reasonable position that if a program considers it necessary to create such files, it isn't the OS's place to refuse. As such it is impossible for creat/open to be passed an invalid argument under the various POSIX standards, therefore EINVAL can't happen. After all, even under NT, if the underlying filesystem might support a given char, the argument can't be considered invalid. Therefore given that the definition of ENOENT (as listed in the linux manpages, my copy of the POSIX function def's is at home) is ENOENT A directory component in pathname does not exist or is a dangling symbolic link. The error for a filename with an embedded char unsupported by the underlying filesystem is probably best described by ENOENT. Andrae Muys P.S. as a matter of interest I had a play to demonstrate non-printable filename handling on a linux box I have available to me: Consider the following... [root at ttdev7 test]# touch ^M^L^D [root at ttdev7 test]# touch hello^Aworld [root at ttdev7 test]# touch helloworld [root at ttdev7 test]# ls ??? helloworld hello?world [root at ttdev7 test]# rm -i * rm: remove `\r\f\004'? y rm: remove `hello\001world'? y rm: remove `helloworld'? n [root at ttdev7 test]# ls helloworld [root at ttdev7 test]# Note the control char's are inserted as literals using ^V^x as this is bash and readline uses ^V to flag control char literals. (the only exception to this appear to be ^C). Also note \r[eturn] == ^M, and \f[ormfeed] == ^L. From rjones at ekit-inc.com Wed Mar 13 17:29:51 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 14 Mar 2002 09:29:51 +1100 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: <20020313092621.C2272@ActiveState.com> References: <20020313092621.C2272@ActiveState.com> Message-ID: <200203132230.WAA10310@crown.off.ekorp.com> On Thu, 14 Mar 2002 04:26, Trent Mick wrote: > [Michael Hudson wrote] > > > Time to look at roundup again? The tracker on sf is starting to piss > > me off (even more). > > If you *are* going to get motivated to look at a different tracker *please* > consider bugzilla. You will find it a much more appropriate than roundup. > > Trent > > p.s. I am gonna regret feeding this. Yes, please be at least a little constructive in your criticism! :) Richard From phd at phd.pp.ru Thu Mar 14 04:34:00 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 14 Mar 2002 12:34:00 +0300 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: ; from bokr@oz.net on Wed, Mar 13, 2002 at 10:36:00PM +0000 References: <3C86047F.1080601@stroeder.com> <20020313201539.2995aad0.andreas@mtg.co.at> Message-ID: <20020314123400.O9851@phd.pp.ru> On Wed, Mar 13, 2002 at 10:36:00PM +0000, Bengt Richter wrote: > Ok, then how about: > ... def __init__(self,s): self.sesc = "\\'".join('\\"'.join(s.split('"')).split("'")) That's limited advantage. Different SQL servers have different rules of quoting. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jeff at ccvcorp.com Fri Mar 22 15:32:28 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 12:32:28 -0800 Subject: Word frequencies -- Python or Perl for performance? References: <1o2m9ucoqb9qqs2fcign6sts3ckc3mqkma@4ax.com> Message-ID: <3C9B94DC.67BC2826@ccvcorp.com> Anders M Eriksson wrote: > Hello Jim! > > I tried to run the program in Python 2.1 but I get errors > > > for line in file: > Here I get the error ^ > for line in file: > TypeError: loop over non-sequence > > Is this something specific for Python 2.2, or just a typo? For Python 2.1, change the offending line to: for line in file.xreadlines(): and you should get the behavior that you want. Jeff Shannon Technician/Programmer Credit International From h_schneider at marketmix.com Fri Mar 22 06:35:32 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Fri, 22 Mar 2002 12:35:32 +0100 Subject: quick win32 pipe and objects question References: Message-ID: Sorry for this newby-question .. why pickle ? "dsavitsk" schrieb im Newsbeitrag news:X0sm8.575$d7.169869 at newssrv26.news.prodigy.com... > when writing and reading from a pipe, is it okay to do something like ... > > >>> t = (0, 1, 2, 3) > >>> r = win32pipe.CallNamedPipe(pipename, t, 512, 0) > > of should i pickle t first? > > -d > > From mkelly2002 at earthlink.net Fri Mar 29 15:21:18 2002 From: mkelly2002 at earthlink.net (Michael Kelly) Date: Fri, 29 Mar 2002 15:21:18 -0500 Subject: Win32 Impersonation References: Message-ID: <63j9aug6a7halrrfd7h3919puq54um4ge8@4ax.com> On Fri, 29 Mar 2002 04:04:32 GMT, "Giganews" wrote: >Upon reading the ActivePython docs, I found >that the user who runs the impersonation script needs SE_TCB_NAME, >SE_CHANGE_NOTIFY_NAME, and SE_ASSIGNPRIMARYTOKEN_NAME priveleges. > >Maybe I'm missing the point here, but the only two accounts on these systems >with these priveleges are the administrator and the local system account. >Obviously, if I already were the administrator I wouldn't have this problem. >I think I'm missing something. Are you using AdjustTokenPrivileges() and related APIs? If not check the Win32 API docs for those calls and see if it applies. Mike -- "I don't want to belong to any club that would have me as a member." -- Groucho Marx From peter at engcorp.com Sun Mar 31 09:07:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 09:07:57 -0500 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> <3CA5F90F.BF37B528@engcorp.com> <3CA6B051.6D55B4D5@engcorp.com> Message-ID: <3CA7183D.C153DF81@engcorp.com> "Martin v. Loewis" wrote: > > Peter Hansen writes: > > If the documentation must be changed, why not just make it clear in > > the documentation what it means when a method returns 1 or 0 or > > None? > > The documentation already says that. However "If the section in fact > existed, return 1. Otherwise return 0." leads to the question "why > aren't you returning a boolean value?", to which the answer is > "because they are not supported in the language". Heh... I thought the answer was "we _are_ returning a boolean value, but they're spelled 1 and 0 in Python". -Peter From jody at adsl-216-62-149-210.dsl.hstntx.swbell.net Mon Mar 25 11:39:29 2002 From: jody at adsl-216-62-149-210.dsl.hstntx.swbell.net (Jody Winston) Date: Mon, 25 Mar 2002 16:39:29 GMT Subject: Porting a Python app to IRIX -- need help References: Message-ID: "Paul F. Dubois" writes: > I am trying to get a Python-based app running on an SGI running IRIX 6.5. I > am running into a problem involving some objects being compiled "n32" and > others "o32". The linker refuses to link them. > > I got pretty far by setting environment variable CC to "cc" but then it > complained that the X11 library is o32. Can an SGI person tell me whether > o32 or n32 is "normal" and what I tell the compiler to be sure I get that? > To force the compilers and linkers to use only one ABI set the environment variable SGI_ABI for example: setenv SGI_ABI "-n32" -- Jody Winston From joel.quinet at be.unisys.com Tue Mar 12 11:13:12 2002 From: joel.quinet at be.unisys.com (Joel Quinet) Date: Tue, 12 Mar 2002 17:13:12 +0100 Subject: ADO and Store Procedure Message-ID: Hi everybody I make some test with ADO and Python which run correctly now. But I still have some little problem : The following code call a stored procedure in SQL Server 7. This stored procedure insert a row in a table. There is a Unique Contsraint on that table. If I try to insert an existing value in that table with the following script, I receive no error .... I would like to receive an error and be able to deale with it. Moreover, My store procedure return 1 in case of problem. How can I rescue that ? How can I do that ? PS : the stored procedure works well in SQL Interactif mode Thanks Joel from win32com.client import constants from win32com.client import gencache mServer = '(local)' mUsr = 'sa' mPwd = '' mDb = 'Test' conn = win32com.client.Dispatch(r'ADODB.Connection') DSN = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=" + mUsr + ";" + "Password=" + mPwd + ";Initial Catalog= " + mDb + " ; Data Source=" + mServer + "" err = win32com.client.Dispatch(r'ADODB.Error') conn.Open(DSN) cmd = win32com.client.Dispatch(r'ADODB.Command') cmd.ActiveConnection = conn cmd.CommandText = "Insert_Continent" cmd.Prepared = 1 cmd.CommandType = constants.adCmdStoredProc cmd.CommandTimeout = 15 prm = win32com.client.Dispatch(r'ADODB.Parameter') prm.Type = constants.adChar prm.Size = 6 prm.Direction = constants.adParamInput prm.Value = 'Europe' cmd.Parameters.Append(prm) rs, res = cmd.Execute() From neal at metaslash.com Mon Mar 4 16:09:23 2002 From: neal at metaslash.com (Neal Norwitz) Date: Mon, 04 Mar 2002 16:09:23 -0500 Subject: Why isn't pychecker mentioned prominently? References: <3C80ED0B.42292C99@tds.net> Message-ID: <3C83E283.6F030BA1@metaslash.com> "Martin v. Loewis" wrote: > > "Edward K. Ream" writes: > > > I just found out about pychecker (http://pychecker.sourceforge.net/) and > > I am wondering why it isn't mentioned prominently all over the Python > > web site: the tutorial, the links on the left and side of the home page, > > topics guides, general reference etc. > > Two reasons: > > a) it is mentioned prominently. Guido mentioned as hist favourite tool > both in the proceedings and his keynote at IPC10. It can't get more > prominent than that, in the Python world :-) > > b) because it is fairly new, and evolving > > c) because nobody submitted patches to the tutorial. > > (you always get three reasons in a message that says it will give two > reasons :-) :-) All of these are true. There have been some conversations about how pychecker should fit into Python. Right now, the timing isn't great. Pychecker has it's share of problems and is a work-in-progress. However, there is general agreement that the functionality pychecker offers will eventually get into Python. We simply need to determine the best approach. In the meantime, I suppose the best approach is to add some doc (both in Python and Pychecker). I added a Python FAQ entry (4.101) a while ago. What are some suggestions for where best to update documenation, provide links, etc. including specific pages or files? Neal From SBrunning at trisystems.co.uk Thu Mar 7 03:54:30 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 7 Mar 2002 08:54:30 -0000 Subject: CP4E was Re: Deitel and Deitel Book... Message-ID: <31575A892FF6D1118F5800600846864DCBCD8B@intrepid> > From: Geoff Gerrietts [SMTP:geoff at gerrietts.net] > For the space of around three years, a child is immersed almost > constantly, from waking to sleep, and even sometimes while asleep, in > language. For those first three years, the child is almost completely > incapable of making him or herself understood. You don't have kids, do you? Children are able to make themselves understood to some extent by a year or so, well in advance of their use of grammatical constriction. Soon after that, they start to put words together into proto-sentences. Again, they are understood. This is at least partly because patents make an effort to understand malformed sentences. Computers don't do this! (Interestingly, though children miss parts of sentences out at this age, and for some time to come, they usually get those parts of the sentence that they do use in the correct order. Stephen Pinker's 'The Language Instinct' is a *facinating* read if you find this sort of thing even remotely interesting - I cannot recommend it too highly.) It seems to me that there are two differences between natural languages and computer languages. Firstly, all children are natural geniuses with natural language. Secondly, when using a natural language imperfectly, one can still make oneself understood. (I certainly hope so, for my sake!) This isn't the case with computer languages. So I don't think that computer languages can be learned in the same way as natural languages. Children learn language by a combination of instinct and trial-and-error. We don't *have* a computer language instinct - only Guido has one of those - and trial-and-error will just mean trial-and-syntax-error. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From zen at shangri-la.dropbear.id.au Tue Mar 12 18:48:23 2002 From: zen at shangri-la.dropbear.id.au (Stuart Bishop) Date: Wed, 13 Mar 2002 10:48:23 +1100 Subject: Text Search Engine that works with Python In-Reply-To: <88bc63c6.0203071841.1867a977@posting.google.com> Message-ID: On Friday, March 8, 2002, at 01:41 PM, Doug Farrell wrote: > So the requirements of the search engine are that it compress the text > (or have index files so small that compression is un-necessary) and > the retrieval engine have an API accessible to Python, not implemented > as a command line tool. I want to incorporate the search engine into a > larger application that links the text together with media. I know, I > know, big demands, but that's why it's in the conceptual stage with me > right now. You may want to download a copy of Zope and see if the ZCatalog product meets all your requirements. I don't think the indexes are compressed, but they may be small enough for your needs anyway. If this is an issue, I believe there is a ZODB storage implementation that stores objects in a compressed format (but they still will chew up RAM). You can talk to the Zope database directly from Python without the need to run the Zope application server so it should interface nicely with your GUI (the Standalone ZODB and just ZCatalog from the Zope distribution might be more suitable in the long run for your product since you won't get all the cruft you don't care about, but using the Zope distribution initially gives you everything out of the box with no hassles). -- Stuart Bishop http://shangri-la.dropbear.id.au/ From justin at iago.org Fri Mar 1 12:18:22 2002 From: justin at iago.org (Justin Sheehy) Date: Fri, 01 Mar 2002 12:18:22 -0500 Subject: Python's Syntax In-Reply-To: ("David Russell"'s message of "Fri, 1 Mar 2002 05:01:53 -0000") References: Message-ID: "David Russell" writes: > if condition == TRUE: > do this > > > How do you tell it when to stop? I just can't figure out how to do it. Could > somebody explain it to me please, even though I have a strange suspicious > that it is one of the simplest deatils imaginable. Just return to the previous indent level. For instance: if test: line1 line2 line3 line4 Lines 1-3 will be executed inside the if clause, and line4 follws it. Python's logical blocks are delimited by indentation. > Also, another thing about Python's syntax. Are statements just sperated by > their lines, or do they have some form of seperator (like a semi-colon)? Either. You may place multiple statements on one line and delimit them with a semicolon. -Justin From garrett at bgb.cc Thu Mar 21 15:54:47 2002 From: garrett at bgb.cc (Don Garrett) Date: Thu, 21 Mar 2002 20:54:47 GMT Subject: IntSpan? References: <3c97c886@news.nwlink.com> <3C99F049.5A78B149@metaslash.com> <3c9a1ae9$1@news.nwlink.com> Message-ID: <3C9A481D.8DE2494D@bgb.cc> Chris Liechti wrote: > using xrange instead of range does not allocate a list but generates > the vaulues when they're needed. > > chris While xrange is an excellent optimization in some cases, it's not quite the same thing as a list, so there are a number of things you can't do that seem relevant. For a non-working example: xrange(1, 500) + xrange(600, 700) -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From phd at phd.pp.ru Sun Mar 17 16:49:02 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 18 Mar 2002 00:49:02 +0300 Subject: time out socket In-Reply-To: ; from evebill8@hotmail.com on Sun, Mar 17, 2002 at 05:33:03PM +0000 References: Message-ID: <20020318004902.A30949@phd.pp.ru> On Sun, Mar 17, 2002 at 05:33:03PM +0000, Billy Ng wrote: > Would anybody please tell me how time out the socket.connect() if the host > does not exists or is unable to connect, thanks! http://www.timo-tasi.org/python/timeoutsocket.py Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mlh at vier.idi.ntnu.no Sun Mar 31 15:18:00 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 31 Mar 2002 20:18:00 +0000 (UTC) Subject: New-style exceptions? Message-ID: Is there a reason why new-style objects can't be used in the raise statement? >>> class Error(object): pass ... >>> raise Error Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be strings, classes, or instances, not type This seems like an artificial restriction... (Using 2.2) -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From emile at fenx.com Sun Mar 3 11:48:36 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 3 Mar 2002 08:48:36 -0800 Subject: question about Generator References: Message-ID: "chongqing xiao" wrote in message news:u84gjbo6v11dca at corp.supernews.com... > Hi, > > Suppose if I have a generator (func) which will return [2,4,6,8] > > Is any way I can just get the first item (instead of using for x in func() > to get the first item) > or stop before I get the last item in the Generator. To get as many as you want, use next: >>> def func(): ... i = 1 ... while 1: ... yield i*2 ... i += 1 ... >>> a = func() >>> a.next() 2 >>> a.next() 4 > Also, any comments on what the following code will do. (I don't have 2.2 > installed so I > can't try it myself) >>> def func(): ... i = 1 ... while i<5: ... yield i*2 ... i+=1 ... >>> for x in func(): ... for y in func(): ... print x,y ... 2 2 2 4 [...] 8 4 8 6 8 8 >>> HTH, -- Emile van Sebille emile at fenx.com --------- From mlh at vier.idi.ntnu.no Tue Mar 19 19:07:14 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Wed, 20 Mar 2002 00:07:14 +0000 (UTC) Subject: Binary generation with distutils? (Freeze, py2exe, etc.) Message-ID: I know there are several solutions available for building standalone binary executables from Python programs (Freeze, py2exe, McMillan Installer, etc.) -- I just wondered if it would be possible to add functionality like this to distutils? E.g. adding some command (xdist, for executable, as opposed to the existing bdist?)... -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From geoff at gerrietts.net Fri Mar 8 19:13:54 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 8 Mar 2002 16:13:54 -0800 Subject: broken pipes, import errors (LONG, INVOLVED) Message-ID: <20020309001354.GH4569@isis.gerrietts.net> At work, I'm seeing an "interesting" problem in my production environment, or maybe two problems. It's one of those problems that crops up only irregularly, and when it does, its symptoms are somewhat changeable. I'm hoping someone might recognize the symptoms and be able to provide a clue about what we're seeing, or at least advice toward resolution. An Admission of Sorts --------------------- I should confess near the start that we're using Python 1.5.2 (slightly patched in the direction of 1.6) and a version of Zope that's so old that most people don't even like to think about it any more (2.1.3 for those that do). These run on top of security-hardened RedHat 6.2 boxes. So I recognize that the systems involved are not exactly up to date. On the other hand, the barriers to upgrading any of these are pretty substantial at a technical level. Consequently, upgrading will be pretty costly in terms of pure labor, regression testing, etc., and it's been slated for an off-peak season. Without a more substantial business case for why we need to upgrade than "because it's likely to be more stable", we need to muddle through as best we can. So with the confession out of the way, let me describe the situation. Strange OSError --------------- Occassionally, the Medusa core of zope hiccups. The way it looks to me, the FCGI server has one end of a "trigger" object that contains a pipe. The asynccore engine behind Medusa has the other end of that pipe, and when the FCGI server "pulls the trigger", Medusa will wake up out of its select loop and deal with the data in its inbox. Well, every once in a while, when the FCGI server goes to "pull the trigger", an OSError: [Errno 32] Broken pipe. Now I think that means that the asynccore end of the pipe has gone and closed the pipe on us, but none of us can figure out why it would have done something that cruel. After this occurs, Zope is pretty much unusable, and must be restarted. This would be bad enough for most people, but it gets worse. Bizarre Import Behavior ----------------------- Sometimes, when we get the strange OSError, even more Bad Things happen after we restart Zope. In particular, we have what we call the "import bug" (you know it's bad when you've got a name for it). We're pretty sure -- as in, all existing records indicate -- that the "import bug" only shows up on the heels of one of the broken pipes. That is, we get a broken pipe error from the FCGI server, we restart Zope, then we get this. "This" is extremely curious. In one of our Zope products, we have a sequence of logic that looks something like this: > statement = "import module.submodule.SubSubModule" > object_nm = "module.submodule.SubSubModule.Object" > > exec statement > object = eval(object_nm) Obviously, the names have been changed to protect the innocent and reduce the complications. When Zope starts back up, the app will execute this block of statements one or more times for several different values of "statement" and "object_nm". Sometimes, though, it fails. The way it fails is both unusual and a little unnerving. The first three lines execute flawlessly. No problem assigning local variables, no problem running the exec. But when we get to the fourth line, the eval fails with an AttributeError: SubSubModule not found. Now, this is a little strange, because we've just exec'ed the statement that imports it not a split second before. Further, we ARE finding "submodule", which would not be imported if it weren't for the exec'ing of statement. So we tried to do some tests to see what was really happening. Things We've Tried ------------------ It was clear to me pretty early on that we could reproduce the perceived behavior by running a script like the following: > import module.submodule.SubSubModule > > delattr(module.submodule, "SubSubModule") > > # this does nothing, really > import module.submodule.SubSubModule > > print eval("module.submodule.SubSubModule.Object") So the question became: who's importing and deleting our module? Well, it's not that simple. It turns out that three things that work in this scenario, don't in ours. Those three things are: - If you look in os.modules before the second import (or any subsequent imports), you'll see the cached module. Well, our exec'ed import was the first import of every module that failed. - If you wrap the "eval" in a try block, and reload() the module on failure, everything gets put back in place. In our case, though, a reload() appeared to work, just like the original import, but the module contained only a fraction of the names it was supposed to. - If you tear it down and stepwise import a piece at a time from the original files, it should work just like a reload(). For us, though, it neither works, nor fails silently like the reload() -- now it fails to import a name (call it AnotherObject) from yet another module (module.anothersub.YASSModule). The failure occurs during a load_source() call. So. Has anyone seen anything like this before? Anyone have any ideas? -- Geoff Gerrietts -rw-rw-rw-: permissions of the beast From secrets at 18teenwhores.com Sun Mar 10 10:55:43 2002 From: secrets at 18teenwhores.com (Mandy) Date: Sun, 10 Mar 2002 10:55:43 -0500 (EST) Subject: Warning; Adult Material Message-ID: <000000000000.g2A7sl0IW06@localhost> LEARN HOW TO GET 100% FREE ACCESS TO PORN PAYSITES! FOLLOW THESE INSTRUCTIONS CAREFULLY ... IT'S SO EASY!! The Secrets the Porn Biz doesn't want you to know! TAKE 1 MINUTE OF YOUR TIME TO READ WHAT I HAVE TO SAY, AND YOU WILL BE DOWNLOADING STACKS OF FREE PORN FROM SOME OF THE INTERNET'S LARGEST PAYSITES ... IT ONLY TAKES A FEW MINUTES!! ------------------------------------------------------------------------ Your email address has been entered into one of our adult entertainment sites for partner offers in your email. If this wasn't you, then to remove yourself from our free info service, reply to this mail with 'remove' in the subject field and you will not receive any further correspondence. ------------------------------------------------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: From shalehperry at attbi.com Mon Mar 25 16:33:29 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 25 Mar 2002 13:33:29 -0800 (PST) Subject: PHP to Python In-Reply-To: Message-ID: On 25-Mar-2002 jeff wrote: > > I'm looking for a tool to translate code from PHP to Python. > > Does it exists ? seriously doubt it. That's almost like asking for a perl -> python (or python -> perl). From duncan at NOSPAMrcp.co.uk Mon Mar 25 11:41:38 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 25 Mar 2002 16:41:38 +0000 (UTC) Subject: PEP262 - database of installed packages References: Message-ID: "Thomas Heller" wrote in news:a7nhv1$mqa0r$1 at ID- 59885.news.dfncis.de: > All true. On the other hand, Python has no possibility to display > or change the owner and access control lists (except if you do some > hardcore win32 programming). It is messy, but not hardcore: Python to display the owner of a file: os.system("dir /q " + filename) Likewise, to display or change the access control list os.system("cacls "+arguments) I don't know of an equivalent to change the owner of a file. -- 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 eppstein at ics.uci.edu Wed Mar 6 19:21:31 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 16:21:31 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , Steve Lamb wrote: > range[foo,bar,baz] is what is there and, for anyone who > takes the time to learn the language instead of looking for problems, finds > that it is quite clear. Speak for yourself, please. To Steve Lamb, range(foo,bar,baz) may be clear but it is not to me. I understand what it means, I don't have to go looking in any texts, I don't pine after C's for(foo,bar,baz) instead, but it still takes me too much unnecessary time to work out the +1's and -1's whenever I want something other than the generic half-open interval. And please avoid the ad-hominems ("too lazy to learn the language"), it doesn't contribute to rational debate. From bokr at oz.net Tue Mar 12 17:07:42 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Mar 2002 22:07:42 GMT Subject: english thesaurus and dictionary References: Message-ID: On 12 Mar 2002 09:05:47 -0800, bobnotbob at byu.edu (Bob Roberts) wrote: >I want to incorporate an english thesaurus and dictionary into my >application. Does anybody know of freely available thesauri and >dictionaries that I could use? dict.org may be of interest. Regards, Bengt Richter From logiplexsoftware at earthlink.net Tue Mar 5 15:59:47 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 5 Mar 2002 12:59:47 -0800 Subject: Python song? (Re: Python isn't necessarily slow) In-Reply-To: <86n0xmg2q4.fsf@skitty.catseye.net> References: <86n0xmg2q4.fsf@skitty.catseye.net> Message-ID: <20020305125947.765c6562.logiplexsoftware@earthlink.net> On 05 Mar 2002 14:48:51 -0600 Tim Legant wrote: > > Oh, are you from across the pond? It was either Bronski Beat or the > Communards who did an interesting cover of Ain't Necessarily So in the > early '80s - I think both groups were Brits.... It's in more of a > Broadway musical style than country, though. It was Bronski Beat (from "Age of Consent"). I don't recall who did the original. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From MaximilianScherr at T-Online.de Sun Mar 10 07:30:51 2002 From: MaximilianScherr at T-Online.de (maximilianscherr) Date: Sun, 10 Mar 2002 12:30:51 -0000 Subject: server questions Message-ID: hi, ok at first my code (questions at the bottom): import os.path import os import threading import SocketServer import binascii import string import socket class Program: def Start(self): ucisfile = os.path.isfile('uoslserver.cfg') pcinfohandler = PCInfoHandler() pcinfohandler.CheckFile() ohandler = OHandler() ohandler.CheckFile() if ucisfile == 0: ohandler.WriteO('Couldn\'t find uoslserver.cfg!') elif ucisfile == 1: readuc = open('uoslserver.cfg') try: address = eval(readuc.readline()) try: ohandler.WriteO('Starting up...') ihandler = IHandler() serverthread = Server(address) serverthread.start() ihandlerthread = threading.Thread(None, ihandler.ReadI, None, (serverthread,)) ihandlerthread.start() ohandler.WriteO('...finished!') except: ohandler.WriteO('...aborted!') except: ohandler.WriteO('Couldn\'t read uoslserver.cfg') class OHandler: def CheckFile(self): ulisfile = os.path.isfile('uoslserver.log') if ulisfile == 0: writeul = open('uoslserver.log', 'w') writeul.close() elif ulisfile == 1: os.remove('uoslserver.log') writeul = open('uoslserver.log', 'w') writeul.close() def WriteO(self, string): writeul = open('uoslserver.log', 'a') print string writeul.write(string +'\n') writeul.close() class Server(threading.Thread): def __init__(self, address): self.serverstate = 1 self.address = address threading.Thread.__init__(self, None, self.Start) def Start(self): self.server = SocketServer.ThreadingTCPServer(self.address, RequestHandler) while self.serverstate == 1: self.server.handle_request() def Save(self): pcinfohandler = PCInfoHandler() pcinfohandler.SetInfoAll() def ShutDown(self): self.serverstate = 0 functionhandler = FunctionHandler() for op in functionhandler.ListOnlinePlayers(): op.Close() sdsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sdsock.connect(self.address) sdsock.close() class RequestHandler(SocketServer.StreamRequestHandler): def handle(self): clienthandlerthread = ClientHandler(self.request) clienthandlerthread.start() class ClientHandler(threading.Thread): def __init__(self, sockobj): self.clienthandlerstate = 1 self.sockobj = sockobj threading.Thread.__init__(self, None, self.Recv) def Recv(self): datahandler = DataHandler() pcinfohandler = PCInfoHandler() while self.clienthandlerstate == 1 and self.sockobj: try: data = self.sockobj.recv(1024) returnvalue = datahandler.Start(data, self) if returnvalue != 0: self.pcserial = returnvalue[0] self.pcname = returnvalue[1] self.pcpass = returnvalue[2] self.pcx = returnvalue[3] self.pcy = returnvalue[4] self.pcz = returnvalue[5] self.pcdir = returnvalue[6] except: self.clienthandlerstate = 0 pcinfohandler.SetInfoSingle(self.pcserial, self.pcname, self.pcpass, self.pcx, self.pcy, self.pcz, self.pcdir) ohandler = OHandler() ohandler.WriteO('Player '+ self.pcname +' logged off!') def Close(self): self.sockobj.close() self.clienthandlerstate = 0 class DataHandler: def Start(self, data, clienthandlerthread): self.converteddata = binascii.b2a_hex(data) self.clienthandlerthread = clienthandlerthread if self.converteddata[:4] == 'fe01': returnvalue = self.HandlePacketfe01() return returnvalue else: return 0 def HandlePacketfe01(self): conversionhandler = ConversionHandler() pcserial = conversionhandler.ConvertHexToInt (self.converteddata[8:16]) pcname = conversionhandler.ConvertHexToStr(self.converteddata [24:340]) pcpass = conversionhandler.ConvertHexToStr(self.converteddata [1116:1190]) pcinfohandler = PCInfoHandler() returnvalue = pcinfohandler.GetInfo(pcserial) functionhandler = FunctionHandler() ohandler = OHandler() if returnvalue != 0: if functionhandler.CheckPass(pcserial, pcpass) == 0: self.clienthandlerthread.sockobj.close() self.clienthandlerthread.clienthandlerstate = 0 return 0 elif functionhandler.CheckPass(pcserial, pcpass) == 1: ohandler.WriteO('Player '+ pcname +' logged on from client address: '+ str(self.clienthandlerthread.sockobj.getsockname ())) return returnvalue elif returnvalue == 0: if functionhandler.CheckPass(pcserial, pcpass) == 0: self.clienthandlerthread.sockobj.close() self.clienthandlerthread.clienthandlerstate = 0 return 0 elif functionhandler.CheckPass(pcserial, pcpass) == 1: ohandler.WriteO('Player '+ pcname +' logged on from client address: '+ str(self.clienthandlerthread.sockobj.getsockname ())) return [pcserial, pcname, pcpass, 554, 576, 0, 0] class FunctionHandler: def CheckPass(self, pcserial, pcpass): pcinfohandler = PCInfoHandler() returnvalue = pcinfohandler.GetInfo(pcserial) if returnvalue != 0: for pcinfo in returnvalue: for op in self.ListOnlinePlayers(): if op.pcpass != pcpass or pcinfo[2] != pcpass: return 0 elif pcinfo[2] == pcpass: return 1 elif returnvalue == 0 and self.FindOnlinePlayerByPCSerial (pcserial) != 0: return 0 elif returnvalue == 0 and self.FindOnlinePlayerByPCSerial (pcserial) == 0: return 1 def ListOnlinePlayers(self): oplist = [] for threadobj in threading.enumerate(): try: threadobj.pcserial oplist.append(threadobj) except: pass return oplist def FindOnlinePlayerByPCSerial(self, pcserial): if self.ListOnlinePlayers() == []: return 0 else: for op in self.ListOnlinePlayers(): if op.pcserial == pcserial: return op else: return 0 class PCInfoHandler: def CheckFile(self): pdisfile = os.path.isfile(os.getcwd() +'\\data\\pc.dat') if pdisfile == 0: writepd = open(os.getcwd() +'\\data\\pc.dat', 'w') writepd.write('[]') writepd.close() def GetInfo(self, pcserial): readpd = open(os.getcwd() +'\\data\\pc.dat', 'r') pcinfolist = readpd.readline() readpd.close() try: pcinfolist = eval(pcinfolist) if pcinfolist == []: return 0 else: for pcinfo in pcinfolist: if pcinfo[0] != pcserial: return 0 elif pcinfo[0] == pcserial: return pcinfo except: ohandler = OHandler() ohandler.WriteO('Couldn\'t read pc.dat') def SetInfoSingle(self, pcserial, pcname, pcpass, pcx, pcy, pcz, pcdir): readpd = open(os.getcwd() +'\\data\\pc.dat', 'r') pcinfolist = readpd.readline() readpd.close() try: pcinfolist = eval(pcinfolist) for pcinfo in pcinfolist: if pcinfo[0] != pcserial: pcinfolist.append[[pcserial, pcname, pcpass, pcx, pcy, pcz, pcdir]] elif pcinfo[0] == pcserial: pcinfolist.remove(pcinfo) pcinfolist.append[[pcserial, pcname, pcpass, pcx, pcy, pcz, pcdir]] except: ohandler = OHandler() ohandler.WriteO('Couldn\'t read pc.dat') writepd = open(os.getcwd() +'\\data\\pc.dat', 'w') writepd.write(str(pcinfolist)) writepd.close() def SetInfoAll(self): readpd = open(os.getcwd() +'\\data\\pc.dat', 'r') pcinfolist = readpd.readline() readpd.close() try: pcinfolist = eval(pcinfolist) for pcinfo in pcinfolist: functionhandler = FunctionHandler() for op in functionhandler.ListOnlinePlayers(): if op.getName() == pcinfo[0]: pcinfolist.remove(pcinfo) pcinfolist.append[[op.pcserial, op.pcname, op.pcpass, op.pcx, op.pcy, op.pcz, op.pcdir]] except: ohandler = OHandler() ohandler.WriteO('Couldn\'t read pc.dat') writepd = open(os.getcwd() +'\\data\\pc.dat', 'w') writepd.write(str(pcinfolist)) writepd.close() class IHandler: def ReadI(self, serverthread): ihandlerstate = 1 ohandler = OHandler() functionhandler = FunctionHandler() while ihandlerstate == 1: input = raw_input() if input == 'c': ohandler.WriteO('Input: c') ohandler.WriteO('Valid commands:') ohandler.WriteO('c -- show this list') ohandler.WriteO('o -- show online players') ohandler.WriteO('a -- save') ohandler.WriteO('s -- shut down') elif input == 'o': ohandler.WriteO('Input: o') ohandler.WriteO('Online players:') opstr = '' for op in functionhandler.ListOnlinePlayers(): if len(opstr) < len (functionhandler.ListOnlinePlayers()) - 1: opstr = opstr + op.pcname +', ' else: opstr = opstr + op.pcname if opstr != '': ohandler.WriteO(opstr) elif opstr == '': ohandler.WriteO('No players are online!') elif input == 'a': ohandler.WriteO('Input: a') ohandler.WriteO('Saving...') serverthread.Save() ohandler.WriteO('...finished!') elif input == 's': ohandler.WriteO('Input: s') ohandler.WriteO('Shutting down...') serverthread.ShutDown() ihandlerstate = 0 ohandler.WriteO('...finished!') class ConversionHandler: def ConvertHexToInt(self, hex): while hex[0] == '0': hex = hex[1:] int = string.atoi(hex, 16) return int def ConvertHexToStr(self, hex): hex = string.replace(hex, '00', '') str = binascii.a2b_hex(hex) return str program = Program() program.Start() ok now the two questions i have at the moment are: 1)how can i shut dwon the server right? (see Server class) 2)how can i find out right if i a client disconected? (see ClientHandler class) thanks in advance, Max P.S. I know it's a very very bad scripted:), you don't need to tell me that:) From holger at trillke.net Sun Mar 24 15:44:28 2002 From: holger at trillke.net (holger at trillke.net) Date: Sun, 24 Mar 2002 21:44:28 +0100 Subject: Stopping threads from the outside In-Reply-To: <3C9E173A.88BBDBB4@engcorp.com>; from peter@engcorp.com on Sun, Mar 24, 2002 at 01:13:14PM -0500 References: <3C9E173A.88BBDBB4@engcorp.com> Message-ID: <20020324214428.H12768@prim.han.de> > > You really want to know it? I am currently working > > on (coded) agents which move through the network. > > "The network"? Which one? The Internet, or an internal > network over which you have full control? Who controls > the servers on which these agents will be running? well. at the moment the servers are under my control. but this is hopefully going to change. > > But of course i'd sometimes like to shut down some or > > all agent-threads. > > Run them in a separate process and kill the process when > it's "sometime"? If you can live without individual > control. Maybe you can identify groups of them? As Boudewijn pointed out this would lead to the problem of managing interprocess communication. One of the reasons i am developing this system is to _avoid_ having interprocess communication and/or remote references that bloats and complicates the system. In fact it is quite hard to group the agent-threads because they are very autonomous (and btw quite cooperative with other agents). And I just wanted to deploy a "kill-agent" that manages to shutdown certain or all Agent-threads. thanks for your replies so far! holger From david.abrahams at rcn.com Sat Mar 30 09:51:27 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sat, 30 Mar 2002 09:51:27 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: <016d01c1d7fa$c679ee40$0202a8c0@boostconsulting.com> ----- Original Message ----- From: "Guido van Rossum" To: "David Abrahams" Cc: ; Sent: Saturday, March 30, 2002 9:23 AM Subject: Re: [Python-Dev] PEP 285: Adding a bool type > > > [David Abrahams] > > > > 6) Should we eventually remove the inheritance relationship > > > > between Int and Bool? > > > > > > > > I hope so. Bool is-a Int doesn't seem like the right relationship to > > > > me, unless perhaps we make Int is-a Long... naah, not even then. > > > > > > Hm. In your favorite language bool is one of the integral types. > > > Doesn't that imply pretty much the same thing? > > > > Well, I try not to play favorites <0.002 wink>, but the implicit > > conversion rules in C++ are admittedly and unfortunately liberal. > > However, bool is detectably NOT derived from int in C++: > > > > void f(int const&); > > f(false); // error! > > assert(boost::is_base_and_derived::value); // fails! > > I don't understand this example, but I though int and bool weren't > considered classes in C++, so I'm not sure this matters. That's correct, they're not. Still, it matters that when you do type introspection the system doesn't tell you they're related by inheritance. I'm sure I've written programs that would break if that answer suddenly changed. My point is just that "int and bool are integral types" is a very different thing from "bool is derived from int" (for another example, derivation implies one-way implicit conversion from derived->base, whereas the numeric types are all implicitly inter-convertible). > I know you > don't care, but C99 *does* consider bool an integral type. As does C++, and why wouldn't I care? > Another argument for deriving bool from int: implementation > inheritance. A bool must behave just like an int, and this is most > easily accomplished this way: the bool type doesn't have > implementations for most operations: it inherits them from the int > type, which find a bool acceptable where an int is required. I recognize that as the /only/ real argument for such derivation. Many are suspicious of public implementation inheritance these days, tending to prefer delegation so as not to expose a false is-a relationship, breaking the LSP. However, I think bool may squeeze by on that count since as I said it's immutable. Uh, whoops, no: the repr() and str() functions, for example change the way it works in incompatible ways. > > > Anyway, do you have a use case where it matters? > > > > Given that Bool is immutable, I have no cases other than examples of > > type introspection which can be written to account for the fact that > > Bool is-a Int. However, it does make certain things trickier to get > > right: > > > > numeric_types = [ Int, Long, Bool, Float, Complex ] > > for t in numeric_types: > > if isinstance(x, t): > > # Do something... > > > > This sort of thing could depend on getting the order of the list right > > (I didn't). > > Using isinstance() this way is usually bad. Can you say something about this that doesn't invoke a moral judgement? I don't believe in evil programming practices, just useful/fragile ones. > And who knows that long > doesn't inherit from int? In Python, people make assumptions based on their implementation because for details like this there is often no other guideline. > (At some point in the future it may, or > they may become the same thing -- see PEP 237. Well, sure, anything could happen. Anyway, I don't have a strong position about this issue, but it rubs my instincts the wrong way. happy-as-a-wet-cat-ly y'rs, dave From aahz at pythoncraft.com Mon Mar 25 10:03:39 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Mar 2002 10:03:39 -0500 Subject: Indentation problem References: Message-ID: In article , Gilles Diribarne wrote: > >2/ Programmers wants independence: some wants to manage building blocks >with spaces, other with tabs, some wants length = 4 with tabs. >I would like to use my own programming style! But, my code risks to be >not supported by others. Bingo! That's why you should follow Guido style. Like the tight structure of a sonnet, what you lose in freedom of format, you gain in freedom from thinking about format. Really, it works much better; I fought on your side for a couple of years before I Saw The Light. >2/ Emacs and a great number of editors cannot indent region, since the >building blocks are only in programmer's mind. Not true, AFAIK. Have you tried using Emacs in Python mode? >3/ A large number of programming language use this. C, PERL, Ruby, ... >Why not Python? Because those languages are not built on actual human factors research; Python is based on ABC. Find out some info about ABC before you make further comments. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From bokr at oz.net Wed Mar 13 23:12:32 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Mar 2002 04:12:32 GMT Subject: win32 extension: rare PythonService problem References: Message-ID: On Thu, 14 Mar 2002 00:46:39 +0000, Dale Strickland-Clark wrote: >bokr at oz.net (Bengt Richter) wrote: > >>On 10 Mar 2002 21:55:37 GMT, bokr at oz.net (Bengt Richter) wrote: >>[...] >>>But I'd check the event logs (run "%SystemRoot%"\system32\eventvwr.exe) first >> >>Oops, misplaced quote, that won't work verbatim. Try >> >> "%SystemRoot%\system32\eventvwr.exe" >> > >Actually, either quoting approach works fine with NT/W2K. That's interesting. I tried the first version on my system and got an error. (That's why I posted my Oops.) The event viewer starts, but it complains that the file name, directory name, or volume label syntax is incorrect, whereas with the second version it comes up fine. I have NT4sp3 on this box. Can you shed some light? Regards, Bengt Richter From pearu at cens.ioc.ee Fri Mar 29 07:03:26 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Fri, 29 Mar 2002 14:03:26 +0200 Subject: Anyone need a program written? In-Reply-To: <3ca43ef4.3666136@news.tudelft.nl> References: <3ca43ef4.3666136@news.tudelft.nl> Message-ID: On Fri, 29 Mar 2002, Fused wrote: > I'm currently trying to master Python, but to succeed I need to > exercise. However, I detest building programs that have already been > built a kazillion times and aren't of use to anyone. > Can anyone think of a program that I could build that would actually > have use to someone (you?)? I'm trained in Delphi, know some Java and > rudimentary C, so the programs don't need to be newbie-easy ( I like a > challenge: the greater the challenge, the faster I'll learn ;-) ). > Great! How about implementing Delphi to Python translator? Basically, you'll need to write a parser that reads Delphi (OOP) code and then translates it to the corresponding Python code. There are many yacc/lex type of packages already available that will ease this job. I recommend PLY http://systems.cs.uchicago.edu/ply/ Regards, Pearu From martin at v.loewis.de Fri Mar 1 18:51:38 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Mar 2002 00:51:38 +0100 Subject: Multple HTTPS requests over the same socket References: Message-ID: "Chad Maine" writes: > I have class that opens an SSL socket to an HTTPS server in it's > __init__. I then call a class method to send the headers and make > the request ( a 'POST') and return the results. If I try to use > that same SSL socket again for another request, I get nothing. Is > what I'm trying to possible or do I need to close the socket and > open another? At a minimum, it depends on the protocol you are using. You need to use HTTP/1.1., and post a Connection: Keep-alive header, otherwise the server will close the socket. The server may still close the connection even if you request that it be kept alive. Regards, Martin From gh_pythonlist at gmx.de Sun Mar 3 21:30:55 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 4 Mar 2002 03:30:55 +0100 Subject: Calling java servlets using python In-Reply-To: References: Message-ID: <20020304023054.GB3682@lilith.hqd-internal> Le 04/03/02 ? 00:29, gopesh_sharma ?crivit: > Dear All: > > Please let me know how to call java servlets using python? You need to be more specific what exactly you want to accomplish. Python is the client, the Java servlet is the server: use urllib/ urllib2. Or did you have something else in mind? > I need this help urgently. :-X Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 0.4 ?C Wind: 2.3 m/s From mlh at vier.idi.ntnu.no Tue Mar 26 13:43:53 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 26 Mar 2002 18:43:53 +0000 (UTC) Subject: Streaming XML-RPC? References: <3C9F51EE.5000203@jerf.org> <3C9FAF96.5DE9A0@bgb-consulting.com> Message-ID: In article , Skip Montanaro wrote: > > Don> Are there any decent (finished/tested) Jabber libraries for Python? > >Don't know what its status is, but there is jabberpy: > > http://jabberpy.sourceforge.net/ It's LGPL, which may make it unsuitable for some projects (like the standard Python library). But it seems to support the basic protocol. -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From sorry.antispam at address.net Mon Mar 18 16:12:46 2002 From: sorry.antispam at address.net (sorry.antispam at address.net) Date: Mon, 18 Mar 2002 21:12:46 GMT Subject: Initialization of base classes Message-ID: <52mc9u0ghanm3bg0ajt8aro58bqce6ki2s@4ax.com> On pp 74 of Bealey's excellent book "Python Essential Reference, 2nd Ed" it is written: "When an instance is created [of a derived class], the __init__() methods of base classes are not invoked. Thus, it's up to a derived class to perform the proper initialization of its base classes, if necessary" Is this really true? If you have: class A: def __init__(self): print "Class A" class B: def __init__(self): print "Class B" class C(A): pass class D(A, B): pass Then: w = A() --> "Class A" x = B() --> "Class B" y = C() --> "Class A" z = D() --> "Class A" Hence, instantiating class C does in fact invoke the constructor of class A, but not of class B. i.e., only the constructor of the first base class is invoked. Is this a bug in the book, or a bug in Python 2.1? And if it's not a Python bug, what is the rationale for only calling the constructor of the first base class, and not the other base classes? ...Edmund. From amuys at shortech.com.au Wed Mar 13 19:07:11 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 13 Mar 2002 16:07:11 -0800 Subject: Why Don't Scripts Run ? References: <3C8F9C59.F9408D47@mcn.net> <1p9v8u4vo4dqpccjsom40gtjlgtaiedve8@4ax.com> Message-ID: <7934d084.0203131607.5800b1b@posting.google.com> Michael Kelly wrote in message news:<1p9v8u4vo4dqpccjsom40gtjlgtaiedve8 at 4ax.com>... > On Wed, 13 Mar 2002 18:37:00 GMT, jrc wrote: > > >Hi - I'm a reasonably experienced programmer. I work in > >Windows (ME). Thinking to give Python a try, I downloaded > >v22 and installed. At first, it looks good, but then, I discover > >it seems impossible to get any scripts to run in the command > >prompt, using any available documentation whatever. I even > >have Chris Fehily's book - essentially none of his examples > >work with scripts from command prompt; yet this is a 2002 > >book . (?!!) > > Hi. If you don't have any Python 2.2 dependencies or just > want to try Python out you might find it less frustrating to > download ActivePython 2.1. For me(using Win98 2nd Ed.) > even the Windows Scripting Host worked out of the box. > I've even been using my COM servers on Win98 using > ActivePython with no problems at all. > On the W2000 box I have to use at work atm, I just installed cygwin and included python2.2. Gave me a decent cli, and python2.2. Administrator at TTDEV2 ~ $ pytest.py Hello World Administrator at TTDEV2 ~ $ python pytest.py Hello World Administrator at TTDEV2 ~ $ ls -l pytest.py -rwxr-xr-x 1 Administ None 39 Mar 14 10:09 pytest.py Administrator at TTDEV2 ~ $ cat pytest.py #!/usr/bin/python print "Hello World" Administrator at TTDEV2 ~ $ which python /usr/bin/python Andrae Muys From niemeyer at conectiva.com Sun Mar 24 15:36:45 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sun, 24 Mar 2002 17:36:45 -0300 Subject: yenc encoding? In-Reply-To: References: <3c9b8743.23437968@news.t-online.de> Message-ID: <20020324173645.C20294@ibook.distro.conectiva> > > Does someone work on a yenc-encoder/decoder for python? Both "base64" > > and "binascii" are there in the python standard library, after all. > > > > Just wondering: Should an implementation for a new encoding follow the > > base64-model (that is, have four funcs encode, encodes, decode, > > decodes) or the binascii-modell (a2b_yenc,b2a_yenc) or something > > totally different altogether? > > You might want to take a look at > > http://www.exit109.com/~jeremy/news/yenc.html > > The guy seems to make very valid points. ----- Conclusions I, and others, have repeatedly pointed out what is wrong with yEnc, and we have been ignored. Unfortunately, it has the big selling point of smaller encoding, so getting users to accept it and to demand support for it from their newsreaders has been remarkably easy, and yEnc has spread across Usenet like a plague. ----- Heh.. that's the real world. He should be helping yEnc's author to integrate it into the MIME standards instead of writing such a long critique. I could keep talking for hours about why SMTP, TCPIP, and dozens of standards we use are "bad", but they implemented something necessary at their time. If yEnc has spread across usenet, it's too late. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From eppstein at ics.uci.edu Sun Mar 10 19:58:49 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 10 Mar 2002 16:58:49 -0800 Subject: Modulo operator : differences between C and Python References: <3C8BE537.74E55963@mega-nerd.com> Message-ID: In article <3C8BE537.74E55963 at mega-nerd.com>, Erik de Castro Lopo wrote: > > Just recently I prototyped a relatively complex algorithm in Python > before converting it to C. During this conversion I noticed that > the modulo operator returns different results in C and Python if > the numerator is negative. For positive values they produce the same > result. Yes. Python produces the correct results. C doesn't. Almost every time I use modulo in C, I end up having to fix it by adding the modulus if the result is negative. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From geoff at gerrietts.net Fri Mar 29 20:48:32 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 29 Mar 2002 17:48:32 -0800 Subject: runtime location discovery Message-ID: <20020330014832.GF7602@isis.gerrietts.net> I'm writing a program designed for maximal flexibility, with minimal dependencies. The other night, I tried to put in a chunk of code that allowed the program to be executed from an arbitrary location (like a user's home directory) without previously knowing where we were installed (allowing the app to be installed wherever it seems most natural to the system administrator). The code I wrote did this: root_location = os.path.dirname(sys.argv[0]) Later, I could use root_location as a prefix in statemnts like: Image.open(os.path.join(root_location, "image/naked_chicks.png")) or whatever ;) That worked famously, but infamy was a mere logical step away. When I created a symlink to the script, it went shopping for the resource files at all in ~geoff/bin/ instead of ~geoff/src/sp/. Obviously, it didn't find them. Now I can go look for symlinks and resolve them, that's not a problem. But a hard link would create the same problem all over again. So I'm curious -- this can't be an uncommon hurdle to hop. How have other people solved the problem? Thanks, --G. -- Geoff Gerrietts http://www.gerrietts.net/ "If I were two-faced, would I be wearing this one?" --Abraham Lincoln From fredrik at pythonware.com Tue Mar 12 16:26:10 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Mar 2002 21:26:10 GMT Subject: english thesaurus and dictionary References: Message-ID: Bob Roberts wrote: > I want to incorporate an english thesaurus and dictionary into my > application. Does anybody know of freely available thesauri and > dictionaries that I could use? this might be useful: http://www.dcs.shef.ac.uk/research/ilash/Moby/ "Moby Thesaurus: 30,000 root words, 2.5 million synonyms and related words" "Moby Words: 610,000+ words and phrases. The largest word list in the world" From shomon at softhome.net Fri Mar 1 04:34:03 2002 From: shomon at softhome.net (skoria) Date: Fri, 01 Mar 2002 09:34:03 -0000 Subject: newbie lists and code examples for OOP. Message-ID: Hi Firstly: is there a better forum for newbie questions like this one? It's hard for me to post to a high traffic list, and maybe there's a local uk based one or one specifically aimed at newbies. I'm trying to write a class where one function calls a method in the same class. Right now I'm doing this with trial and error, and I don't really understand where I need to put parentheses, use (self), etc. I can't find any "functional" examples of object oriented programming on any online tutorials, or any simple programs already written that can be used as a good tool to figure out how to call functions within classes in python, when to use self.* what internal functions (like __init__) can be used for. Lots of theory on this, but no functional examples. Can anyone suggest any? Thanks, Ale From brandon.rhodes at gtri.gatech.edu Sun Mar 24 15:43:50 2002 From: brandon.rhodes at gtri.gatech.edu (Brandon Craig Rhodes) Date: 24 Mar 2002 15:43:50 -0500 Subject: NormalDate 1.2 released References: Message-ID: <87wuw1hf21.fsf@europa.gtri.gatech.edu> "Delaney, Timothy" writes: > All calendars are ridiculous. It should be very simple ... > > 13 x 28 day (4 week) months = 364 days. > > 1 "extra" day (new year?) > 1 additional day in leap years. > > IIRC this is the system that the shire hobbits used. Not quite; the Shire calendar involved: 12 months of 30 days = 360 days 2 days of Yule (between December and January) 3 days of Lithe (between June and July) + the Overlithe, added to the Lithedays in leap-years More details and a rather attractive chart can be found at: http://www.shire-reckoning.com/calendar.html > Why was this simple system never adopted? Habit. -- Brandon Craig Rhodes http://www.rhodesmill.org/brandon Georgia Tech Research Institute brandon at rhodesmill.org From logiplexsoftware at earthlink.net Tue Mar 5 14:04:15 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 5 Mar 2002 11:04:15 -0800 Subject: Order of constructor/destructor invocation In-Reply-To: References: Message-ID: <20020305110415.4115ca48.logiplexsoftware@earthlink.net> On Tue, 05 Mar 2002 12:49:05 -0500 Justin Sheehy wrote: > "Reginald B. Charney" writes: > > Basically, I need to know if the order of destruction is guaranteed to be > > the reverse of construction when reference counts on the objects are the > > same (e.g., 1 on this case). Without this guarantee, I don't understand how > > Python can effectively use destructors - it falls into the same hole as > > Java. For me, this is a show-stopper. > > This makes no sense. Actually it makes perfect sense. He's asking if, when the reference counts are all equal (in this case 1), the objects will be destroyed in the reverse order they were created when the reference counts drop. However, I agree that depending upon the order of destruction of an object is a bad idea, and worse, won't work at all under Python. I would consider this sort of behaviour to be a side-effect and something to be avoided. While in the particular example given it looks like an elegant solution (and would be, if that were the extent of the application - which I doubt ;), this type of logic in anything more complex is going to be at least somewhat non-obvious and has no real benefit as far as conciseness (he could avoid using the destructor altogether and simply have an end() method which he calls explicitly - more obvious at the cost of 3 LOC). I also think his assertion that Python can't effectively use destructors is a bit overstated. What he's really saying is he can't use Python destructors in the fashion he intends. However, I've always considered destructors to be a method for cleaning up /after/ an object, not finishing its function, which Python seems to do well enough. I consider using a method that claims to do one thing (in this case, destruction of an object) to sneak in something unrelated is a bad idea. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From aahz at panix.com Fri Mar 1 09:50:19 2002 From: aahz at panix.com (Aahz Maruch) Date: 1 Mar 2002 06:50:19 -0800 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <20020227163411.71b4b4d8.alex@netWindows.org> Message-ID: In article , Michael Hudson wrote: >Dennis Roark writes: >> >> The Python book appears substantially based on the templates of >> their previous books. > >Certainly the first draft of chapter 2 that I reviewed[0] looked >suspiciously like the corresponding chapter from Java:HTP. That went >back with a lot of red ink on it... All right, let me ask: are there any reviewers who think that PyHTP looks like a book written by Python programmers rather than a book written by Java programmers? >[0] My, there were a lot of reviewers weren't there? Yup. A lot of *opinionated* reviewers, at that. In all fairness, it's pretty clear that Deitel paid a fair amount of attention to our comments, but thought it was more important to stick with the style of their existing books. And, heck, they *did* pay well for my time. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From tim.one at comcast.net Mon Mar 18 22:42:59 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 18 Mar 2002 22:42:59 -0500 Subject: RELEASED: Python 2.2.1c1 In-Reply-To: <3C972183.3050804@bigfoot.de> Message-ID: [Michael Hudson] > I would ask those of you with access to the more > unusual platforms (i.e. not Linux/x86, Win32/x86) to run test_math in > verbose mode [Gerhard H?ring] > How would I do that? python Lib/test/test_math.py For example, on Windows: C:\Python22>python Lib/test/test_math.py math module, testing with eps 1e-05 constants acos asin atan atan2 ceil cos cosh exp fabs floor fmod frexp hypot ldexp log log10 modf pow sin sinh sqrt tan tanh exceptions C:\Python22> The last part ("exceptions") isn't normally run. If it's unhappy, it will blow up (raise some sort of exception). From robin at jessikat.fsnet.co.uk Tue Mar 12 04:18:33 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 12 Mar 2002 09:18:33 +0000 Subject: PEP 285 bool types Message-ID: Any one know what the effects of introducing the proposed bool type will be? I see it generating large traffic on the dev list, but what will it really mean and will there be yet another great divide in python versions? -- Robin Becker From gh_pythonlist at gmx.de Thu Mar 7 13:06:55 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 7 Mar 2002 19:06:55 +0100 Subject: hexstring to string? In-Reply-To: References: Message-ID: <20020307180655.GA1317@lilith.hqd-internal> Le 07/03/02 ? 17:32, maximilianscherr ?crivit: > i made a function to convert a hex string containing character to a > normal string. > > it looks like this: > > class ConversionHandler: > def ConvertHexToStr(self, hex): > letter = 0 > str = '' > while len(str) < len(hex) / 2: > nextletter = letter + 2 > str = str + chr(int(hex[letter:nextletter], 16)) > letter = nextletter > > return str > > hex looks like: 414243 > > but why does it not work? It does work correctly. Btw. you could have just used binascii.unhexlify from the Python standard library. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 10.3 ?C Wind: 5.5 m/s From henrik.motakef at web.de Mon Mar 11 17:53:24 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 11 Mar 2002 23:53:24 +0100 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8CC0CE.50509@geneva-link.ch> Message-ID: <871yeq4syj.fsf@apo.hmotakef.int> Boris^2 writes: > What sounds really like April 1st is M$ naming open source software > (rather than, eg, Outlook or Windows) "potentially viral software". Don't make them worse than they are. >From Microsofts "Important Macro Virus tips" for Office on the Mac: Q: Will the virus [Melissa] impact my Macintosh if I am using a non-Microsoft e-mail program, such as Eudora? A: If you are using an Macintosh e-mail program that is not from Microsoft, we recommend checking with that particular company. But most likely other e-mail programs like Eudora are not _designed to enable virus replication_. From sjmachin at lexicon.net Thu Mar 21 07:41:35 2002 From: sjmachin at lexicon.net (John Machin) Date: 21 Mar 2002 04:41:35 -0800 Subject: how to read full file into buff for re using? References: Message-ID: "Zoom Quiet" wrote in message news:... > i'm chinese python fresh men; help please! > how to read full file into buff for re object using? > such as: > re.sub() > ??! import re print re.sub(r"\bmen\b", "man", file("ni_de_message").read()) From joonas at olen.to Mon Mar 25 16:34:41 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Mon, 25 Mar 2002 23:34:41 +0200 Subject: python cgi problem References: <1573b893.0203250317.693ef1dc@posting.google.com> Message-ID: <3C9F97F1.D9475BF5@olen.to> etienne wrote: > > hi there ! > > I'm programming such a cgi: > step 1- user submits some data > step 2- cgi validates data > step 3- outputs a html file telling the user to wich url point to find > output > step 4- do the hard work. > > the reason for step 3 is that step 4 needs to dig in a very large > database, and may take lot of time > > everything woks fine but output of step3 comes when step 4 is over and > user needs to wait up to some minutes for his response. > > cgi schema is as follow: > > def main(): > # 2 > params = validate_params() > # 3 > htm_out = generate_output() > print htm_out > # 4 > os.system(" python my_module.py params &") > > I can see results of print htm_out when os.system(" python > my_module.py params &") is over > > can i force htm_out output somehow ??? It is explained at http://starship.python.net/crew/davem/cgifaq/faqw.cgi?req=show&file=faq02.005.htp how to run commands in the background from CGI scripts. Also sys.stdout.flush() might work for your purpose. From skip at pobox.com Tue Mar 19 00:47:33 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Mar 2002 23:47:33 -0600 Subject: RELEASED: Python 2.2.1c1 Message-ID: <15510.53493.198841.313608@12-248-41-177.client.attbi.com> mh> I would ask those of you with access to the more unusual platforms mh> (i.e. not Linux/x86, Win32/x86) to run test_math in verbose mode Seemed like a good chance for me to get some exposure to the SF compile farm, so I logged in, selected MacOS X, downloaded and built 2.2.1c1, and got this when I tried the math regression test: ./python Lib/test/test_math.py math module, testing with eps 1e-05 constants acos asin atan atan2 ceil cos cosh exp fabs floor fmod frexp hypot ldexp log log10 modf pow sin sinh sqrt tan tanh exceptions Traceback (most recent call last): File "Lib/test/test_math.py", line 195, in ? test_exceptions() File "Lib/test/test_math.py", line 192, in test_exceptions raise TestFailed("sqrt(-1) didn't raise ValueError") test_support.TestFailed: sqrt(-1) didn't raise ValueError -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From lac at strakt.com Sat Mar 23 11:07:29 2002 From: lac at strakt.com (Laura Creighton) Date: Sat, 23 Mar 2002 17:07:29 +0100 Subject: How to get Checkbutton Handle? In-Reply-To: Message from mnations@airmail.net (Marc) of "22 Mar 2002 15:05:59 PST." <4378fa6f.0203221505.5d18a75f@posting.google.com> References: <4378fa6f.0203221505.5d18a75f@posting.google.com> Message-ID: <200203231607.g2NG7Trq007099@ratthing-b246.strakt.com> > This seems like an easy question, but that answer has proven fairly > difficult. I am simply trying to get the checkbutton handle back, > exactly the same way I do it with the Label or RadioButtons, etc. I am > doing it this way: > > self.allCheck = IntVar() > self.allButton = Checkbutton(albutFrame, text="Check to select all > test scenarios", state=NORMAL, anchor=W, > variable = self.allCheck, command = self.select > All).pack() > print "allButton location is ", self.allButton > > But I don't get the handle back. All I get is this: > > allButton location is None > Yes. Storing the result of packing is useless as you just found out, because the pack method returns None. Laura Creighton From bokr at oz.net Wed Mar 20 13:13:42 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Mar 2002 18:13:42 GMT Subject: Remove empty lines References: <3C98C025.7741BA58@ifi.uio.no> Message-ID: On Wed, 20 Mar 2002 18:00:21 +0100, Kristin Skoglund wrote: >Hi > >I am trying to make a script that reads javafiles and remove comments >and empty lines. The script looks like this...... > >def removestuff(file): > > infilename=file > > infile=open(infilename, 'r') > > copyfile=infilename +".bak" > > newfile=open(copyfile,'w') > > str = infile.read() > > str=re.sub(r"/\*\*\n.*\n*\*/|/\*\n.*|\*.*|\s*/\s*"," ",str) #This strips away comments > > lines=re.split("\n",str) > > for line in lines: # Here I try to remove the emty lines > > if line== '': > > continue > > elif empty: > > continue > > else: > > tmp.append(line) > > newfile.write(line) > > infile.close() > > newfile.close() > >...and everything works except the removal of empty lines. Does anyone >knoe whats wrong? > What do you see if you do a hex char dump of the new file, where it has "empty" lines? Maybe you need to match on all-white-space instead of '' after splitting with \n ? Regards, Bengt Richter From jason at jorendorff.com Fri Mar 1 04:04:13 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 1 Mar 2002 03:04:13 -0600 Subject: ASV module, CVS modules In-Reply-To: <3C7F4014.7090800@stroeder.com> Message-ID: Michael Stroder wrote: > John Machin wrote: > > You 2: On Windows, either use forward slashes "c:/test_data.csv" (it > > works!) > > AFAIK this does not work on W2K anymore. I might be wrong. As far as I can tell, you are. I'm constantly using this ability on Windows 2000. ## Jason Orendorff http://www.jorendorff.com/ From tchur at optushome.com.au Sat Mar 23 19:59:26 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 24 Mar 2002 11:59:26 +1100 Subject: MS Sql Server References: <788n8.60257$bj1.19179906@news02.optonline.net> Message-ID: <3C9D24EE.6C7636D0@optushome.com.au> Chase wrote: > > Wondering what the most accepted practice is, for communicating to Sql > Server Databases. Is it the ODBC module ? mxODBC ? Is there an ADO module ? You can use the mxODBC module but Object Craft have a Python interface which is specific to MS SQL Server and Sybase - see http://www.object-craft.com.au - but you may want to check with its developer, Dave Cole, as to its suitability for production systems. Tim C From chris.gonnerman at newcenturycomputers.net Fri Mar 29 22:01:18 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 29 Mar 2002 21:01:18 -0600 Subject: Another stab at a "switch/case" construct (new proposal): References: <20020329150225.7efdaf2b.logiplexsoftware@earthlink.net> Message-ID: <004d01c1d797$401f2120$0101010a@local> ----- Original Message ----- From: "Cliff Wells" > > Now which is cleaner? I think the perceived need for this type of > construct is a holdover from thinking in other programming languages versus > thinking in Python. Bingo. Like I said before, "clearer code" is not good enough. The advantage must be *overwhelming*, not just good. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From irmen at NOSPAMREMOVETHISxs4all.nl Wed Mar 27 17:24:52 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Wed, 27 Mar 2002 23:24:52 +0100 Subject: unicode experiments + questions Message-ID: Hello I was experimenting with Python 2.2's unicode strings and different encodings. First, what is the best way to enter international and/or unicode characters in your Python source? I can't just type the Euro sign and trust that it is read as a Euro sign on another platform, because how does Python know the character encoding of the source file! So I'm using the unicode escape char syntax, but that is cumbersome (where do I look up all my special characters?) and hard on the eyes. I also have the following question: what exactly happens when I type "print u" in Python, where u is a unicode string? for example; >>> e=u'\u20ac' >>> e u'\u20ac' >>> print e ? (<--- this is an Euro symbol on my screen) What charset does the print convert to? I'm on Win2000, so when I type >>> print e.encode('cp1252') I get the Euro symbol. Does print automatically convert to the windows charset cp1252? How does Python know this charset, because in my syte.py encoding="iso-8859-15". When I type >>> print e.encode('iso-8859-15') I don't see the Euro symbol, but some other weird symbol. For your interest, below is the test program I'm using to generate different encoded documents. Interestingly enough, UTF-7 is not understood by Opera 6. IE 5 and Mozilla get it right. import codecs euro=u'\u20ac' atilde=u'\u00e3' print 'The unicode euro symbol = ',repr(euro),' --> ',euro print 'The unicode a-tilde = ',repr(atilde),' --> ',atilde def getHTMLDoc(encoding): doc=u'\n' \ u'\n' \ u'Euro sign etc\n' \ u'

    EURO SIGN: ' + euro + u'\n'\ u'

    A TILDE: ' + atilde + u'\n' return doc def getXMLDoc(encoding): doc=u'\n' \ u''+euro+u''+atilde+u'' return doc def makeEncoding(encoding): doc=getHTMLDoc(encoding) codecs.open('euro-'+encoding+'.html','wb',encoding).write(doc) doc=getXMLDoc(encoding) codecs.open('euro-'+encoding+'.xml','wb',encoding).write(doc) for enc in ['utf-16','utf-8','utf-7','iso-8859-15','cp1252']: makeEncoding(enc) print 'Euro symbol in '+enc+' is: '+repr(euro.encode(enc))+' --> '+euro.encode(enc) print 'A-tilde in '+enc+' is: '+repr(atilde.encode(enc))+' --> '+atilde.encode(enc) From skip at pobox.com Mon Mar 4 15:32:12 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 4 Mar 2002 14:32:12 -0600 Subject: OT - file permission checks on Windows In-Reply-To: References: Message-ID: <15491.55756.317544.534681@beluga.mojam.com> >> Is the permission model there even remotely similar to what I'm used >> to on Unix systems? Thomas> No, I don't think so. I was afraid of that. >> I poked around posixmodule.c, but it makes next to no use of uids and >> gids. As far as I can tell, Windows doesn't know about uid_t or >> gid_t, though it has a struct _stat type whose st_uid and st_gid >> fields are shorts, so I can work around the missing types. Thomas> st_uid and st_gid are always set zo zero under Win NT: Thomas> http://msdn.microsoft.com/library/en-us/vclib/html/_crt__stat.2c_._wstat.2c_._stati64.2c_._wstati64.asp Thanks for the pointer. This takes me someplace weird in the msdn website, most likely because I'm using Opera instead of MSIE. I'll have to fiddle with that a bit I think. Thomas> Are you maybe looking for the _access function? Thomas> http://msdn.microsoft.com/library/en-us/vclib/html/_crt__access.2c_._waccess.asp Perhaps. On Unix, definitely not. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From jrchaff at mcn.net Wed Mar 13 13:37:00 2002 From: jrchaff at mcn.net (jrc) Date: Wed, 13 Mar 2002 18:37:00 GMT Subject: Why Don't Scripts Run ? Message-ID: <3C8F9C59.F9408D47@mcn.net> Hi - I'm a reasonably experienced programmer. I work in Windows (ME). Thinking to give Python a try, I downloaded v22 and installed. At first, it looks good, but then, I discover it seems impossible to get any scripts to run in the command prompt, using any available documentation whatever. I even have Chris Fehily's book - essentially none of his examples work with scripts from command prompt; yet this is a 2002 book . (?!!) I do have the path set (and yes, rebooted, etc) - I checked it. It includes both the installation directory and the working directory. I started the cmd line prompt using the provided icon, and also via a Dos Prompt (again, with proper path set), followed by 'python'. The interpreter starts up just fine and works ( >>> 2 + 2 -> 4 , etc). But, with a script in the current directory (on the path too), a command, 'python script.py' completely fails (syntax error). This is the only way I know - following the Fehily book and the sparse comments in Python documentation - to execute scripts from the cmd line. If v 22 is somehow different, it would be very nice to point out to (potential) users. I've also tried every permutation of this procedure that I can reasonably imagine - with the same result. The only way I am able to get scripts to run (without which python is just a toy) is to use 'Idle', load the file via "File Open", then in THAT window, execute it, (!!), then back in the cmd line I have to issue yet another command to get the prompt back. This is essentially an unusably awkward procedure, for my use. So unless there is some reasonably convenient way to run scripts, python has no value to me at all. I would very much appreciate someone telling me which un- documented point(s) I am missing. Thanks, jrc From sholden at holdenweb.com Sun Mar 31 08:59:44 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 31 Mar 2002 08:59:44 -0500 Subject: string copying References: Message-ID: "Tim Peters" wrote ... > [Bengt Richter, on consuming vast quantities of memory quickly] > > s = 'x'*2**30 would be a quick gig too. But it made me think > > maybe one could write a sort of memory test (to exercise the > > available python space, anyway). Does python run out of memory > > gracefully? > > Very. You should get a clean MemoryError exception if you try. > > >>> 'x' * 2**30 > Traceback (most recent call last): > File "", line 1, in ? > MemoryError > >>> > My laptop upgrade clearly takes my platform beyond the timbot conceptual limit: it took about three minutes to start printing (I'm not thinking of letting it finish) with no error message in sight. the-point-is-still-valid-though-ly y'rs - steve From aahz at pythoncraft.com Tue Mar 26 20:09:31 2002 From: aahz at pythoncraft.com (Aahz) Date: 26 Mar 2002 20:09:31 -0500 Subject: Logging tracebacks to MySQL (was RE: hang in urllib.read()?) References: Message-ID: In article , Nick Arnett wrote: > >At this point, my robot is being nicely stable, but now I'm starting to >think that the real problem was time-outs, but I sure don't see why they >would last for hours. Aahz's suggestion of using timeoutsocket was right on >the mark. I am definitely seeing timeouts now, which are recovering nicely >by simply starting over with urlopen. Sockets are simply unreliable over any kind of external network. I've learned to use timeout code even for internal networks, just to be safe. >And after a fairly hideous time figuring out how to come up with an >appropriate error message and escape it for MySQL, timeouts are now even >being logged into a table. If anyone has an example of getting a full >traceback into a MySQL field, I'd be grateful to see it. What seemingly >should work seems to somehow recurse a few times, so that backslashes and >such get repeatedly escaped... at least in all the ways I could see to use >the traceback module. I gave up and up and I'm using sys.exc_info()[:2] >instead, which is probably sufficient information. You should only need to escape "'" if you're using straight SQL calls. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From joekm at earthlink.net Thu Mar 28 22:58:25 2002 From: joekm at earthlink.net (Joe) Date: Fri, 29 Mar 2002 03:58:25 GMT Subject: trouble getting pdb to work within Xemacs on windows 98 Message-ID: <3CA3E656.80403@earthlink.net> tried both the cygwin and native installs of xemacs. Did a static link for the cygwin install (ln -s /lib/python2.2/pdb.py /usr/local/bin/pdb) and wrote the recommended batch file for the windows install and put it in my path (C:\py22 in this case). Regardless of what I do, Win98 either hangs or crashes outright whenever I try to run pdb within Xemace (meta-x pdb). It's a laptop if that means anything....am I doing something wrong? From mnations at airmail.net Mon Mar 18 11:58:11 2002 From: mnations at airmail.net (Marc) Date: 18 Mar 2002 08:58:11 -0800 Subject: PIL Headaches: Advice Needed References: <4378fa6f.0203161652.7f28e23b@posting.google.com> <7652139e.0203170045.3c143995@posting.google.com> Message-ID: <4378fa6f.0203180858.4ad5f8b3@posting.google.com> This is the main error that I am seeing: ... File "play2_copy.py", line 90, in createWidgets im = "Image.open("cs.bmp") File "C:\Python22\lib\Image.py", line 960 in open IOError: cannot identify image file I have tried this with .gif, .jpg, and a couple of others and none of the file types are recognized. Here is the code where the image is imported: canvas = Canvas(goFrame, width=400, height=400) im = Image.open("cs.bmp") im.show() canvas.pack() What am I doing wrong? Thanks, Marc From shalehperry at attbi.com Fri Mar 1 17:33:22 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 01 Mar 2002 14:33:22 -0800 (PST) Subject: Code Review!! (or bash!) In-Reply-To: <19650FF08A99D511B19E00B0D0F06323060B2B@SRM201002> Message-ID: > > Before I let it out into the wild, I'd like to know what you > all people think about this toy. I know, there's xml.dom stuff, > and xml.sax stuff, but I can't seem to wrap my brain around it, > so I just started writing this out of curiosity, and now it's > starting to feel useful. But "useful" is so subjective, isn't it. > >:-) > > Mind you, it only works for 8-bit chars, so there's a limitation. > Verbose. Nice. The re.compile() where you buld the 'amp|lt|gt' string took me a moment to parse, but other than that it reads pretty well. One possible comment for future development. The ENTITIES list must always begin with ('&', '&') or the encode_entities() function may hiccup because it will encode say 'copy sign' to '©' and then turn that into '&copy;'. From lac at strakt.com Thu Mar 28 15:24:17 2002 From: lac at strakt.com (Laura Creighton) Date: Thu, 28 Mar 2002 21:24:17 +0100 Subject: Another stab at a "switch/case" construct (for Python 3000): In-Reply-To: Message from Jeff Shannon of "Thu, 28 Mar 2002 11:19:18 PST." Message-ID: <200203282024.g2SKOHrq016811@ratthing-b246.strakt.com> I don't like the overloading of continue. I'd go for a new keyword, fallsthrough myself. I fear that this proposal will lead to people never bothering to learn about dictionary-based dispatching, which will be sad. On the other hand, I have been building parse trees lately, where some sort of case statement would be useful. Was there some sort of ruling on PEP 275? I'm not sure we should be starting a new switch statement PEP until we have found out why the last one was rejected. On the fence, Laura From peter at engcorp.com Mon Mar 11 23:51:35 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 11 Mar 2002 23:51:35 -0500 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8C82D3.CA4220CA@earthlink.net> <3C8CAA83.9EBBC03E@engcorp.com> <924j8.19297$N7.4387774@ruti.visi.com> Message-ID: <3C8D8957.9A0BB9C0@engcorp.com> Grant Edwards wrote: > > In article <3C8CAA83.9EBBC03E at engcorp.com>, Peter Hansen wrote: > > Tim Hammerquist wrote: > > > >> Didn't you know? Microsoft invented Open Source! ;) > > > > No, that was Al Gore! > > Ya know, I've actually read the transcript of that interview. > He never claimed to have invented the Internet, only to have > been responsible for funding it. I hadn't read it either, but I remembered the words quoted as "invented the information superhighway". Well, searching on Google (of course :-) using search pattern: http://www.google.ca/search?q=%22al+gore%22+information+superhighway+invented turned up this: http://www.wired.com/news/politics/0,1283,39301,00.html which discusses how the use of the word "invented" was, well, invented, but that Al really did say he "took the initiative in creating the Internet". Furthermore, in a speech he gave in 1994 (see http://artcontext.com/cal/97/superhig.txt), he claimed: "Incidentally, when I first coined the phrase "information superhighway" 15 years ago, I was not prepared for some of the unusual images it would ultimately bring into our language. " Fascinating, really. (Notes: I'm Canadian, but I like Al anyway, and the articles quoted indicated that he really did play a significant role in bringing into the world much of the infrastructure we are using right now.) -Peter From fp at contact.de Wed Mar 27 05:39:27 2002 From: fp at contact.de (Frank Patz) Date: Wed, 27 Mar 2002 11:39:27 +0100 Subject: RELEASED: Python 2.2.1c2 In-Reply-To: Message-ID: > [...] > Note for AIX users: there are still problems with AIX in this release, > and there has not been time to repair them without fear of breaking > platforms that currently work. Hopefully by the time of the release > of 2.2.1 final we will be able to provide a recipe that allows AIX > users to build and run Python. > [...] Hmm, can someone shed more light on this issue? - frank -- fp at contact dot de From grante at visi.com Sun Mar 10 15:01:02 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 20:01:02 GMT Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: In article , phil hunt wrote: > On Sat, 09 Mar 2002 22:57:42 -0500, Peter Hansen wrote: >> >>I agree with much of what you say, especially the "consider skipping >>C++ and just learn C part", but _what_ pragmatic point of view is it >>that has one learning Perl, Java, or C++ when one uses Python already? >>Not dissing those languages, but when would you really need them? > > I can think of several tasks for which C++ is better than Python, > e.g. writing operating systems, network stacks, windowing systems, > run-time interpreters, crypto algorithms, etc. And I can think of several languages which are better than C++ for those tasks: Modula-2, Modula-3, Ada, Bliss-32... ;) -- Grant Edwards grante Yow! .. I want to perform at cranial activities with visi.com Tuesday Weld!! From geoff at gerrietts.net Wed Mar 6 13:51:30 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Wed, 6 Mar 2002 10:51:30 -0800 Subject: Why KeyError ??? In-Reply-To: <7dee885c.0203061030.5626d5e@posting.google.com> References: <7dee885c.0203051843.36efa5c2@posting.google.com> <7xvgcabcti.fsf@ruckus.brouhaha.com> <7dee885c.0203061030.5626d5e@posting.google.com> Message-ID: <20020306185130.GB20722@isis.gerrietts.net> Quoting Ozren Lasic (ozren_lasic at yahoo.com): > Sorry, but I didn't get it. > Maybe you can explain me on another example?? > This is all very interesting. Consider this: >>> a = '\xe7\xd0\x9f\x86\xa7' >>> b = unicode(a,'cp1250') >>> c = "abcde" >>> d = unicode(c,'cp1250') >>> a.__hash__() -1420316064 >>> b.__hash__() 2044161023 >>> c.__hash__() -1332677140 >>> d.__hash__() -1332677140 >>> a == b Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) The only hypothesis I can put forward here is that the Unicode code is trying to maintain a sense of the actual identity of the referenced glyphs. I'm not familiar with the encodings that are under discussion here, but I'm assuming that in codepage 1250, as in the default C locale, the characters "a" - "e" refer to the same glyphs. On the other hand, I'm guessing that in codepage 1250, the glyphs referenced by "\xe7\xd0\x9f\x86\xa7" are different from the glyphs referenced by those same bytes in the default encoding. In fact, the traceback at the end there suggests that those glyphs have NO meaning in the default encoding. Consequently, the underlying unicode representation -- 2 bytes per glyph? I'm not sure -- tracks the two strings differently. When you go to hash them, the difference is exposed, but when you're looking at them, they don't look all that different. I'm not sure why the key on the dictionary would report "abcde" instead of u"abdcde"; that's pretty baroque. --G. -- Geoff Gerrietts "I am always doing that which I can not do, in order that I may learn how to do it." http://www.gerrietts.net --Pablo Picasso From grante at visi.com Sat Mar 16 00:31:38 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 16 Mar 2002 05:31:38 GMT Subject: socket References: Message-ID: In article , Billy Ng wrote: > Nothing evil here. I have 2 reasons why I would do this program. Firs, it > is my TCP/IP concept class's project. Basically, I want to try what the > book tells in to code, but I notice it does not work the way it says in so > many commercial SMTP servers. What?! Things in the real world don't work they way they describe them in networking classes?!?! ;) > Second, I have been unemployed for about 4 months. My > friend's company needs a program to verify the users who > registered to their service. They found out many registered > users were using fake addresses. The only way that will actually work is to send an e-mail with some sort of unique ID in it. Require that the user reply to the message. No competent ISP will allow outsiders to check whether an arbitrary e-mail address is valid. > I just want to try this program to see if I will get a job > there. That's all! I really do appreciate if you would > provide any info for me to complete this project. Good luck, but it's going to be an up hill battle. -- Grant Edwards grante Yow! Is this BOISE?? at visi.com From tim.one at comcast.net Thu Mar 14 22:37:54 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 14 Mar 2002 22:37:54 -0500 Subject: YANRQ (yet another regex question) In-Reply-To: <4f5k8.435$zT5.13755@news.itd.umich.edu> Message-ID: >> Depending on the definition of easy, this is the alternative I would >> use. >> >> r = re.compile(r'(?P(?=.{7}) *foo *)') >> >> Of course, your milage may wary. [Michael George Lerner] > Doesn't quite work for me: > > >>> import re > >>> r = re.compile(r'(?P(?=.{7}) *foo *)') > >>> s = r.match('foo ').groupdict()['foo'] > >>> s > 'foo ' > >>> len(s) > 12 > >>> > > and I only want to match things that are seven characters long here. If matches, e.g. 'foobarx' too. > It does, however, match all of the correct seven character strings, > and I'll have to remember that trick in the future. Thanks! If you can settle for a regexp that matches *at least* the correct strings, '' would work too . From bokr at oz.net Tue Mar 5 02:35:58 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Mar 2002 07:35:58 GMT Subject: Status of PEP's? References: <7xwuwrofhk.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 04 Mar 2002 19:59:03 -0800, David Eppstein wrote: >In article <7xwuwrofhk.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > >> Usually the term "natural numbers" don't include zero. >> http://mathworld.wolfram.com/NaturalNumber.html > >I think "usually" is an exaggeration. For instance, a better authority >than Weisstein, Ebbinghaus et al's _Numbers_ (Springer Graduate Texts in >Mathematics 123, 1991, p. 14) disagrees. Natural numbers (1, 2, 3 ...) were the only numbers known to the Greeks until Diophantus thought of fractions, about 275 (though Egyptians apparently had thought of fractions with one as the numerator before 1700 B.C.). The Greeks had no symbol for zero. It didn't appear until the fifth century sometime, when Hindus introduced it. By the twelfth century they had negative integers, but Europeans didn't catch up to that unitl the sixteenth century and Descartes. ... all this (paraphrased) according to Harriet Griffin's "Elementary Theory of Numbers" (one of McGraw-Hill's International Series in Pure and Applied Mathematics (c) 1954, p. 1) (It was a textbook used 1956 at MIT for freshmen, FWIW ;-) FWIW again, Wordnet agrees also: [23:32] C:\pywk\telt>wn "natural number" -over Overview of noun natural_number The noun natural number has 1 sense (no senses from tagged texts) 1. natural number -- (the number 1 and any other number obtained by adding 1 to it repeatedly) Regards, Bengt Richter From newsfroups at jerf.org Tue Mar 26 23:28:56 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Wed, 27 Mar 2002 04:28:56 GMT Subject: Streaming XML-RPC? References: <3C9F51EE.5000203@jerf.org> Message-ID: <3CA14A4A.3030702@jerf.org> Magnus Lie Hetland wrote: > In article <3C9F51EE.5000203 at jerf.org>, Jeremy Bowers wrote: >>This is in stark contrast to HTTP. HTTP thinks you're nuts. HTTP will >>fight you tooth and nail. HTTP is old, and hoary, and set in her ways. >>And XML-RPC isn't exactly ecstatic about being streamed, either. > Well, jabber-rpc is just XML-RPC in a Jabber stream... :) Yes, but it goes out in discrete chunks. Watch a jabber-rpc call, and and XML-RPC call, go by on the wire, and they'll look the same modulo some header. Try to trickle XML-RPC calls over either system and it'll be ugly. (Uglier in Jabber, though, because you'll be consuming the entire Jabber connection while you're trying that.) If you have control of both the server and the client, you may be able to set up an ugly fast RPC server. Just have it look for and while reading a TCP stream, and break the stream up that way. (Watch out to make sure that the server always responds in order, or tag them with ids.) From claird at starbase.neosoft.com Tue Mar 19 16:57:29 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 19 Mar 2002 15:57:29 -0600 Subject: Java and Python References: Message-ID: In article , Steven Majewski wrote: > > >On Mon, 18 Mar 2002, Ahmed Moustafa wrote: . . . >> I understand Microsystems supports Java. Who does play the same role for >> Python? > >Nobody supports "Java", although often someone supports particular >implementations of Java. ( Sun supports J2SE SDK, Apple supports >MRJ, and there are open source compiler implementations like IBM's >Jikes. ) > >-- Steve Majewski > > > > I'm still looking for a way to get this point across: the answer to many questions is, "There's no such thing." No one plays the role for Python that Sun plays for Java. It's OK to ask; don't always expect simple answers, though. Or perhaps people mean something by "same" that I don't understand. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From dalke at dalkescientific.com Tue Mar 12 02:59:01 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 12 Mar 2002 00:59:01 -0700 Subject: NormalDate 1.2 released References: Message-ID: John Machin: >To make some sense of reported historical dates, one needs to guess >based on the location, origin and mind-set of the reporter. I always figured time code should use the parameters "latitude", "longitude", and "attitude" (which rhymes better than religion :) Andrew dalke at dalkescientific.com From cce at clarkevans.com Sun Mar 17 11:37:23 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Sun, 17 Mar 2002 11:37:23 -0500 Subject: tty interface to a hashtable for script configuration? Message-ID: <20020317113723.A18074@doublegemini.com> Hello. I'm looking for a small module that would take a hashtable for input, and allow the user to change the hashtable entries (or after N seconds return with the hashtable unchanged if no one is at the console). Of course, this could get very featureful, but those are the base requirements. I was wondering if anything like this is out there as a module. I'm sure it has been written 100s of times -- so rather than roll my own, I was thinking that someone may have done this already and is willing to share. If it is not packaged and someone is willing to share, then I'll package it. Best, Clark From sjmachin at lexicon.net Sun Mar 17 16:13:39 2002 From: sjmachin at lexicon.net (John Machin) Date: 17 Mar 2002 13:13:39 -0800 Subject: Pythonic Porter stemmers (Was: Re: Word frequencies -- Python or Perl for performance?) References: Message-ID: "Van Gale" wrote in message news:... > W.B. Frakes and R. Baeza-Yates. 1992. "Information Retrieval: Data > Structures and Algorithms," Prentice-Hall, describes the Porter algorithm as > well as a few other stemming algorithms. The reference for the algorithm > is: > > Porter, M. F. 1980. "An Algorithm for Suffix Stripping." Program, 14(3), > 130-37. > Martin Porter has a home page for his stemming algorithm. http://www.tartarus.org/~martin/PorterStemmer/index.html Read all the way through to the last line. > Frakes mentions nothing about a patent on the Porter algorithm, and I'd be > surprised if there were since it was pretty rare back in the "good old > days". Check out Porter's personal home-page. Given the comment about his family buying him a comb after he first put his photo on the web, I get the impression not of patent-royalty-rich but of archtypal-English-academic :-) > > I worked on a huge indexing project for a legal publisher, and we developed > our own stemming algorithm. It was much simpler than Porter, basically > being the most obvious conflations (like remove "s" and "ies") which covered > the vast majority of English words, and then a list of "exceptions". Of > course we had the advantage of 50+ editorial staff capable of proofreading > the index finding new exceptions, but I still think that's a better way to > go than trying to stem completely by algorithm. As hard as the Porter > algorithm tries it still make a *lot* of mistakes. And of course once you had an exception dictionary, for a performance boost you'd consider dumping into it the 10^n most frequent words and their "correct" stems whether or not the stemming algorithm gave the "correct" result or not -- wouldn't you? From cliechti at gmx.net Sat Mar 2 10:11:02 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Mar 2002 16:11:02 +0100 Subject: Possible to fake object type? References: <3c80e76b@nntp.server.uni-frankfurt.de> Message-ID: Michael 'Mickey' Lauer wrote in news:3c80e76b at nntp.server.uni-frankfurt.de: > So: Is it possible to fake the type of a class or > is it possible to magically override the method call "bouncing" > to the base class ? you can allways call the methods of on e of the supperclasses by using: Baseclass.method(self, args, ...) it's the same you do in __init__ to initilaize base classes: class Dockable(gtk.HandleBox): def __init__(self): gtk.HandleBox.__init__(self) def dosomething(self, arg): print "calling dosomething...", result = gtk.HandleBox.dosomething(self, arg) print "result = %r" % result return result ... -- Chris From cce at clarkevans.com Sat Mar 9 17:42:08 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Sat, 9 Mar 2002 17:42:08 -0500 Subject: python wrapper for FreeBSD fdisk, disklabel, etc? Message-ID: <20020309174208.A26209@doublegemini.com> I was wondering if someone has written a wrapper for FreeBSD's "fdisk", "disklabel", "newfs" and "mount". If not, any suggestions/hints along the lines of using os.system/os.popen would be fantastic. Thanks! Clark From ray at rays-web.com Sun Mar 3 18:29:23 2002 From: ray at rays-web.com (Ray Smith) Date: 3 Mar 2002 15:29:23 -0800 Subject: Newbie: import works ok if in base directory but fails in other directories Message-ID: <5654fff9.0203031529.40914d77@posting.google.com> Hi, I'm reading "how to think like a computer scientist" and tried one of the examples which uses the "pickle" import library. This is the program: ------------- # picking example import pickle f = open("pickle.dat", "w") pickle.dump(12.3, f) pickle.dump([1,2,3], f) f.close() ------------- When it is saved as and run in the directory "c:\work\python\pick1.py" it returns the following output: ----------- Traceback (most recent call last): File "pick1.py", line 2, in ? import pickle File "c:\dev\python22\lib\pickle.py", line 6, in ? Classes: AttributeError: 'module' object has no attribute 'dump' ------------- If I save the program to my base Python directory (in my case c:\dev\python22\) and run it everything works ok. What do I need to do to get it to run in other directories? Any help is much appreciated. Thanks, Ray Smith From mzou at bu.edu Mon Mar 25 01:42:28 2002 From: mzou at bu.edu (ricky) Date: Mon, 25 Mar 2002 01:42:28 -0500 Subject: files and reading from them References: Message-ID: not sure what you mean but check out the "shelve" module "Avi Homes" wrote in message news:auzn8.71680$Vl.2635455 at typhoon.austin.rr.com... > I am writing a dictionary to a file, like so > f.write(str(Info)) > > and what it is writing to the file is the following.. > {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} > > and if i write in two things, i get.. > {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} > {'IPrice': '2', 'IName': 'notworking, 'IDesc': 'annoying'} > > What i would like to do is pull a readline or somesuch.. and have it take in > the whole thing, and then just let me assign that to a empty name, and turn > it into a new dictionary.. like say > file.seek(1) > //thats how i'd go to the first place in the file correct? > X=file.readline() > > and now i can say print X['IName'] ... and its turned into a dictionary.. i > am most likely going about this *all* wrong. > > > > From claird at starbase.neosoft.com Thu Mar 21 10:05:58 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 21 Mar 2002 09:05:58 -0600 Subject: Java and Python References: <3C996234.9090506@verizon.net> Message-ID: <852630CB444A0E88.1C47E73805633E2D.6D8C67A72D42A034@lp.airnews.net> In article , Gerhard =?iso-8859-15?Q?H=E4ring?= wrote: >* Rich Salz [2002-03-21 04:31 +0000]: >> >> >> Cameron Laird wrote: >> >I'm still looking for a way to get this point across: the >> >answer to many questions is, "There's no such thing." No >> >one plays the role for Python that Sun plays for Java. >> >> Hmm.. Both provide a reference implementation, both provide a community >> process for suggesting improvements (but still retain the right to do >> what they think best)... what's missing? > >Both just are 'infrastructure' for the company behind them, they don't >make money directly from it. . . . Rich's question is a reasonable one. I recognize that I'm a bit touchy on the subject. My experience is that, when people start asking this question, they generally have more interest in accusing Python of deficiencies than in sound engineering analysis. So, for example, I've heard that Python isn't as serious as Java because it's not possible to hire "Zope-certified Python Engineers". Sun does that for Java, Zope doesn't for Python, therefore Python isn't as trustworthy as Java. It feels to me like a species of colonialism to require Python (for example) to do and be everything that Java (for example) is, but also better. I've simply never had a conversation that started that way conclude in a productive way. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From bokr at oz.net Sun Mar 17 22:47:22 2002 From: bokr at oz.net (Bengt Richter) Date: 18 Mar 2002 03:47:22 GMT Subject: how to print class names, not references References: <3C9544B5.47CD0918@pop.ntlworld.com> Message-ID: On Mon, 18 Mar 2002 01:36:53 +0000, "a.clarke11" wrote: >Hi, >I wrote a function of x, where later in the program x is substituted by >class names. In the function, print x is used, but this returns ><__main__.Player instance at 0x38b1ce90> rather than the plain old class >name that I wanted. >How can I print the name instead? >Thanks for your help, Pythoneers... > >>> class CwithClassName: ... pass ... >>> c = CwithClassName() >>> c <__main__.CwithClassName instance at 0x0084AF40> >>> Calias = CwithClassName >>> calias = c >>> Calias >>> calias <__main__.CwithClassName instance at 0x0084AF40> >>> Calias.__name__ 'CwithClassName' >>> calias.__name__ Traceback (most recent call last): File "", line 1, in ? AttributeError: CwithClassName instance has no attribute '__name__' >>> calias.__class__.__name__ 'CwithClassName' Does any of that help? Regards, Bengt Richter From michael.neuroth at freenet.de Thu Mar 7 19:17:31 2002 From: michael.neuroth at freenet.de (Michael Neuroth) Date: Fri, 08 Mar 2002 01:17:31 +0100 Subject: undefined symbols when linking Python into a shared library References: <3C8540B5.E133D407@freenet.de> Message-ID: <3C88031B.8A0FB866@freenet.de> "Martin v. Loewis" writes: > On Linux, use "nm -D foo.so" to see the symbols exported by foo.so. Thank you for the tip, now I can see, that the 'missing symbol' is exported from the shared library: 000a7bac D _Py_NoneStruct Is there any difference for exported (data) symbols, when loading a shared library with dlopen() instead of linking it 'statically' while creating the program file? > > What is the magic option to solve that (linker?) problem? > > You'll need to understand the problem first before trying to find a > solution. I, for one, can only guess what is going on: most likely, > your shared library really does not provide the symbol missing in > _tkinter.so; this is probably not surprising, since the linker, when > creating the library, had no clue that the symbol might be needed. > > In any case, it is a bad idea to incorporate libpython.a object files > into a shared library, as this is non-PIC code. That is true of course. Is there any possibility to create a shared libraray for Python: libpython.so instead of libpython.a? I have not found any option in the ./configure script. Is there any reason against shared libraries? Regards, Michael. From bass at slinkp.com Thu Mar 7 17:09:31 2002 From: bass at slinkp.com (Paul Winkler) Date: 7 Mar 2002 14:09:31 -0800 Subject: [OT] range() for unix shell Message-ID: <2adab837.0203071409.76588265@posting.google.com> I've been taking some classes on various comp. subjects, including (currently) unix/linux. We're currently doing shell scripting, which I've done before but always kinda disliked, preferring our favorite snaky language. Today, struck by the similarity between sh and python's for loops, and facing an example which required us to generate a range of numbers from boundary parameters, I wrote a sh range function. It works just like python's range() function (allowing for syntactic differences). Of course now I'm expecting someone to leap forward and tell me that some analogous feature is already built in to the shell, but I haven't seen it yet. Hoping it's useful to some of the unix/python people out there, I'm posting my function below. compare to familiar python examples: >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(2, 10) [2, 3, 4, 5, 6, 7, 8, 9] >>> range(2, 10, 2) [2, 4, 6, 8] >>> range(10, -1) [] >>> range(5, -5, -3) [5, 2, -1, -4] >>> for i in range(4): print i ... 0 1 2 3 here's a pdksh session (also tested in bash): /home/train18$ range 10 0 1 2 3 4 5 6 7 8 9 /home/train18$ range 2 10 2 3 4 5 6 7 8 9 /home/train18$ range 2 10 2 2 4 6 8 /home/train18$ range 10 -1 /home/train18$ range 5 -5 -3 5 2 -1 -4 /home/train18$ for i in `range 4`; do echo $i; done 0 1 2 3 shell-is-weird-but-handy-ly-y'rs, Paul Winkler # FUNCTION BEGINS HERE range () { # written 2002 by Paul M. Winkler, Brooklyn, NY. # I hereby place the copyright to this program # in the public domain. # This is a translation of python's # range function into shell. Tested with # bash and pdksh. Doesn't work in ash (no "let"). # Instead of returning an array (like python), # it returns a string that can be used as a sequence. # Example: for i in `range 10`; do echo $i; done # Defaults: let start=0 let step=1 case $# in 1) # start and step are default. let stop="$1" ;; 2) # Implicit 1 step. let start="$1" let stop="$2" ;; 3) # no default used let start="$1" let stop="$2" let step="$3" ;; *) cat << END_USAGE Usage: $0 [start] stop [step] Yields a sequence of integers N such that start <= N < stop. If start is not given, it is 0 by default. Successive values increase by step. If step is not given, it is 1 by default. END_USAGE return 1 ;; esac # NOTE: all following tests have variables in quotes. # This is to avoid cryptic failures if $IFS happens # to be set to "-" if [ "$step" -eq 0 ] then echo "Invalid step size 0. Must be a" echo "positive or negative integer." return 1 fi # Different comparisons apply if we're counting up or down. if [ "$step" -ge 1 ] then op='-lt' else op='-gt' fi result="" let thisnum=$start while [ "$thisnum" "$op" "$stop" ] do result="$result $thisnum" let thisnum=thisnum+step done echo "$result" } # END From stephen at xemacs.org Wed Mar 13 23:52:25 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 14 Mar 2002 13:52:25 +0900 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> <3C8F1D74.10802@mxm.dk> Message-ID: <87r8mnsqd2.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Cliff" == Cliff Wells writes: >> Not everybody is as knowledgable as Mark, Even though we work >> on the superior Windows platform ;-) Cliff> And quite possibly because not many people using the Cliff> superior Windows platform have a C compiler Cliff> available to them. Probably due to thoughtfulness on Cliff> Microsoft's part ;) Yeah, if there's a superior Windows platform around, they sure seem to have forgotten to put it on the market. Beta test still? -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From phr-n2002a at nightsong.com Tue Mar 26 19:29:01 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 26 Mar 2002 16:29:01 -0800 Subject: Python vs. C/C++/Java: quantitative data ? References: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> <3CA10CA8.DFF48898@gmx.de> Message-ID: <7x663iam5u.fsf@ruckus.brouhaha.com> Ingo Linkweiler writes: > I?m writing a diploma paper on rapid prototyping and python at education. > I am interested in your experiences with python, too, including the time you > needed to learn python. > > - Do YOU think, it is more easy to learn python than perl, java or C++ or > ..... ? Perl may be easiest to do some simple things, but gets horribly complicated as you try to do harder things. Python is easier than java and java is easier than C++. > - What do you think about the syntax of Python? Is it easy to use, or do you > have any problems with it? Mostly easy. There's some surprises like z=[[0,0,0]]*3 giving you what looks like a 3x3 matrix of zeros until you try changing an element. I personally find it inconvenient that there's no conditional expressons or assignment expressions, but that's a subject of endless debate here. > - Is here anybody who learned Python as first language? Not me :) > - Where do you see disadvantages of Python? Slow execution, spotty runtime library, cumbersome C API, lack of good debugging environment in standard distribution. From mhammond at skippinet.com.au Tue Mar 19 22:03:49 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 20 Mar 2002 03:03:49 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: <3C97FC23.1030702@skippinet.com.au> Neil Hodgson wrote: > Martin v. Loewis: > > >>Subclassing may not be the right solution - perhaps it is better to >>admit that ntmodule.c really should be different from >>posixmodule.c. What do you think? > > > There is also a lot that should be shared, such as the docstrings, much > of the argument parsing as well as many of the posix calls. Splitting may > lead to more breakage when common patches aren't applied to both. How about just using #include files here then? > It needs a way to specify the base generic > posix case cleanly but then to allow platforms to specialise or remove those > functions needing different implementations or which can not be implemented. > In my own C++ work, I normally do this through subclassing. It doesn't have to be *too* cleanly :) Having little helper functions isn't too bad and could probably work - ie, think "pragmatically" more than "cleanly" :) Mark. From phr-n2002a at nightsong.com Tue Mar 19 17:16:26 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 19 Mar 2002 14:16:26 -0800 Subject: Dictionary Comprehension References: <3mbe9usoufc2f5ppjmk7lh6ks71pgb45f9@4ax.com> Message-ID: <7xsn6w9pad.fsf@ruckus.brouhaha.com> Michael Hudson writes: > The "Parade of the PEPs" says: > > PEP 274 - Dict Comprehensions - Warsaw > > If we were to adopt dict comprehensions, this PEP says everything > that needs to be said. But I don't even want to think about this > for Python 2.3; I think it's way too minor a feature. > > This would be a lot easier to adopt if there was a working > implementation in patch form. > > Sometimes it would be nice if things like this could be defined > using hygienic macros or some other kind of preprocessor or > whatever, and imported from a module, rather than requiring major > hacking in the parser, the bytecode compiler, and the virtual > machine. I didn't get around to replying when "Parade of the PEPs" was posted. The Parade of PEPs response surprised me a little. It seems obvious to me that dict comprehensions should be in Python if list comprehensions are, even if no one uses them, on general considerations of symmetry and the principle of least astonishment (i.e. I wondered why they weren't both added at the same time). There are times when it's right to use more abstract grounds than "importance" to decide to include something. It's unlikely that anyone has ever used the numeric literal 901472937 in any Python program, but if for some reason Python could recognize every numeric literal except for that one, we'd call it a bug even if the restriction was described in Python's documentation. I hope no one would say Python needn't recognize 901472937 because hardly anyone wants to specify that particular integer in a program and you can always say 901472936+1 insead. The idea of implementing dict comprehensions using macros is interesting; maybe list comprehensions can be re-done the same way. Also, if adding dict comprehensions really require "major hacking in the parser, the bytecode compiler, and the virtual machine", then IMO a code cleanup is needed that's much larger in scope than adding one feature. Certainly no change to the VM should be needed at all, since the dict comprehension is equivalent to a for loop, and the compiler can generate the exact same code as the for loop would have. The parser and compiler would need a patch, but I'd hope it wouldn't be "major hacking". That said, on pragmatic grounds I don't see any terrible urgency to the issue, and if dict comprehensions don't make it into 2.3 it's no big deal. I do hope they get added sooner or later. From gerhard at bigfoot.de Fri Mar 22 05:07:18 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 22 Mar 2002 10:07:18 GMT Subject: CGI, etc. References: Message-ID: In article , dsavitsk wrote: > "Sheila King" wrote in message >> http://www.python.org/topics/web/ > > btw, the instructions linked to here for doing CGI on windows under iis are > out of date (only covering 9*/NT). For win2k (server and professional) see > http://www.e-coli.net/mag.shtml (or http://www.e-coli.net/pyiis.html and > http://www.e-coli.net/pyiis_server.html specifically) I'd suggest to inform webmaster at python.org. Gerhard From david.abrahams at rcn.com Sun Mar 31 15:53:23 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sun, 31 Mar 2002 15:53:23 -0500 Subject: PEP 285: Adding a bool type References: <3CA751EF.10F25F2D@ndh.net> <3CA75ECC.389A0186@alcyone.com> <2NJp8.140405$Yv2.43077@rwcrnsc54> Message-ID: "Emile van Sebille" wrote in message news:2NJp8.140405$Yv2.43077 at rwcrnsc54... > Someone (Guido?) already mentioned that testing for true is redundant, > but doesn't : > if 2: > imply > if 2 == True: > which in turn then implies that: > True == 2 > is true? Not exactly. if x: would be the same as if bool(x): (which is the same way it works in C++, FWIW). -Dave From ken at ineffable.com Thu Mar 7 12:36:35 2002 From: ken at ineffable.com (Ken Causey) Date: 07 Mar 2002 11:36:35 -0600 Subject: Handling bad tags with SGMLParser In-Reply-To: References: Message-ID: <1015522595.442.24.camel@temp> On Thu, 2002-03-07 at 11:33, Sean 'Shaleh' Perry wrote: > > > > I'm inclined at the moment to report this situation as a bug. But I > > wanted to get some opinions as I'm neither an SGML expert nor fully > > confident of my understanding of the SGMLParser class. > > > > I agree this is a bug because the class name is SGMLParser yet it is concerning > itself with html tags. > I'm not sure I understand this comment. What tag do you mean? All of these are standard SGML tags as I understand it. Ken From gerhard at bigfoot.de Wed Mar 20 09:18:48 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-1?Q?H=F5ring?=) Date: 20 Mar 2002 14:18:48 GMT Subject: shared memory block References: <3C988A9F.51137D54@mathworks.fr> <3C988C67.2010008@bigfoot.de> <3C9893B2.53A8255F@mathworks.fr> Message-ID: In article <3C9893B2.53A8255F at mathworks.fr>, Boris Huart wrote: > Well I am using a real-time system and I only have a Python library to get > about 20 floats calculated on the platform. Then I have implemented a Java > applet which needs those data to interact via an External Aauthoring > Interface with a VRML plugin embedded in IE. My problem is how to make the > python script and the java applet communicate together. XML-RPC or a custom programmed protocol via sockets seems to be the way to go. If you're using Python 2.2, xml-rpc is part of the standard library, else it is available here: http://www.pythonware.com/products/xmlrpc/index.htm. This is a XML-RPC library for Java: http://xml.apache.org/xmlrpc/server.html I think you'll have to do some tricks to work around Java's security model to actually get an XML-RPC server running in your Java applet. I think you'll get the best answers for disabling/working around that for the MS JVM in a Microsoft Java newsgroup. Or maybe Google has some anwsers. The only thing I can tell you is that the signed applet way is a major PITA. Gerhard From peter at engcorp.com Fri Mar 15 21:57:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 15 Mar 2002 21:57:57 -0500 Subject: socket References: Message-ID: <3C92B4B5.ECA3DF43@engcorp.com> Billy Ng wrote: > "Grant Edwards" wrote: > > Billy Ng wrote: > > > I am trying to write a python program to verify the email > > > address. > > > > What you're trying to do is pointless. Whether it's evil or > > not, I don't know, but one is suspicious. > > Nothing evil here. I have 2 reasons why I would do this program. Firs, it > is my TCP/IP concept class's project. Basically, I want to try what the > book tells in to code, but I notice it does not work the way it says in so > many commercial SMTP servers. Second, I have been unemployed for about 4 > months. My friend's company needs a program to verify the users who > registered to their service. They found out many registered users were > using fake addresses. I didn't think it was anything evil... I just wanted to know the background because the answer is really always "it depends". In this case, and as you may learn from other answers (this has been discussed several times in the last year, as well, if you care to search the newsgroup a little), the *only* valid and effective way of confirming an email address is to actually send an email to the address and request a reply. I repeat, *all* other methods have various problems and do not, in general, work. They may work some of the time, but since they cannot be relied upon there is no point wasting time trying to use them. Send the email, and if you get a reply then it's a valid address. Alternatively, send the email and if you don't get a bounce, assume it's valid. Won't make much difference in this case, it seems. This is a parallel to doing exception handling in Python and similar languages. Don't check the parameters ahead of time, just try using them but be sure to catch the exceptions in case they don't work. -Peter From tony.claeys at pandora.be Sun Mar 10 11:12:42 2002 From: tony.claeys at pandora.be (tc) Date: Sun, 10 Mar 2002 16:12:42 GMT Subject: financial calculations Message-ID: Is there a python module for financial calculations ? Using floats would give me too much problems with rounding errors. Thanks in advance. From duncan at NOSPAMrcp.co.uk Fri Mar 22 09:24:09 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 22 Mar 2002 14:24:09 +0000 (UTC) Subject: Sorting distionary by value References: Message-ID: Artur Skura wrote in news:slrna9m5sc.ai9.arturs at aph.waw.pdi.net: > known = [] > times = 0 > output = {} > > for i in a: > if i not in known: As the 'known' list gets longer, the check for list membership gets slower. A much better way is to keep a dictionary of the words (which you already have) and check for dictionary membership: if not output.has_key(i): > for l in a: > if l == i: > times = times + 1 And this bit means that you loop through all your input again and again: once for every unique word. Better just to go once through the data and add 1 to the count each time. > known.append(i) > output[i] = times > times = 0 > > it seems it's slow not because of sorting... Try something like: for i in a: if output.has_key(i): output[i] += 1 else: output[i] = 1 Also put your code inside a function to shave a little bit more off the runtime. -- 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 jeff at ccvcorp.com Thu Mar 28 14:19:18 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 28 Mar 2002 11:19:18 -0800 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: <3CA36CB6.69D7A488@ccvcorp.com> Ken Peek wrote: > A clause can be forced to 'fall through' with the use of a > 'continue' statement, which jumps to the first statement in the > next match clause (because 'falling through' IS useful > sometimes.) I don't think I like this re-use of the 'continue' keyword -- it seems to me that the sense, in this context, is considerably different than the sense of its use in a loop. In a loop, it means "start over from the top", where here, it means "run this one next bit too, but not anything else". I'm not sure that falling through is a necessary idiom to accommodate. If the code that should be used for more than one case is significant enough to be worth adding a 'continue' to get to, then it most likely is a good candidate for extraction as a separate function that can be painlessly called from both cases. (My $0.02, anyhow.) Jeff Shannon Technician/Programmer Credit International From robin at jessikat.fsnet.co.uk Thu Mar 14 10:00:59 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 14 Mar 2002 15:00:59 +0000 Subject: PyProlog 0.2.0 - compiling under Windows References: <3d06fae9.0203140649.635d4b49@posting.google.com> Message-ID: <3PDcksArsLk8EweI@jessikat.demon.co.uk> In article <3d06fae9.0203140649.635d4b49 at posting.google.com>, jmdeschamps writes ..... >LINK : fatal error LNK1104: cannot open file "python21_d.lib" >Error executing link.exe. > >pyswipl.dll - 1 error(s), 0 warning(s) >********* .... you might want to consider turning off debug compilation. Then you should only need python21.lib which will be in the python/Libs area. Of course you need to configure MSVC++ to look for .libs in that directory. Alternatively I believe that the debug versions of python21 libs are available at www.python.org. -- Robin Becker From grey at despair.dmiyu.org Wed Mar 6 18:10:06 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 06 Mar 2002 23:10:06 -0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 14:23:02 -0800, David Eppstein wrote: > I realize that's a different purpose than most working Python > programmers, but anything that leads to greater readability and easy of > understanding should be helpful in that world too. I fail to see how it is is greader readability or understanding when the current method is both. It may not be the /common/ way people expect it to be seen. However, people expect ; { and } quite often as well. Thankfully Python is devoid of those cumbersome constructs. It should remain free of the difficult to read (and overloaded) for statement as well. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From eppstein at ics.uci.edu Fri Mar 1 20:08:46 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 17:08:46 -0800 Subject: Status of PEP's? References: Message-ID: In article , James_Althoff at i2.com wrote: > I agree as I just remembered another issue that came up concerning the > "for-relational" suggestion. Namely, that the "for-relational" syntax > doesn't handle step values for intervals. So even though there would be > new syntax, we would still need to use range/xrange in cases requiring a > step value not equal to 1 or -1. True, it doesn't handle step values, unless you count syntax like [2*x for start <= x < end]. Neither does PEP 276, of course. Nobody is proposing to eliminate range/xrange, I think. I will see if I can find some time to work on a PEP. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From maxm at mxm.dk Sun Mar 3 15:52:38 2002 From: maxm at mxm.dk (Max M) Date: Sun, 03 Mar 2002 20:52:38 +0000 Subject: new images from strings using PIL References: Message-ID: <3C828D16.9020201@mxm.dk> BL wrote: > pixels = "1 2 3 4 5 6" //test pixels > im = Image.fromstring("I", (2,1), pixels) //create a 3x2 image from pixels > These values are obviously wrong. Why isn't my 3x2 image being created with > the proper pixel intensities? I think that the function is just meant as a way to generate an image via a string, in lack of a better data format. So the string is not a string of pixel values (pun inteded) but image data stored in a string indstead of a file. Your string would probably look a little like this: "GIF89aEUR???!??&(?&(g(/&dg;" Well actually it wouldn't. But the general idea is that the string would be how an image file like a gif would look like if opened in a text editor. regards Max M From skip at pobox.com Sat Mar 2 13:13:23 2002 From: skip at pobox.com (Skip Montanaro) Date: Sat, 2 Mar 2002 12:13:23 -0600 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: <15489.5180.402637.125675@12-248-41-177.client.attbi.com> References: <15489.5180.402637.125675@12-248-41-177.client.attbi.com> Message-ID: <15489.5699.603634.319536@12-248-41-177.client.attbi.com> (Minor point of possible confusion.) I wrote: Skip> According to the pow man page on my Mandrake 8.1 system it Skip> suggests that ERANGE should be set if its first arg is zero. This Skip> appears to happen when x is around 1.5717e-162. "x" is the name of the first arg to pow() in the pow() manpage. The actual arg in floatobject.c:float_pow() is "iv". Skip From akuchlin at ute.mems-exchange.org Fri Mar 8 20:34:29 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 09 Mar 2002 01:34:29 GMT Subject: PEP Parade References: Message-ID: In article , Donn Cave wrote: > but putting us in kind of a backwater. If we sort of collectively > agree on 2.1.1 (or whatever) for that role, though, that backwater > could get pretty lively. Seems unlikely; if people can't muster enough interest to participate in handling bugs and patches in the current CVS tree, the likelihood of taking on the even drier and duller job of backporting fixes seems an order of magnitude less probable. Unless someone can be found to pay money for it, of course. (I wonder why more people don't maintain forks of the Python source tree for specific things like oddball platforms, though. Right now Linux is having a mini-explosion of different trees, some managed with an eye for stability, some for including all the bleeding edge patches; I don't think that would harm Python any.) --amk (www.amk.ca) "We're running out of places to run." "The story of our lives." -- Turlough and Tegan, in "The Awakening" From ronny at cs.kun.nl Tue Mar 5 08:21:57 2002 From: ronny at cs.kun.nl (Ronny Wichers Schreur) Date: Tue, 05 Mar 2002 14:21:57 +0100 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> <3C848DBE.CEF2A2F7@cs.kun.nl> <3C84A009.D0E65B6@kfunigraz.ac.at> Message-ID: <3C84C675.FEA4D5AE@cs.kun.nl> Siegfried Gonzi criticises Clean: > [..] The problem in Clean: the array concept is not a tool which helps > a programmer it impedes the programmer. The problem is not that an > array has a type the problem in Clean actually is that it is impossible > often to judge what is allowed and what not. Part of Clean's type system is the uniqueness typing. This is what allows destructive array updates, while keeping referential transparency. I suggested that it was the uniqueness type system that you're feeling uncomfortable with. > [..] Clean does often not work correctly. [...] It's hard to answer your criticism, because it's not very concrete. Maybe there was a problem in your program. For example, there are index out-of-bounds bugs in the Clean code you posted, which suggests that you ran the program with run-time index checks disabled. This can give undeterministic results. Or maybe there is a bug in the Clean system, but you write: > [..] I didn't contact any Clean developers, You didn't report the bugs to us, yet you see it fit to portray our implementation as completely unreliable. That's difficult for me to accept. I suggest we continue this discussion by email. Cheers, Ronny Wichers Schreur From maurelius01 at hotmail.com Fri Mar 22 17:12:55 2002 From: maurelius01 at hotmail.com (Marc) Date: Fri, 22 Mar 2002 17:12:55 -0500 Subject: mutlifile inheritance problem References: <9896e047.0203211303.741f695a@posting.google.com> <3C9A680A.F00216D2@hotmail.com> <3C9B8A4C.F7FB97FD@ccvcorp.com> Message-ID: <3C9BAC67.9BF9162D@hotmail.com> Jeff Shannon wrote: > > Marc wrote: > > > > > So here is my basic question: should I be able to > > inherit class from another file. > > Yes, you can do this. I do it all the time. And the way that you're doing it is > indeed correct -- just refer to the base class by its properly qualified name. > > I have no idea why you're having a problem, but then, I missed your initial post. > Are you getting an exception? If so, you might try posting the stack trace... > > Jeff Shannon > Technician/Programmer > Credit International Thanks Jeff - It's good to know that it can work. It does seem reasonable. Do you use reload? This seems to be part of my problem, but I find it tough to develope without it. I've reposted a simplified example, and hopefully with no typos this time. Marc From wealthychef at mac.com Fri Mar 15 13:21:44 2002 From: wealthychef at mac.com (wealthychef) Date: 15 Mar 2002 10:21:44 -0800 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <1016173476.645562@yasure> Message-ID: <2b57f654.0203151021.7f709e4c@posting.google.com> "Donn Cave" wrote in message news:<1016173476.645562 at yasure>... > Quoth grante at visi.com (Grant Edwards): > ... > | When select returns a file descriptor, that means that read() > | won't block. If only a partial line is available, then > | readline() will still block. I doubt that this is going to be > | an issue, since your output is probably line-oriented. That concerns me, because in many cases, it will not be line-oriented. I need a general tool. I cannot be sure about endlines in general, although for this case, of course I chose readline() because I am sure. If it is not line-oriented, must I then use select.select combined with read(1) and go character by character? That reminds me, is there a way to get the integer value of a character in Python analogous to casting a char to an int in C? > > That's a good point. > > The complementary problem, of course, is that once you have invoked > readline(), it will read all the data available on the file descriptor, > or a lot of it anyway, and return only the first line. The next time, > it will return the next line from its buffer, but you have no way to > know that it has another line waiting there. select() can't see it. > There are solutions, I think the easiest thing in most cases is to > throw away the file object and just use the file descriptor (fileno()) > (or sockets in this case.) This is even more frightening. I don't want to lose any data! How can I protect myself from this? Why is using the file descriptor better? Thanks for the help, good people! From eppstein at ics.uci.edu Mon Mar 4 14:18:29 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 04 Mar 2002 11:18:29 -0800 Subject: Status of PEP's? References: <3C82BABF.B632A4FB@cosc.canterbury.ac.nz> <3C83C368.3B98FEC8@ccvcorp.com> Message-ID: In article <3C83C368.3B98FEC8 at ccvcorp.com>, Jeff Shannon wrote: > I believe that Tim's comment was regarding how "for 3 < i < 10" would be > parsed. That was also how I interpreted it. > I vaguely recall a discussion, from the first time around, that the > parser will grab "for 3" and then choke on the rest. It would require > significant modifications to the parser to have it read the entire line and > then analyze it. This amount of work has been deemed not justifiable for the > (questionable) benefits of having this construct. Deemed by whom? It seems like it should be really easy to modify the parser to parse "for" expression ":" and then check whether the expression is an "in" or a comparison... > Of course, this is my vague memories, and could be totally wrong. Having a > PEP to archive things like this would be nice (even though I'd be hoping that > it gets rejected). I've started working on one. I'd like to know why you think it should be rejected, so that I can include all relevant views in the discussion section. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From jicondon at us.ibm.com Tue Mar 5 14:14:42 2002 From: jicondon at us.ibm.com (dW) Date: 5 Mar 2002 11:14:42 -0800 Subject: Python SOAP libraries - With and without WSDL Message-ID: IBM developerWorks released it second article on Python and SOAP: Continuing their look at Python SOAP implementations, Mike Olson and Uche Ogbuji put the Zolera SOAP Infrastructure (ZSI) through its paces as a SOAP client and server library. They find that ZSI is possibly the best tool for SOAP use under Python right now. http://www-106.ibm.com/developerworks/library/ws-pyth6?open&l=968,t=grws,p=py2 From jcromwell at ciena.com Fri Mar 15 13:43:20 2002 From: jcromwell at ciena.com (Cromwell, Jeremy) Date: Fri, 15 Mar 2002 10:43:20 -0800 Subject: syntax question: "<>" and "!=" operators Message-ID: >From Python Library Reference, section 2.2.3 Comparisons <> and != are alternate spellings for the same operator. (I couldn't choose between ABC and C! :-) != is the preferred spelling; <> is obsolescent. -Jeremy Cromwell -----Original Message----- From: josephgrossberg at hotmail.com [mailto:josephgrossberg at hotmail.com] Sent: Friday, March 15, 2002 10:13 AM To: python-list at python.org Subject: syntax question: "<>" and "!=" operators Is there any effective difference between the two? (Sorry if this has already been addressed; it's difficult to search on punctuation.) >>> name = "joe" >>> name <> 'Joe'; name != 'Joe'; name <> 'joe'; name != 'joe' 1 1 0 0 Doesn't this violate the Python principle that " There should be one--and preferably only one--obvious way to do it." if I'm interpreting that correctly? -- http://mail.python.org/mailman/listinfo/python-list From emile at fenx.com Tue Mar 26 16:28:08 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 26 Mar 2002 13:28:08 -0800 Subject: Most efficient unzip - inverse of zip? References: Message-ID: Pearu Peterson > What would be the most efficient way to unzip zipped sequences > in Python 2.2? > > For example, consider > > a_b = zip(a,b) # where a and b are some sequences > a_b.sort() > a,b = unzip(a_b) > You'd need to define efficient better, but I'd try something like: >>> z = zip(range(52),string.letters) >>> a = [ii for ii,jj in z] >>> b = [jj for ii,jj in z] -- Emile van Sebille emile at fenx.com --------- From bmeerdnk at telekabel2.nl Mon Mar 25 17:58:08 2002 From: bmeerdnk at telekabel2.nl (Bart Meerdink) Date: 25 Mar 2002 14:58:08 -0800 Subject: Is it really so difficult to enable Tkinter? Message-ID: (Warning: I'm a bit of a Python-newbie) After following the standard configure/make/make install procedure for python 2.2.1c1 (newer is always better, you know) on SuSE Linux, I found that tkinter would not work ("no module named _tkinter"). I tried again, installed the tck/tk 8.3.3 headers, did configure, edited Modules/Setup (paragraph about tkinter, guessing what I should change there), crossed my fingers, and continued with make and (as root) make install. Success! But I cannot believe this is the intended way. And sadly, the nice ActiveState rpm distribution, which worked out of the box, seems not to be maintained anymore. One more question: is it on purpose that idle is left out? Bart Meerdink From oscar at westlakefinancial.com Thu Mar 14 19:56:59 2002 From: oscar at westlakefinancial.com (Oscar) Date: 14 Mar 2002 16:56:59 -0800 Subject: Dear Guru, I have added def and it doesnt work Sincerly, F Message-ID: Dear Guru, I have added def joinsplit = (join(split(lines, '"'), ' ')) return joinsplit to watch.txt in an effort to replace " and / with " " to no avail. Old watch.txt works fine, without my new def. Please help. Sincerly, ''''\ ` c-@@ ` > \_ ^ Frustrated and Hostile. p.s. how far can computers fly if thrown out a window ?? line from watch.txt ( data change to protect the indecent or innocent) 7036718,"756-74-6445","04/04/74","(555) 555-0707","(555) 555-0002","829","E PATOR ST","CHANDLER","AZ","85225","HOLE, MICHELE M." ________________________________________________________________________________ #!/usr/bin/python # Script is for "batch alternate input request for TRANS UNION. # for use with a file generated from an I.Q. report from Megasys. # watch.py version 0.3 date: Mar 12 2002 by Oscar # new def -- the one not working ############################################## def joinsplit = (join(split(lines, '"'), ' ')) return joinsplit ## old stuff works fine ############################################# def fixdate(date): """This is a method to format the date properly""" stringdate = str(date) year = stringdate[6:] month = stringdate[:2] day = stringdate[3:5] return year + month + day def paddfield(field,length): padded = field + (" "*(length-len(field))) return padded def fixnumeric(field,length): """remove garbage characters and also pads""" stringfield = str(field) fixedfield = '' for char in stringfield: if char in ('0','1','2','3','4','5','6','7','8','9'): fixedfield = fixedfield + char padded = fixedfield + (" "*(length-len(fixedfield))) return padded file=open("watch.txt") lines = file.readlines() for line in lines: list = eval('[' + line + ']') """subscriber specific information""" list.append("F ") list.append("0254438") list.append("ZN95") list.append("1258") formatted = str(list[0]) + str(list[1]) + fixdate(list[2]) + joinsplit.fixnumeric(list[3],10) + joinsplit.fixnumeric(list[4],10) + fixnumeric(list[5],5) + joinsplit.paddfield(list[6],30) + paddfield(list[7],16) + list[8] + fixnumeric(list[9],9) + paddfield(list[10],50) + list[11] + list[12] + list[13] + list[14] print formatted From jeff at ccvcorp.com Mon Mar 18 15:40:38 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 18 Mar 2002 12:40:38 -0800 Subject: Begginers Guide - Exrcise. Help me, plz! References: Message-ID: <3C9650C6.6427FA27@ccvcorp.com> Jeffrey-man wrote: > Thank you very much! > Here it is the final version: This is good, but there's a few improvements that could be made. (I've reindented your code -- single-space indents are hard to read.) > sum = 0 > sum_stop = 100 > while sum < 100: You've defined sum_stop, but you're not using it. > num = input("Please enter the number: ") > sum = sum+num > if sum < 100: > print "The sum is", sum > else: > print "The sum is > 100 and it is", sum As long as you're in your while loop, you *know* that sum < 100, so doing this explicit 'if' test isn't really necessary. Try something like this: while sum < sum_stop: num = input("Please enter the number:") sum = sum + num # could also be sum += num print "The sum is", sum print "and it is > 100" This will print "The sum is ..." after every number input. When the sum goes over 100, the while loop ends and it *also* prints the "and it is..." line. Jeff Shannon Technician/Programmer Credit International From ulbi at ivs.tu-berlin.de Fri Mar 15 04:26:00 2002 From: ulbi at ivs.tu-berlin.de (Andreas Ulbrich) Date: Fri, 15 Mar 2002 10:26:00 +0100 Subject: how to check how many bytes are available to read() ? References: <2b57f654.0203142026.68ec3fc7@posting.google.com> Message-ID: <3C91BE28.2050508@ivs.tu-berlin.de> Grant Edwards wrote: > > If f is a pipe, then you can use select -- at least under Unix. > I don't know about Windows. > Lib ref. says that this will only work for sockets on Windows. From philh at comuno.freeserve.co.uk Mon Mar 4 14:44:47 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 4 Mar 2002 19:44:47 +0000 Subject: Deitel and Deitel Book... References: Message-ID: On Sun, 3 Mar 2002 12:01:03 -0600, Jason Orendorff wrote: >Sheila King wrote: >> That's funny. I'm not familiar with the Lippman/Lajoie book, but I >> have a LOT of C++ texts here at home. And I learned C++ from the Deitel >> and Deitel book, and thought it was pretty good. Later, when I taught >> C++ I used it as a reference, although I didn't select it as the text >> for my course. Most people I know who are familiar with the Deitel >> and Deitel C++ text think it is very good. > >I dislike Deitel & Deitel because of their casual disregard for >correctness. I can't open any of their books without finding an error. >In C++HTP, they illustrate "Circle" as a subclass of "Point". This could well be the case in a particular class hierarchy. > In CHTP, >they say it's a common programming error to use \n outside of a printf >statement (it only works in printf statements, they say). That's an absurd thing to say. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From tanzer at swing.co.at Mon Mar 25 03:22:41 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Mon, 25 Mar 2002 09:22:41 +0100 Subject: 2.2 open In-Reply-To: Your message of "Mon, 25 Mar 2002 15:41:40 +1200." <3C9E9C74.781B3911@cosc.canterbury.ac.nz> Message-ID: Greg Ewing wrote: > Robin Becker wrote: > > > > So the question now is, how do I tell if __import__ is the built in one > > even if the import system is not fully initialized. > > You could compare its type with what you really > should have been comparing it with in the > first place: > > import types > if type(__import__) == types.BuiltinFunctionType: > ... Curious what you'll say about you-really-should-have-been-comparing-it-with-in-the-first-place when `__import__` evolves into a type itself <3/4 wink>. Despite-the-righteousness-your-advice-is-sound-though-ly yr's -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From gerhard at bigfoot.de Sat Mar 2 06:33:56 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 2 Mar 2002 11:33:56 GMT Subject: Fw: smtplib: including a subject References: Message-ID: Tal Linzen wrote in comp.lang.python: > Hi. > > I couldn't figure out how to send a mail with a subject. Help? You're not the first one to have this problem *hint, hint*: See http://groups.google.com/groups?q=python+smtplib+subject for previous discussions of this question. > (By the way, I think the docs on this module could use some > rewriting -- it appears to be directed to those familiar with the c > library it wraps, rather than to the common Python user). You'll need to file a bug report at the Sourceforge bug tracker if you want to bring this to the attention of the Python committers. Be sure to set the Category to "Documentation". Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From gvdbogae at vub.ac.be Fri Mar 1 19:16:57 2002 From: gvdbogae at vub.ac.be (Geert-Jan Van den Bogaerde) Date: 02 Mar 2002 01:16:57 +0100 Subject: Stedents Question In-Reply-To: <1015027935.1342.3.camel@gandalf> References: <3c80126f_1@news.iprimus.com.au> <1015027935.1342.3.camel@gandalf> Message-ID: <1015028218.1341.9.camel@gandalf> On Sat, 2002-03-02 at 01:12, Geert-Jan Van den Bogaerde wrote: > On Sat, 2002-03-02 at 00:45, Tony K wrote: > > The question below is a tutorial question that stumps me. Any suggestions > > would be appreciated. > > Tony > > > > Write a Python function findABBC which takes a single string as parameter > > and returns all substrings thereof which match the regexp pattern ab+c. You > > are NOT allowed to use the re module. > > > > Haven't used regexps in a while, but I believe that just means: > > def findABBC(str): > return str == "a" + "b" * len(str[1:-1]) + "c" > And as I press send I spot an error in my code, it should be: def findABBC(str): return len(str) > 2 and str == "a" + "b" * len(str[1:-1]) + "c" as we need at least one b Geert-Jan From peter at engcorp.com Sun Mar 24 22:43:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 22:43:57 -0500 Subject: question: python and UDP References: Message-ID: <3C9E9CFD.AC6A149B@engcorp.com> ricky wrote: > > I am trying to write a python program to connect to a proxy server which > takes the following header: > however, the proxy server doesn't seem to understand the header i sent to > it. [...] > My question is how do i format the header so that proxy server would > understand the information I send to it. [...] Are you looking for the 'struct' module? That should be enough to produce the header format you need. -Peter From phd at phd.pp.ru Sun Mar 17 17:22:52 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 18 Mar 2002 01:22:52 +0300 Subject: Eliminate Spam Now... >g< Python w/DNS/&POP3 In-Reply-To: ; from junkster@rochester.rr.com on Sun, Mar 17, 2002 at 09:56:15PM +0000 References: Message-ID: <20020318012252.C30949@phd.pp.ru> On Sun, Mar 17, 2002 at 09:56:15PM +0000, Benjamin Schollnick wrote: > I'm attempting to use the (py)DNSlib (sourceforge project), to look > up Spammers via ORBZ (or similiar group)... ORBZ is far from the best balcklist. I heard stories of good people listed there becuase they've said something bad about ORBZ or people behind it. I stopped using ORBZ - they list too many good site. I recommend the following resources to learn how to fight spam (filters using blacklists or header/content analysis, reporting tools, etc): http://www.abuse.net/ http://spam.abuse.net/spam/ http://spamcop.net/ http://www.cauce.org/ http://www.nanae.org/ http://openrbl.org/ http://razor.sourceforge.net/ http://spamassassin.org/ http://www.spambouncer.org/ http://junkfilter.zer0.org/ http://samspade.org/ http://combat.uxn.com/ Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From mats at laplaza.org Sun Mar 3 11:38:13 2002 From: mats at laplaza.org (Mats Wichmann) Date: Sun, 03 Mar 2002 16:38:13 GMT Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: <3c82509c.213336581@news.laplaza.org> On 2 Mar 2002 23:22:36 GMT, bokr at oz.net (Bengt Richter) wrote: :On Sat, 02 Mar 2002 00:22:58 GMT, mats at laplaza.org (Mats Wichmann) wrote: : :>Note: this is not a Python question per se. :> :>I'm looking for a piece of software to aid in reviewing a document :>through the web :If it doesn't have to be too slick, I think you could write relatively :simple cgi to do it, depending on what you mean by "document". :Also, with a small collection of doc text pages and a few occasional :user/reviewers you could get away with something that wouldn't scale :to a massive online catalog with graphics layout and thousands of reviewers. : :I've thought it would be nice to have something like that for collaborating :on documentation and/or maybe PEPs. : :What kind of docs are you dealing with? Smallish - for my uses, it doesn't have to scale very far. On the order of one to dozens of printed pages (should anyone print 'em), rather than hundreds, certainly; and with similar orders of magitude for number of reviewers. The sorts of docs are spec fragments, documentation, whitepapers, maybe FAQ answers. Mats Wichmann From shivers at cc.gatech.edu Fri Mar 29 15:50:27 2002 From: shivers at cc.gatech.edu (Olin Shivers) Date: 29 Mar 2002 20:50:27 GMT Subject: SIGPLAN Scheme Workshop Message-ID: The Scheme Workshop will be held this year in Pittsburgh, in October, the day before ICFP. I am the workshop chairman. I am taking the liberty of cross-posting the call for papers to some netnews programming-language groups with related topics. We would certainly welcome papers on relevant topics from your communities as well as attendance and participation in the workshop's discussions. -Olin Shivers =============================================================================== ACM SIGPLAN 2002 Scheme Workshop Thursday, October 3, 2002 Pittsburgh, Pennsylvania The workshop forms part of PLI 2002, which consists of the ICFP and PPDP conferences and other workshops. Full details on the workshop can be found at URL . ------------------------------------------------------------------------------- * Scope ------- The purpose of the workshop is to discuss experience with and future developments of the Scheme programming language, as well as general aspects of computer science loosely centered on the general theme of Scheme. Papers are invited concerning all aspects of the design, semantics, theory, application, implementation, and teaching of Scheme. Some example areas include (but are not limited to): - Theory Formal semantics, correctness of analyses and transformations, lambda calculus. - Design critiques Limitations of the language, future directions. - Linguistic extensions Scheme's simple syntactic framework and minimal static semantics has historically made the language an attractive "lab bench" for the development and experimentation of novel language features and mechanisms. Topics in this area include modules systems, exceptions, control mechanisms, distributed programming, concurrency and synchronisation, macro systems, and objects. - Type systems Static analyses for dynamic type systems, type systems that bridge the gap between static and dynamic types, static systems with "type dynamic" extensions, weak typing. - Implementation Compilers, optimisation, virtual machines, resource management, interpreters, foreign-function interfaces, partial evaluation, and generally implementations with novel or noteworthy features. - Program-development environments The Lisp and Scheme family of programming languages have traditionally been the source of innovative program-development environments. Authors working on these issues are encouraged to submit papers describing their technologies. - Education Scheme has achieved widespread use as a tool for teaching computer science. Papers on the theory and practice of teaching with Scheme are invited. - Applications and experience Interesting applications which illuminate aspects of Scheme; experience with Scheme in commercial or real-world contexts; use of Scheme as an extension or scripting language. - Scheme pearls Elegant, instructive examples of functional programming. A "Scheme pearl" submission is a special category, and should be a short paper presenting an algorithm, idea or programming device using Scheme in a way that is particularly elegant. ------------------------------------------------------------------------------- * Proceedings ------------- The proceedings of the conference will be published as a Georgia Tech College of Computing technical report. A special issue of the journal Higher-Order and Symbolic Computation about Scheme is planned afterwards. ------------------------------------------------------------------------------- * Important dates ----------------- - Submission deadline: 2200 UTC, 17 May, 2002 - Notification of acceptance or rejection: 28 June, 2002 - Final paper due: 31 August, 2002 - Workshop: 3 October, 2002 ------------------------------------------------------------------------------- * Submission guidelines ----------------------- Authors should submit a 100-200 word abstract and a full paper by 22:00 Universal Coordinated Time on Thursday, 17 May, 2002. (Note that 2200 UTC is 1800 EDT, or 1500 PDT.) Submissions will be carried out electronically via the Web, at . Papers must be submitted in PDF format, or as PostScript documents that are interpretable by Ghostscript, and they must be printable on US Letter sized paper. Individuals for which this requirement is a hardship should contact the program chair at least one week before the deadline. There are two classes of submissions: reular papers and short papers: - Regular papers Submissions should be no more than 12 pages (including bibliography and appendices) in standard ACM conference format: two columns, nine point font on ten point baseline, page 20pc (3.33in) wide and 54pc (9in) tall with a column gutter of 2pc (0.33in). Authors wishing to supply additional material to the reviewers beyond the 12 page limit can do so in clearly marked appendices, on the understanding that reviewers are not required to read the appendices. Submissions that do not meet these guidelines will not be considered. Suitable style files for Latex, Word, and Word Perfect can be found on the submission Web site. Submitted papers must have content that has not previously been published in other conferences or refereed venues, and simultaneous submission to other conferences or refereed venues is unacceptable. Each paper should explain its contributions in both general and technical terms, clearly identifying what has been accomplished, saying why it is significant, and comparing it with previous work. Authors should strive to make the technical content of their papers understandable to a broad audience. - Short papers Short papers need not present novel research; it is sufficient that they present material of interest or utility to the Scheme or functional-programming community. "Scheme pearls" submissions should be presented as short papers. Short papers should be formatted with the same guidelines as regular papers, but are expected to be typically around six pages in length. ------------------------------------------------------------------------------- * Organisers ------------ Workshop chair: Olin Shivers College of Computing Georgia Tech Atlanta, Ga 30332-0280 +1 404 385.00.91 shivers at cc.gatech.edu Steering committee: William D Clinger (Northeastern University) Marc Feeley (University of Montreal) Matthias Felleisen (Northeastern University) Matthew Flatt (University of Utah) Dan Friedman (Indiana University) Christian Queinnec (University Paris 6) Manuel Serrano (INRIA) Mitchell Wand (Northeastern University) Program committee: Alan Bawden (Brandeis) Olivier Danvy (University of Aarhus) Richard Kelsey (Ember, Corp.) Brad Lucier (Purdue University) Paul Steckler (Northeastern University) Andrew Wright (Aleris) Publicity: Shriram Krishnamurthi (Brown University) From michael+usenet at dynamine.net Fri Mar 29 18:28:00 2002 From: michael+usenet at dynamine.net (Michael S. Fischer) Date: Fri, 29 Mar 2002 23:28:00 -0000 Subject: IOError on file close References: Message-ID: On 30 Mar 2002 00:11:37 +0100, Martin v. Loewis wrote: > "Michael S. Fischer" writes: > >> It appears that the write() call is the one that's failing, not the >> close() call. Python is throwing the exception at the wrong time. >> Should I report this as a Python bug? > > Not really. My guess is that the C library buffers the write call, and > attempts to flush the stream when closing the file. This, in turn, > produces the error - the write itself succeeds. > > Just try opening the file without buffering. OK, I added a third argument (..., 0) to the open() call and now the exception is thrown during the write() call. Thanks. -- Michael S. Fischer / michael at dynamine.net / +1 650-533-4684 Lead Hacketeer, Dynamine Consulting, Silicon Valley, CA From news at charneyday.com Tue Mar 5 14:32:01 2002 From: news at charneyday.com (Reginald B. Charney) Date: Tue, 05 Mar 2002 19:32:01 GMT Subject: Order of constructor/destructor invocation References: Message-ID: Brett is exactly right. I am using an approach that is valid and elegant in C++. Since I am fairly new to Python, I had assumed it handled contructors/destructors in an ordered (i.e. deterministic) fashion. It seems not. While Justin is correct - there are a number of packages out there to generate HTML, I was writing an article and trying to use Python for the simple examples in the article. (The article was not about Python, per se). I had to remove all references to Python when I found that the order of destruction was non-deterministic. As an aside, it seems a shame that while algorithms are often implementation independent, their actual coding varies widely because of language semantics. For example, I expect all computer languages to have a looping construct, a way of doing arithmetic, and a way of testing for ordering. In OO languages, I expect a way of defining classes, instantiating them, defining inheritance and polymorhism, etc. It is interesting that destruction/garbage collection (something usually done after everything has been completed) has so profound effect on the design of programs and thus, implementation of algorithms. Reg. "Brett g Porter" wrote in message news:Rt8h8.111896$7a1.9472757 at bin5.nnrp.aus1.giganews.com... > > "Justin Sheehy" wrote in message > news:mailman.1015350430.26774.python-list at python.org... > > "Reginald B. Charney" writes: > > > > > Perhaps you are using "destructors" to refer to some concept that is > > different from what the rest of us use that word for? > No, based on what he wants to do (and his observation that Python suffers > from the same 'misdesign' as Java) it's pretty clear that he's using > 'destructor' in the C++ sense, since C++ dtors have exactly the behavior > he's looking for. > > As someone who needed a year or so to separate the C++ and Python halves of > my brain, I sympathize, and can only urge (as gently as possible) Mr Charney > to think Pythonically , instead of dealing with the frustration of expecting > Python to follow C++'s rules. Down that path lies madness. > > > -- > // Brett g Porter * Lead Engineer, Development Practices > // BgPorter at artlogic.com * www.artlogic.com > // Art & Logic, Inc. * software engineering and design > // Desktop * Embedded * Web > > From tim.one at comcast.net Mon Mar 18 23:50:13 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 18 Mar 2002 23:50:13 -0500 Subject: RELEASED: Python 2.2.1c1 In-Reply-To: <3C9727A0.2030402@bigfoot.de> Message-ID: [Gerhard H?ring] > That's why I asked. I get this: As Michael asked, please email results to him. From susan at mars.provis.com Fri Mar 29 16:17:17 2002 From: susan at mars.provis.com (Susan Williams) Date: Fri, 29 Mar 2002 15:17:17 -0600 (CST) Subject: Newbie: List of instances? Message-ID: <200203292117.g2TLHH305110@mars.provis.com> >> This is closer. a itself is an object, and the way you deal >> with it, at least for some functions, is thru its methods. >> append is a method of the list object, so what you really want >> is: >> >> a.append(Bob('localhost')) > >This works! If I create a list a that has five elements where >are just instances of Bob, can I "call" a method for a specific >element of the list? I take I can (Jeff sneaks off to experiment >while his wife is napping). > >Thanks! > >Jeff Hope your experiments went well. Not sure exactly which question you're asking, but: Once you have a list with elements, you can get to an element in the "normal" way like a[0]. This is really using a method of the list object too, but its more like a function overload where [] is a sort of operator. (Sorry, I'm not a "language lawyer" so that is not the best explanation :-) Or: yeah, you can call a Bob method on an element of a: a[0].Bobmethod1('somethingOrOther') susan From bokr at oz.net Fri Mar 1 04:30:13 2002 From: bokr at oz.net (Bengt Richter) Date: 1 Mar 2002 09:30:13 GMT Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: On 28 Feb 2002 15:09:23 +0100, Martin von Loewis wrote: [...] >You may wonder why Python (the programming language) needs to worry >about the encoding at all. The reason is that we allow Unicode >literals, in the form > > u"text" > >The question is what is the encoding of "text", on disk. In memory, it >will be 2-byte Unicode, so the interpreter needs to convert. To do >that, it must know what the encoding is, on disk. The choices are >using either UTF-8, or allowing encoding cookies. > I'm not sure what you mean by 'encoding cookies' but I assume you mean something analogous to browser cookies, where some data of interest is stored separately but related to some other data and processing, like HTML form sumbissions etc. Well, forget the cookie associations, but I think keeping meta-data separate from data is a Good Thing(tm). Also keeping it out of the names of things (i.e., don't encode file types in name extensions ;-) Perhaps we could just use a file to contain extra file metadata, letting a file of metadata govern other files it names in the same directory as itself. Probably a dot file in *nix. For PEP 263 purposes, it would only need to be a text file with file names tab delimited from keyword=encoding-info, with the first line(s) perhaps with a glob pattern for a compact way of specifying encoding for a lot of files in a directory at once. To provide international encoding for file-associated info, like a local dialect/special characters name etc., in a system whose native file naming is more restricted, perhaps this directory of file attributes could be standardized to UTF-8 for its own encoding. That way, you could have the first column represent the file name the system sees and an optional uname= keyword could provide an alternate utf-8 encoded name for the file that tools that knew of it could display, and then encoding=whatever for the actual file data per se. The nice thing is that you don't have to touch the original files to describe them. By including a location= keyword you could even have this work like a symbolic link to a network file or even an URL-specified file, which could be read-only and burned in a CD, or a please-mount-backup-tape-x location, etc. The actual file data would not have to be in the same directory at all. I have more ideas, but I tend to overdo one post that way ;-) Regards, Bengt Richter P.S. This discussion made me look for some more UTF info. For anyone interested, I found a FAQ at http://www.unicode.org/unicode/faq/utf_bom.html#2 and http://www.unicode.org/unicode/reports/tr27/ has a nice table showing where bits go for UTF-8 and UTF-16 encoding of unicode characters, and even 32-bit stuff. Might make a refs links for the PEP. There are some changes as to legality checks, apparently, as of last May. I'm wondering if this affects PEP 263 and/or the unicode implementation in Python. From eric at vasilik.com Sun Mar 17 19:58:46 2002 From: eric at vasilik.com (Eric Vasilik) Date: 17 Mar 2002 16:58:46 -0800 Subject: Help with a Python ASP C extension module ... References: <40ee0487.0203152316.70c12a49@posting.google.com> <3C93F993.3010109@skippinet.com.au> Message-ID: <40ee0487.0203171658.10d1192d@posting.google.com> Thanks Mark, you nailed *exactly* what I'm looking for! I will try to use this asap. I am using Response.BinaryWrite to send an image to the client. To test the performance of my own writes, I have two web pages. One has 30 images all directly hitting JPEGs on my server. The second page has references to the same 30 images, but using a url which causes the server to go to a python script which writes the JPEGs out. By eyeballing the amount of time it takes to completely load both pages, I see that it takes almost 3 times as long to load the page which goes thorugh the script. I'm not sure where the bottleneck is, I'm trying to rule out the GIL by doing my own call to IResponse.BinaryWrite. However, as you point out, there may be other factors. I have to track down some: 1) I'm using a custom 404 error handler to invoke the script. Perhaps there is some single threading issues there? Probably not, I would think that IIS can hand out plenty of errors without locking all threads out. 2) I'm not sending the right caching headers out to the client and the client is refetching all the images all the time, while the direct JPEG page fetches them from the cache. This is a real possibilty I'll have to track down. I'll post back when (if :-) I find out! P.S. I'm eagerly awaiting the arrival of your book "Python Programming on Win32"! - Eric Mark Hammond wrote in message news:<3C93F993.3010109 at skippinet.com.au>... > Eric Vasilik wrote: > > I am writing a C extension to Python. The reason I am writing an > > extension is that I believe that the implementation of > > Response.BinaryWrite() in the Window's ASP extension (I am using > > Active State's Python 2.1) is not releasing the global interpreter > > lock. > > I am almost certain that it does. All COM calls release the GIL. > Response is an IDispatch object. This means that the call is made via > either PyIDispatch::Invoke, or PyIDispatch::InvokeTypes. These release > the lock. > > > I am getting very poor performace using it and I believe that > > my server is not taking advantage of writing out multiple streams > > because of the global lock. > > I am not sure what makes you believe Reponse.Write is to blame. It is > more likely that another Python thread is "busy" somewhere other than > Response.Write or fileIO. > > > Instead of writing out a response with: > > > > Response.BinaryWrite( buffer( open( fileName, 'rb' ).read() ) ) > > > > I am now doing the following: > > > > PythonExt.binaryWriteFile( Response, fileName ) > > OK - but don't be surprised if you see pretty much the same thing. You > are removing a little Python overhead, but not alot. > > > The difference between these two is that the first calls the default > > implementation of Response.BinaryWrite and the second calls an > > extension I have written which reads the file and writes it out to > > response, all while the interpreter lock is released. > > The former Python version will do all the significant work (ie, the file > open, read and response.write call) with the lock released too. Some of > the IDispatch mechanics will be avoided though, as will the multiple > lock transitions involved in the Python version. > > > My problem, is I cannot find any documentation on how to get a hold of > > the IResponse object from the Python Response object. I need to get > > it so that I may call BinaryWrite on without going back into the > > Python interpreter. > > Going via IResponse should speed things up a tiny bit too. Basically, > the "Response" object is a class instance, and the attribute "_oleobj_" > is the PyIDispatch object. So you need something like: > > if (!PyArg_ParseTuple("Os", &pyResponse, &filename)) ... > PyObject *pydisp = PyObject_GetAttrString(pyResponse, "_oleobj_"); > if (!pydisp) ... > // now get the object. > if (!PyCom_InterfaceFromPyObject(pydisp, > IID_IRESPONSE, > (void **)&pResponse, > FALSE /* None is not valid */ )) ... > Py_DECREF(pydisp); > ... use pResponse > pResponse->Release(); > > > Using PyCom_InterfaceFromPyObject() means you will need to include > pythoncom.h, and link against pythoncomxx.lib - which means you will > need to build pythoncom from sources - see > http://starship.python.net/crew/mhammond/win32/BuildingExtensions.html > > Mark. From mwh at python.net Tue Mar 5 10:32:54 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Mar 2002 15:32:54 GMT Subject: Patch: clearing breakpoints in IDLE References: <3C84E2C9.8DC206B4@tds.net> Message-ID: "Edward K. Ream" writes: > Hi all: > > I am beginning to think that IDLE's debugger suffers from a vicious > cycle: > > 1. Nobody uses IDLE's debugger, so > 2. Nobody complains about its glaring deficiencies, so > 3. Nothing gets fixed, so (back to one) http://www.python.org/patches/ (noone will see this here) Actually, you may want to consider talking to the idlefork folks, as that's where I believe idle development is happening these days: http://idlefork.sf.net Cheers, M. -- It's actually a corruption of "starling". They used to be carried. Since they weighed a full pound (hence the name), they had to be carried by two starlings in tandem, with a line between them. -- Alan J Rosenthal explains "Pounds Sterling" on asr From jason at tishler.net Mon Mar 18 07:49:19 2002 From: jason at tishler.net (Jason Tishler) Date: Mon, 18 Mar 2002 07:49:19 -0500 Subject: Problem using pexports & Cygwin to build Python 2.2 extension modules In-Reply-To: References: Message-ID: <20020318124918.GB1460@tishler.net> Les, On Mon, Mar 18, 2002 at 11:57:14AM +0100, Anton Vredegoor wrote: > On Sun, 17 Mar 2002 15:21:19 GMT, "Les Button" wrote: > >$ python setup.py build --compiler=cygwin > > try: > setup.py build --compiler=mingw32 I concur with Anton that the "--compiler=mingw32" is required to build Win32 Python extensions with Cygwin gcc -mno-cygwin. FWIW, this is how I build the Win32 Python readline extension. Jason From brueckd at tbye.com Wed Mar 13 10:20:22 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 13 Mar 2002 07:20:22 -0800 (PST) Subject: Converting relative URLs to absolute In-Reply-To: Message-ID: On Tue, 12 Mar 2002, James A Roush wrote: > Does anyone have any code that, given that absolute URL of a web page, can > convert all the relative URLs on that page to their absolute equivalent? Hi James, You have to separate problems here: finding/replacing the URLs and converting relatives to absolutes. The second problem is the easiest: >>> import urlparse >>> absolute = 'http://www.foo.com/bar/baz/file.avi' >>> url = '../boink/boom.mpg' >>> urlparse.urljoin(absolute, url) 'http://www.foo.com/bar/boink/boom.mpg' In order to handle the first problem you have to decide which URLs you're interested in: just hrefs or everything (at least img, embed, object, param can have URLs too). Also, you need to search the head of the HTML document for an optional 'base' HTML tag that specifies the new base URL to use. -Dave From fredrik at pythonware.com Sun Mar 10 16:46:42 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 10 Mar 2002 21:46:42 GMT Subject: Syntax to catch specific exceptions ? References: <3C8BD227.7D1D5539@vip.fi> Message-ID: <6vQi8.24234$n4.4716288@newsc.telia.net> Pekka Niiranen wrote: > I can get the error text and number as follows, but how to catch only > "File exists" OSError ? > > try: > ... os.mkdir('e:\\tmp') > except OSError, (errno, strerror): > ... print strerror > ... > File exists catch it, check the errno attribute, and raise it again if it's not the right error: import os, errno try: os.mkdir(somedir) except OSError, v: if v.errno != errno.EEXIST: raise # directory exists alternatively, you can use os.path.isdir to check if the directory exists before you call mkdir. From mkingston at -at-shaw.ca Wed Mar 6 14:38:21 2002 From: mkingston at -at-shaw.ca (Mark Kingston) Date: Wed, 6 Mar 2002 11:38:21 -0800 Subject: Python on W2K server and dos batch files? Message-ID: <3c866f0c$1_2@axion.net> Hello Experts, I've been looking into the possibility of using Python as a scripting language for use on our Windows 2000 Server with Terminal Services and Citrix Metaframe XPa. The reason I'm looking into a scripting language instead of a compiled program is that I need to add new functionality to the programs often. The scripting program will also serve as a "launch pad" for other DOS batch files and compiled console applications. I would appreciate if you can tell me if Python is a good fit for what I want to do. If not, please recommend another solution. The tasks I wish to accomplish is as follows: 1. Create a GUI (wxPython?) which will be used for server administration purposes such as automatically displaying a list of NT users on a form and allowing the user to select which user to enable or disable. 2. Create a GUI which will allow a user to launch other scripts such as DOS batch files, Windows programs and console programs. 3. The GUI should also be able to capture the output of console programs and display it on it's own text box or panel. 4. Perform advanced text file manipulation. Thanks for reading this long post and any information is greatly appreciated! -- Mark. mkingston at -at-shaw.ca Please remove '-at-' from email if replying directly to me. From dnijaguar at yahoo.com Tue Mar 19 15:43:54 2002 From: dnijaguar at yahoo.com (Matt Strange) Date: 19 Mar 2002 12:43:54 -0800 Subject: Newbie: EOF Error when making arrays .fromfile Message-ID: <33e33d88.0203191243.454d39b8@posting.google.com> hello all, i am very new to python and i'm using v2.2 on a Win98SE machine. i needed to read in double-type data from an ASCII file (http://dnijaguar.tripod.com/planet0.dat). this file contains 3000 doubles separated by the tab("\t") value. after reading information posted on this newsgroup, i decided that it would be best to first translate this ASCII data into a binary file using a c++ program (http://dnijaguar.tripod.com/atb.cpp). then, i could read in this binary file (http://dnijaguar.tripod.com/bin0.dat) with the following lines of python: >>> coord = array('d') >>> coord.fromfile(open("bin0.dat",'r'),3000) however, there is a problem. i recieve the error: Traceback (most recent call last): File "", line 1, in ? EOFError: not enough items in file and when i type in "coord" from the >>> prompt to see what is stored inside it, i see the values listed at the very end of this message; i.e. the correct values, but definately not 3000 of them like i wanted. i would appreciate it if someone would tell me the reason i am having this problem and the code necessary to fix it (with ASCII or binary files). thank you very much for your help. value of coord shown on command line: array('d', [100000.0, 10000.0, -10000.0, 99995.0, 10001.0, -9998.0, 97469.199999 999997, 10493.200000000001, -8994.9799999999996, 94890.199999999997, 10969.0, -7 986.0299999999997, 92255.0, 11426.4, -6971.3000000000002, 89560.100000000006, 11 863.4, -5950.9799999999996, 86801.800000000003, 12277.799999999999, -4925.369999 9999999, 83976.100000000006, 12666.6, -3894.8499999999999, 81078.399999999994, 1 3026.799999999999, -2859.9699999999998, 78103.5, 13354.6, -1821.4400000000001, 7 5045.800000000003, 13645.5, -780.21400000000006, 71898.800000000003, 13894.20000 0000001, 262.42399999999998, 68655.199999999997, 14094.4, 1304.74, 65306.5999999 99999, 14238.299999999999, 2344.4000000000001, 61843.599999999999, 14316.2000000 00001, 3378.1500000000001, 58255.099999999999, 14316.299999999999, 4401.5, 54528 .599999999999, 14223.5, 5408.04, 50649.400000000001, 14018.5, 6388.46, 46600.699 999999997, 13676.4, 7328.8599999999997, 42363.400000000001, 13164.299999999999, 8207.8999999999996, 37917.5, 12439.6, 8991.7999999999993, 33244.199999999997, 11 447.799999999999, 9625.9500000000007, 28333.599999999999, 10126.6, 10022.7000000 00001, 23197.5, 8424.3799999999992, 10051.5, 17877.599999999999, 6340.1099999999 997, 9557.7600000000002, 12415.1, 3945.0, 8431.9799999999996, 6784.3100000000004 , 1310.78, 6655.5600000000004, 863.47900000000004, -1607.8800000000001, 4227.600 0000000004, -5535.2299999999996, -5062.9700000000003, 1022.54, -12557.1, -9702.5 100000000002, -3429.2600000000002, -19426.0, -17103.799999999999, -10433.2999999 99999, -21219.700000000001, -28053.400000000001, -20689.5, -16580.799999999999, -38120.0, -30341.599999999999, -9804.4699999999993, -46184.900000000001, -38337. 099999999999, -2476.6100000000001, -52974.699999999997]) From michael at amtec.com Fri Mar 29 10:43:57 2002 From: michael at amtec.com (Michael Saunders) Date: Fri, 29 Mar 2002 07:43:57 -0800 Subject: Executing a specific function. Message-ID: <3CA48BBD.FF96D257@amtec.com> I see that the Python C API provides several interfaces for compiling and executing Python code. But I don't want to just execute some Python code I want to call a particular function within a Python file. How do I call a Python function (from C) in a some .py file? Michael From philh at comuno.freeserve.co.uk Tue Mar 12 17:18:09 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Tue, 12 Mar 2002 22:18:09 +0000 Subject: RFC PEP candidate: q''quoted ? References: Message-ID: On 3 Mar 2002 09:50:58 GMT, Bengt Richter wrote: >Problem: How to put quotes around an arbitrary program text? I assume you mean here a *Python* program. > assert q'<-=delim=->'content here<-=delim=-> == 'content here' # this would be true > >without getting an error. Looks a bit complex. What if you have a quoted string inside a quoted string, e.g, you want to quote this: list = [1, q'|'string|, 3] if you just choose the same dewlimiter for the next time, it fails: q'|'list = [1, q'|'string|, 3]| as this would parse as the string "list = [1, q'" followed by a syntax error. Of course, you could choose another delimeter, but it'd be nice if this could be done automatically by a simple-minded program. Lisp is famous for being able to quote program text. The way it manages it is by using (...); this is possible because any brackets inside must match. Let's try this for Python, using {} instead of (), to prevent it from looking like a function call: list = [1, q{string}, 3] and: q{list = [1, q{string}, 3]} This works. The reason it works is that the outer '{' only tries to connect to the matching '}'. Inner braces are matched with themselves; braces inside normal strings or comments are ignored. >Note the lack of quotes around the final delimiter string, since it itself is >the final delimiter. This can also be used to solve the final unescaped >backslash problem for quoting windows paths: > > q'|'c:\foo\bar\| """c:\foo\bar\""" and r"c:\foo\bar\" work just as well. The best solution, of course, is to not use Windows. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From shalehperry at attbi.com Sat Mar 9 17:50:55 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 09 Mar 2002 14:50:55 -0800 (PST) Subject: range Failure? In-Reply-To: <3C8A8564.E2F005AA@sympatico.ca> Message-ID: On 09-Mar-2002 Colin J. Williams wrote: > > > It would seem that the first execution below should deliver the same >
    result as the second. >
    >>> range(5, 2) >
    [] >
    >>> range(0, 5, 2) >
    [0, 2, 4] GAH! kill the html please. range(5,2) says "start at 5 and go to 2" which makes no sense and thus returns an empty list. from the python source: if (PyTuple_Size(args) <= 1) { if (!PyArg_ParseTuple(args, "l;range() requires 1-3 int arguments", &ihigh)) return NULL; } else { if (!PyArg_ParseTuple(args, "ll|l;range() requires 1-3 int arguments", &ilow, &ihigh, &istep)) return NULL; } Look at the last arguments to each funtion. If one argument is passed it because the high value (endpoint). Otherwise the values are assigned in order to low, high and then step (which defaults to 1). From wmistar at yahoo.com Sat Mar 16 23:55:43 2002 From: wmistar at yahoo.com (Will G.) Date: 16 Mar 2002 20:55:43 -0800 Subject: Python calling C with callback to Python - crash! Message-ID: I know I'm rather demented to write something like this: A.py calls B.dll using dynwin (windll) B.dll has a callback to C.py and potentially calling it repeatedly. When I run A.py, the callback is successfully called until it's last invocation when "bam!!" python.exe crashes spectacularly. I know the problem is on Python's side because when I use a C program to invoke the B.dll, the callback to C.py is called and executed flawlessly. Appreciate any help! Will G. PS: Here's the callback code, it's adapted (almost verbatim) from the python on embedding doc: Py_Initialize(); pName = PyString_FromString(HCFAMGR_MODULE); /* Error checking of pName left out */ pModule = PyImport_Import(pName); if (pModule != NULL) { pDict = PyModule_GetDict(pModule); /* pDict is a borrowed reference */ pFunc = PyDict_GetItemString(pDict, PYTHON_FUNCTION); /* pFun: Borrowed reference */ if (pFunc && PyCallable_Check(pFunc)) { // WG - Specify the number of parameter we're going to pass to this // function pArgs = PyTuple_New(4); // WG - Set the main claim as first argument (LPTSTR) pValue = PyString_FromString(charptrToHCFA); if (!pValue) fprintf(stderr, "Can't pass claim\n"); PyTuple_SetItem(pArgs, 0, pValue); ... (finish assigning the parameters) // WG - Call the Python function pValue = PyObject_CallObject(pFunc, pArgs); if (pValue != NULL) { result = PyInt_AsLong(pValue); Py_DECREF(pValue); } else { PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } Py_DECREF(pArgs); /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */ } else { PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", PYTHON_FUNCTION); } Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", HCFAMGR_MODULE); return 1; } Py_DECREF(pName); Py_Finalize(); From mlh at vier.idi.ntnu.no Mon Mar 25 08:39:21 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 25 Mar 2002 13:39:21 +0000 (UTC) Subject: Streaming XML-RPC? Message-ID: I'm thinking about implementing a library that uses the xml-part of XML-RPC (i.e. XML-RPC without the HTTP) in two-way persistent stream (tcp socket) somewhat like Jabber, to improve performance. (Although I haven't tested it yet, it seems that HTTP must be one of the performance killers in XML-RPC.) My original idea was to let only requests go in one direction, and responses in the other -- but I guess mixing requests and responses in both directions might be useful as well, perhaps? That way the client wouldn't need to run a socket server to be able to receive calls from the server. Before I start playing with this -- has anyone else done similar things? Are there such implementations available already? Is it a futile project? And if there are no implementations for Python -- perhaps there are for some other languages? -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From garrett at bgb-consulting.com Mon Mar 25 18:14:57 2002 From: garrett at bgb-consulting.com (Don Garrett) Date: Mon, 25 Mar 2002 23:14:57 GMT Subject: Streaming XML-RPC? References: <3C9F51EE.5000203@jerf.org> Message-ID: <3C9FAF96.5DE9A0@bgb-consulting.com> Okay, I admit I haven't gone looking yet, but.... Are there any decent (finished/tested) Jabber libraries for Python? Jeremy Bowers wrote: > > Magnus Lie Hetland wrote: > > I'm thinking about implementing a library that uses the xml-part of > > XML-RPC (i.e. XML-RPC without the HTTP) in two-way persistent stream > > (tcp socket) somewhat like Jabber, to improve performance. > > Why not Jabber? Jabber is meant to do that. It's designed to do that. > It's *begging* you to use it that way. > > This is in stark contrast to HTTP. HTTP thinks you're nuts. HTTP will > fight you tooth and nail. HTTP is old, and hoary, and set in her ways. > And XML-RPC isn't exactly ecstatic about being streamed, either. > > Why fight the system when you can work with another one? -- Don Garrett http://www.bgb.cc/garrett/ BGB Consulting garrett at bgb.cc From akuchlin at ute.mems-exchange.org Fri Mar 22 15:55:07 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 22 Mar 2002 20:55:07 GMT Subject: "Zope-certified Python Engineers" [was: Java and Python] References: Message-ID: In article , Laura Creighton wrote: > One days reading of your weeks spam will yield you many offers of > programs and advice on how to make your website rise in the Google > ranking. This reflects the reality that once you have made it to the Rule #1 when dealing with spam: Spammers lie. I doubt any of those offers would actually result in any useful information or visible effect on your ranking. Absent Scientology-scale creation of fake links, the only way is to update your site often and to get other people to link to you. > EBay has one sort of approach. So does Advogato (see http://advogato.org ). > It is a real problem and one that interests me a lot. At the Web services panel at Python10, Tim Berners-Lee mourned that third-party Web annotation tools such as crit.org or the commercial Third Voice have never really caught on. Probably this is because, as he suggested, the UI would be really complicated, because we already have the technical pieces needed. Consider your example of a buggy formula on a Web page. Perhaps someone has noted this error on some annotation service, but on which one? The W3C's? crit.org? The American Mathematical Society? You probably can't just pick one for the whole Web, because the AMS annotations probably don't comment on X-Files Web pages much (or particularly well). Instead you'd need a complex set of preferences -- use the AMS for mathematical pages, use the MEMS Exchange for MEMS-related pages, and so forth. This quickly gets really messy. Who annotates a finite-element analysis of a MEMS structure? Both services, or just one? And how do you tell if a page is mathematical, anyway? Or will I constantly telling my browser which service to use for each URL, in a never-ending task. (You could have a annotation service that just classified pages, of course.) A widely adopted solution would bring us much closer to Ted Nelson's vision of a hyperlinked repository of all knowledge, but getting there seems very, very difficult. --amk (www.amk.ca) Beware the devious Calib. One day he'll get so cunning even he won't know what he's planning. -- Leela, in "The Face of Evil" From cbbrowne at acm.org Mon Mar 11 19:29:15 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 11 Mar 2002 19:29:15 -0500 Subject: python and haskell for fun References: Message-ID: Kendall Clark wrote: > >>>>> "sandy" == Sandy Norton writes: > > sandy> "Patrick" wrote: > >> This subset of PASKELL will be clean, beautiful and functional. > > sandy> I'm sorry I wasn't clear. I meant 'beget a pretty monster' of > sandy> an application, not a language. The last thing I would want > sandy> to do is waste time discussing a new hybrid 'PASKELL' > sandy> language... > > I've been daydreaming for about a year of a Python implementation > written in Haskell, which would obviously make writing Python > extensions in Haskell easier (and more elegant, IMO, than writing them > in C or Java). > > However, John Paul Skaller did something similar with Ocaml, which he > called Vyper, and that went over in the Py world like a leaden balloon > -- actually it went over about as poorly as Stackless Python did; > which does cause me to wonder what it is about Python culture, if > anything, that's resistant to unusual alternative implementations?. A > Python implementation in Haskell is probably a fool's task. Though > given the various Haskell compilers, including some pretty impressive > parallelizing stuff, it is an interesting idea. > > (Ocaml is pretty much Caml + objects; Caml is INRIA's implementation > of ML; in the neighborhood of Haskell, but less syntactially elegant, > IMO.) > > At least, a Haskell implementation of Python seems more practical than > a Python implementation of Haskell, which would be rather toylike. But > YMMV. I'd love to see Vyper go further; it's a neat approach to the "wouldn't it be neat to static type Python?" question. The thing that seemed particularly neat was the way it added in ML-style pattern matching. I have a feeling that what has happened isn't so much that people started farting in the author's general direction ("your mother smells like elderberries!"), but that it was a one man show, and that nobody really took interest in it. In effect, it may be just like most of the SourceForge projects that get started up by someone that thinks they have an idea, but who never get around to any usable degree of completion. Alternatively, it could be compared to SOAP implementations on Python. The wonderful thing about SOAP on Python is that there are so many implementations to choose from. Unfortunately, most of them got about half-way through, and authors' companies got lost in the wastelands of the "Internet Bubble." And so we have a whole bunch of implementations, most of which are completely unmaintained. (Compare to Perl's SOAP::Lite...) -- (reverse (concatenate 'string "gro.gultn@" "enworbbc")) http://www3.sympatico.ca/cbbrowne/python.html From python at rcn.com Fri Mar 22 16:53:23 2002 From: python at rcn.com (Raymond Hettinger) Date: Fri, 22 Mar 2002 16:53:23 -0500 Subject: [ANN] PEP 279 updated to version 1.8 Message-ID: PEP 279 has been reposted with the following changes: -- Fixed indentation error in the logger() function. -- Changed variable names in indexed() to start and stop. -- Generator parameter passing proposal moved to a separate PEP (not yet posted) -- Added comments and voting results from the community. -- Revised the author response to comments Note, this PEP has been submitted to GvR for pronouncement. Raymond Hettinger From deltapigz at telocity.com Sat Mar 9 17:33:32 2002 From: deltapigz at telocity.com (Adonis Vargas) Date: Sat, 9 Mar 2002 17:33:32 -0500 Subject: Tkinter + Button widget Message-ID: <3c8a928e$1_2@nopics.sjc> when i start a button widget, it automatically fires the command? def HideNewClient(self, frame): frame.configure(bd=0, width=0, height=0) return pdb_btnSearch = Button(pdb_frmCommands, text="Search", relief=GROOVE, font=("Tahoma", 10), width=16, command=self.HideNewClient(pdb_frmNewClient)) any help would greatly be appreciated. Adonis From peter at engcorp.com Sat Mar 30 12:42:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 30 Mar 2002 12:42:39 -0500 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> Message-ID: <3CA5F90F.BF37B528@engcorp.com> "Martin v. Loewis" wrote: > > Peter Hansen writes: > > > Are there code snippets which clearly have significantly improved > > readability as a result of a rewrite using the proposed bool? > > The standard library has 110 occurrences of "return 0", 70 occurrences > of "return 1", and 136 occurrences of "return None". Optimistically, > this makes 300 functions. It would help users of these 300 functions > if they would know whether those functions return a boolean or an > integral value (if integral, what range?); for the "return None" > cases, the boolean type would help to clarify whether this is "return > no value", "return False", or "return nil object"; So does this change proposes to change the readability so that it is clear at a glance (at the source, not the documentation, which seems an odd thing to base this on) that those functions return boolean conditions rather than integers? If that is _all_ this change does, I suppose it would be okay. If it in _any way_ changes the functionality one can currently expect for those return values, such as the ability to use as indices into a sequence, then I'm still very -1. I like Greg's response too. The improved readability does not appear to outweigh the disadvantages of making Python's special behaviour clear. Furthermore, there will be code breakage, and that should always rate very high on the list of reasons to leave well enough alone. -Peter From James_Althoff at i2.com Fri Mar 8 15:50:47 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 8 Mar 2002 12:50:47 -0800 Subject: PEP 276 final version Message-ID: Included below is the final version of PEP 276. For those interested, I changed the "issues" section to include the concerns that came up in recent discussions on this list. In light of the "Parade of PEPS" message, I also have asked the PEP administrator to move PEP 276 to the withdrawn/rejected group. Many thanks to all who participated in the PEP 276 discussions. Jim Althoff Senior Vice President i2 Technologies, Inc. ===================================================== PEP: 276 Title: Simple Iterator for ints Author: james_althoff at i2.com (Jim Althoff) Type: Standards Track Created: 12-Nov-2001 Python-Version: 2.3 Abstract Python 2.1 added new functionality to support iterators[1]. Iterators have proven to be useful and convenient in many coding situations. It is noted that the implementation of Python's for-loop control structure uses the iterator protocol as of release 2.1. It is also noted that Python provides iterators for the following builtin types: lists, tuples, dictionaries, strings, and files. This PEP proposes the addition of an iterator for the builtin type int (types.IntType). Such an iterator would simplify the coding of certain for-loops in Python. Specification Define an iterator for types.intType (i.e., the builtin type "int") that is returned from the builtin function "iter" when called with an instance of types.intType as the argument. The returned iterator has the following behavior: - Assume that object i is an instance of types.intType (the builtin type int) and that i > 0 - iter(i) returns an iterator object - said iterator object iterates through the sequence of ints 0,1,2,...,i-1 Example: iter(5) returns an iterator object that iterates through the sequence of ints 0,1,2,3,4 - if i <= 0, iter(i) returns an "empty" iterator, i.e., one that throws StopIteration upon the first call of its "next" method In other words, the conditions and semantics of said iterator is consistent with the conditions and semantics of the range() and xrange() functions. Note that the sequence 0,1,2,...,i-1 associated with the int i is considered "natural" in the context of Python programming because it is consistent with the builtin indexing protocol of sequences in Python. Python lists and tuples, for example, are indexed starting at 0 and ending at len(object)-1 (when using positive indices). In other words, such objects are indexed with the sequence 0,1,2,...,len(object)-1 Rationale A common programming idiom is to take a collection of objects and apply some operation to each item in the collection in some established sequential order. Python provides the "for in" looping control structure for handling this common idiom. Cases arise, however, where it is necessary (or more convenient) to access each item in an "indexed" collection by iterating through each index and accessing each item in the collection using the corresponding index. For example, one might have a two-dimensional "table" object where one requires the application of some operation to the first column of each row in the table. Depending on the implementation of the table it might not be possible to access first each row and then each column as individual objects. It might, rather, be possible to access a cell in the table using a row index and a column index. In such a case it is necessary to use an idiom where one iterates through a sequence of indices (indexes) in order to access the desired items in the table. (Note that the commonly used DefaultTableModel class in Java-Swing-Jython has this very protocol). Another common example is where one needs to process two or more collections in parallel. Another example is where one needs to access, say, every second item in a collection. There are many other examples where access to items in a collection is facilitated by a computation on an index thus necessitating access to the indices rather than direct access to the items themselves. Let's call this idiom the "indexed for-loop" idiom. Some programming languages provide builtin syntax for handling this idiom. In Python the common convention for implementing the indexed for-loop idiom is to use the builtin range() or xrange() function to generate a sequence of indices as in, for example: for rowcount in range(table.getRowCount()): print table.getValueAt(rowcount, 0) or for rowcount in xrange(table.getRowCount()): print table.getValueAt(rowcount, 0) From time to time there are discussions in the Python community about the indexed for-loop idiom. It is sometimes argued that the need for using the range() or xrange() function for this design idiom is: - Not obvious (to new-to-Python programmers), - Error prone (easy to forget, even for experienced Python programmers) - Confusing and distracting for those who feel compelled to understand the differences and recommended usage of xrange() vis-a-vis range() - Unwieldy, especially when combined with the len() function, i.e., xrange(len(sequence)) - Not as convenient as equivalent mechanisms in other languages, - Annoying, a "wart", etc. And from time to time proposals are put forth for ways in which Python could provide a better mechanism for this idiom. Recent examples include PEP 204, "Range Literals", and PEP 212, "Loop Counter Iteration". Most often, such proposal include changes to Python's syntax and other "heavyweight" changes. Part of the difficulty here is that advocating new syntax implies a comprehensive solution for "general indexing" that has to include aspects like: - starting index value - ending index value - step value - open intervals versus closed intervals versus half opened intervals Finding a new syntax that is comprehensive, simple, general, Pythonic, appealing to many, easy to implement, not in conflict with existing structures, not excessively overloading of existing structures, etc. has proven to be more difficult than one might anticipate. The proposal outlined in this PEP tries to address the problem by suggesting a simple "lightweight" solution that helps the most common case by using a proven mechanism that is already available (as of Python 2.1): namely, iterators. Because for-loops already use "iterator" protocol as of Python 2.1, adding an iterator for types.IntType as proposed in this PEP would enable by default the following shortcut for the indexed for-loop idiom: for rowcount in table.getRowCount(): print table.getValueAt(rowcount, 0) The following benefits for this approach vis-a-vis the current mechanism of using the range() or xrange() functions are claimed to be: - Simpler, - Less cluttered, - Focuses on the problem at hand without the need to resort to secondary implementation-oriented functions (range() and xrange()) And compared to other proposals for change: - Requires no new syntax - Requires no new keywords - Takes advantage of the new and well-established iterator mechanism And generally: - Is consistent with iterator-based "convenience" changes already included (as of Python 2.1) for other builtin types such as: lists, tuples, dictionaries, strings, and files. Backwards Compatibility The proposed mechanism is generally backwards compatible as it calls for neither new syntax nor new keywords. All existing, valid Python programs should continue to work unmodified. However, this proposal is not perfectly backwards compatible in the sense that certain statements that are currently invalid would, under the current proposal, become valid. Tim Peters has pointed out two such examples: 1) The common case where one forgets to include range() or xrange(), for example: for rowcount in table.getRowCount(): print table.getValueAt(rowcount, 0) in Python 2.2 raises a TypeError exception. Under the current proposal, the above statement would be valid and would work as (presumably) intended. Presumably, this is a good thing. As noted by Tim, this is the common case of the "forgotten range" mistake (which one currently corrects by adding a call to range() or xrange()). 2) The (hopefully) very uncommon case where one makes a typing mistake when using tuple unpacking. For example: x, = 1 in Python 2.2 raises a TypeError exception. Under the current proposal, the above statement would be valid and would set x to 0. The PEP author has no data as to how common this typing error is nor how difficult it would be to catch such an error under the current proposal. He imagines that it does not occur frequently and that it would be relatively easy to correct should it happen. Issues: Extensive discussions concerning PEP 276 on the Python interest mailing list suggests a range of opinions: some in favor, some neutral, some against. Those in favor tend to agree with the claims above of the usefulness, convenience, ease of learning, and simplicity of a simple iterator for integers. Issues with PEP 276 include: - Using range/xrange is fine as is. Response: Some posters feel this way. Other disagree. - Some feel that iterating over the sequence "0, 1, 2, ..., n-1" for an integer n is not intuitive. "for i in 5:" is considered (by some) to be "non-obvious", for example. Some dislike this usage because it doesn't have "the right feel". Some dislike it because they believe that this type of usage forces one to view integers as a sequences and this seems wrong to them. Some dislike it because they prefer to view for-loops as dealing with explicit sequences rather than with arbitrary iterators. Response: Some like the proposed idiom and see it as simple, elegant, easy to learn, and easy to use. Some are neutral on this issue. Others, as noted, dislike it. - Is it obvious that iter(5) maps to the sequence 0,1,2,3,4? Response: Given, as noted above, that Python has a strong convention for indexing sequences starting at 0 and stopping at (inclusively) the index whose value is one less than the length of the sequence, it is argued that the proposed sequence is reasonably intuitive to the Python programmer while being useful and practical. More importantly, it is argued that once learned this convention is very easy to remember. Note that the doc string for the range function makes a reference to the natural and useful association between range(n) and the indices for a list whose length is n. - Possible ambiguity for i in 10: print i might be mistaken for for i in (10,): print i Response: This is exactly the same situation with strings in current Python (replace 10 with 'spam' in the above, for example). - Too general: in the newest releases of Python there are contexts -- as with for-loops -- where iterators are called implicitly. Some fear that having an iterator invoked for an integer in one of the context (excluding for-loops) might lead to unexpected behavior and bugs. The "x, = 1" example noted above is an a case in point. Response: From the author's perspective the examples of the above that were identified in the PEP 276 discussions did not appear to be ones that would be accidentally misused in ways that would lead to subtle and hard-to-detect errors. In addition, it seems that there is a way to deal with this issue by using a variation of what is outlined in the specification section of this proposal. Instead of adding an __iter__ method to class int, change the for-loop handling code to convert (in essense) from for i in n: # when isinstance(n,int) is 1 to for i in xrange(n): This approach gives the same results in a for-loop as an __iter__ method would but would prevent iteration on integer values in any other context. Lists and tuples, for example, don't have __iter__ and are handled with special code. Integer values would be one more special case. - "i in n" seems very unnatural. Response: Some feel that "i in len(mylist)" would be easily understandable and useful. Some don't like it, particularly when a literal is used as in "i in 5". If the variant mentioned in the response to the previous issue is implemented, this issue is moot. If not, then one could also address this issue by defining a __contains__ method in class int that would always raise a TypeError. This would then make the behavior of "i in n" identical to that of current Python. - Might dissuade newbies from using the indexed for-loop idiom when the standard "for item in collection:" idiom is clearly better. Response: The standard idiom is so nice when it fits that it needs neither extra "carrot" nor "stick". On the other hand, one does notice cases of overuse/misuse of the standard idiom (due, most likely, to the awkwardness of the indexed for-loop idiom), as in: for item in sequence: print sequence.index(item) - Why not propose even bigger changes? The majority of disagreement with PEP 276 came from those who favor much larger changes to Python to address the more general problem of specifying a sequence of integers where such a specification is general enough to handle the starting value, ending value, and stepping value of the sequence and also addresses variations of open, closed, and half-open (half-closed) integer intervals. Many suggestions of such were discussed. These include: - adding Haskell-like notation for specifying a sequence of integers in a literal list, - various uses of slicing notation to specify sequences, - changes to the syntax of for-in loops to allow the use of relational operators in the loop header, - creation of an integer-interval class along with methods that overload relational operators or division operators to provide "slicing" on integer-interval objects, - and more. It should be noted that there was much debate but not an overwhelming concensus for any of these larger-scale suggestions. Clearly, PEP 276 does not propose such a large-scale change and instead focuses on a specific problem area. Towards the end of the discussion period, several posters expressed favor for the narrow focus and simplicity of PEP 276 vis-a-vis the more ambitious suggestions that were advanced. There did appear to be concensus for the need for a PEP for any such larger-scale, alternative suggestion. In light of this recognition, details of the various alternative suggestions are not discussed here further. Implementation An implementation is not available at this time but is expected to be straightforward. The author has implemented a subclass of int with an __iter__ method (written in Python) as a means to test out the ideas in this proposal, however. References [1] PEP 234, Iterators http://python.sourceforge.net/peps/pep-0234.html [2] PEP 204, Range Literals http://python.sourceforge.net/peps/pep-0204.html [3] PEP 212, Loop Counter Iteration http://python.sourceforge.net/peps/pep-0212.html Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil fill-column: 70 End: From logiplexsoftware at earthlink.net Fri Mar 15 17:51:03 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 15 Mar 2002 14:51:03 -0800 Subject: Parsing string into fixed-width pieces In-Reply-To: <412F4D3C5614D211853600A0C99E563F0D0D80ED@com83-173.medicine.uiowa.edu> References: <412F4D3C5614D211853600A0C99E563F0D0D80ED@com83-173.medicine.uiowa.edu> Message-ID: <20020315145103.568623a3.logiplexsoftware@earthlink.net> On Fri, 15 Mar 2002 14:44:45 -0600 Johnson, Brad wrote: > Hello, > > I'm new to Python and have been combing the documentation and the message > archive here for information on splitting a string into fix-width pieces. I > assume their is an easy way to do this, I just don't seem to be able to find > it in the reference material. Any suggestions? Just use slices: >>> s = "Hello, World" >>> s[1] 'e' >>> s[2:4] 'll' >>> s[3:] 'lo, World' >>> To split it up into 4 pieces of length 3 (assuming your lengths are all the same): >>> l = 3 >>> for slice in range(0, len(s), l): ... print s[slice:slice + l] ... Hel lo, Wo rld >>> -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From holger at trillke.net Thu Mar 21 21:22:53 2002 From: holger at trillke.net (holger at trillke.net) Date: Fri, 22 Mar 2002 03:22:53 +0100 Subject: __file__ for relative imports In-Reply-To: ; from pinard@iro.umontreal.ca on Thu, Mar 21, 2002 at 08:17:26PM -0500 References: Message-ID: <20020322032253.B13555@prim.han.de> > There is another tiny bit in that area which might be debated as well. > > `__file__' is not defined for the `__main__' module. But `sys.argv[0]' in > that case contains the information one might have hoped out of `__file__'. > I would like if `__file__' was just dependably defined in all circumstances, > the best the Python interpreter can. If this was done, the programmer would > then not have to resort anymore to convoluted code for finding the directory > and file for the current module. also inspect.getsourcelines and friends should work inside __main__. I mean if you define a class in an module file you can get the source via "inspect" but not so if (the same) file is executed as __main__. At least i don't currently understand why this is so. Maybe because __main__ *can* mean that you are reading from stdin (e.g. python prompt)? Maybe it's because __file__ is not defined :-) I'd really like to know ... holger krekel From news at 92tr.freeserve.co.uk Sat Mar 2 14:29:08 2002 From: news at 92tr.freeserve.co.uk (ddoc) Date: Sat, 2 Mar 2002 19:29:08 +0000 Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: > I'm looking for a piece of software to aid in reviewing a document > through the web - click on a paragraph tag, have the comment added > (highlighted in some way). Is this what Annotea (Annotation server from the W3C), Third Voice (now defunct , and to a lesser extent Allegra are for? -- A From mlh at vier.idi.ntnu.no Tue Mar 19 20:48:30 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Wed, 20 Mar 2002 01:48:30 +0000 (UTC) Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: In article , Chris Liechti wrote: >mlh at vier.idi.ntnu.no (Magnus Lie Hetland) wrote in >news:slrna9fkli.9ti.mlh at vier.idi.ntnu.no: > [snip] > >as i understand py2exe it does exactly that. it adds a new target >"py2exe" so that disutils have a new target name. > >i.e "python setup.py py2exe" generates the exe+dlls in the dist dir Yes, I realise that, but... 1. It only works on Windows; working on all platforms (as when compiling extensions with distutils) would be desirable; 2. It's not a part of distutils (in the standard distribution). My hope was that perhaps one day it would be possible (with a standard Python installation) to create executables directly... >-- >Chris > - Magnus (who also is a bit baffled as to why distutils doesn't include an "uninstall" command, such as the one implemented by Thomas Heller.) -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From d95-bli.no at spam.nada.kth.se Thu Mar 21 19:23:26 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-1?Q?Bj=F6rn?= Lindberg) Date: Fri, 22 Mar 2002 01:23:26 +0100 Subject: Popular style document? References: <1016641355.370859@cswreg.cos.agilent.com> Message-ID: <3C9A797E.E6476BEE@spam.nada.kth.se> phil hunt wrote: > IMO the requirement to say self everywhere in methods is the worst > feature of python. How come Python doesn't have an "automatic" this-variable, like C++ or Java? Bj?rn From jcosby at mindspring.com Fri Mar 29 18:43:07 2002 From: jcosby at mindspring.com (Jon Cosby) Date: Fri, 29 Mar 2002 15:43:07 -0800 Subject: List problem References: <3CA4E7C6.EDE85B98@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3CA4E7C6.EDE85B98 at engcorp.com... > > firstword = input("Enter first word (enclosed in quotes): ") #Word to build from > > lword = len(firstword) #Word length > > words = [] # Dictionary list > > cols = [] #Columns > > rows = [] #Rows > > Comments might help a lot. For example, it's unclear what you are > trying to accomplish here, but it doesn't look quite right: > > > f = open(dict, "r") > > for line in f.readlines(): > > if len(line[:-1]) == lword: > > words.append(line[:-1]) #Retrieve words of length lword > > f.close() > > That finds the line matching lword and appends it to words, I think, > which is another way of saying that every instance of lword in the > dict.txt file will be appended to the words list. Strange... > > > for i in range(lword): > > cols.append([]) > > rows.append([]) > > rows[0].append(firstword) > > For every character in lword, append an empty list to the rows > and columns? If that's what you want, you need range(len(lword)) > since range() takes an integer. Didn't you get an exception > here? No, lword is the length of the initial word, there is no exception. > > > # Generate an array of words with matching first letters > > for i in range(lword): > > Same problem as above... use len() with range(). > > > for word in words: > > if word[0] == firstword[i]: # Matches not found Here is where it is failing. No matches are being found, but the only criteria is the first letter. I won't post the dictionary, but there are words meeting the criteria. > > cols[i].append(word) > > > > print len(words) > > print cols > > Bad indentation here, but that's probably cosmetic. Try not to > use tabs when posting source, since many newsreaders screw them > up. Use spaces instead. > > Can you annotate your code so we know what you're trying to do? > > -Peter I hope this helps. Sorry for not being more clear before. Jon From akuchlin at ute.mems-exchange.org Wed Mar 27 10:06:35 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 27 Mar 2002 15:06:35 GMT Subject: Random... References: Message-ID: In article , Chris Gonnerman wrote: > Perhaps I'm stupid... what the heck is wrong with the OP's message? Original material was added at the top of the post, and the entire message being responded to was quoted below. Usenet convention is to do it the way I'm writing this message, by quoting only the few lines of text I'm responding to and writing my answer below. Doing this way makes it much easier to pick up a thread in the middle, saves bandwidth, and users reading the digested version of python-list don't have to plow through 187 quoted copies of the same text again and again. I also view top-posting as rude; it implies the top-posting person's time is so valuable they can't be bothered to edit down the quoted text, but it's OK to waste *my* time by making me dig through levels upon levels of quoted material. --amk (www.amk.ca) Burroughs did something very odd with COBOL at one point (and no, it wasn't The Naked Lunch). -- Will Rose, 27 May 2000 From tim.one at comcast.net Mon Mar 11 18:34:38 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 11 Mar 2002 18:34:38 -0500 Subject: python and haskell for fun In-Reply-To: <15501.8911.362214.989320@cmpu.net> Message-ID: [Kendall Clark] > ... > However, John Paul Skaller did something similar with Ocaml, which he > called Vyper, and that went over in the Py world like a leaden balloon > -- actually it went over about as poorly as Stackless Python did; Stackless actually has a loyal base of intense fans, because Stackless does something they want. John started Vyper because he wanted a faster means to execute his InterScript system, but Vyper didn't get far enough along to run faster than CPython. The last word on that appears to be: [from http://vyper.sourceforge.net/] The interpreter Pystone benchmark is currently about 10 times slower than CPython 1.5.2. Considerable improvement is expected in the future. John then segued into changing the language rules in ways that looked more-or-less random to outsiders. > which does cause me to wonder what it is about Python culture, if > anything, that's resistant to unusual alternative implementations? In Vyper's case, "speed" was the big selling point, but it never materialized. Some of his other experiments have since gotten into the Python core, though (like list comprehensions). In Stackless's case, the relative handful of people who need ultra-lightweight "tasklets" were, and still are, delighted with it. JPython has *many* users, and if you don't think reimplementing Python in Java qualifies as an "unusual alternative", you may have been too young at the time . Bottom line: An alternative will catch on to the extent that people actually want what it actually does. > A Python implementation in Haskell is probably a fool's task. Though > given the various Haskell compilers, including some pretty impressive > parallelizing stuff, it is an interesting idea. If you're aiming at speed, don't get distracted by fiddling, and you'll find a large audience -- if you succeed. Something like "20% faster, most of the time" probably wouldn't be enough to get anyone to bother switching, though. let-alone-10x-slower-ly y'rs - tim From logstx at bellatlantic.net Wed Mar 27 17:35:07 2002 From: logstx at bellatlantic.net (logistix) Date: Wed, 27 Mar 2002 22:35:07 GMT Subject: Regex problem ... References: Message-ID: I don't think you can hook a function inside a regex in Python. You probably want to use tagImg.match or tagImg.search to generate a match object, and use that object to build a new string. Of course this can get annoying with really big HTML docs. Check out the standard module HTMLparser if you want to break the docs into smaller chunks before processing. -- - "Barghest" wrote in message news:a7s3lu$qfq$1 at reader1.imaginet.fr... > Hello, > import re > tagImg = re.compile( r"""(]*>)""", > re.IGNORECASE | re.MULTILINE | re.DOTALL ) > > Wanna match ... and replace > it by > > > the problem is that i don't know how to lowercase the \g<2> part > bp2.write( tagImg.sub( '\g<1>\g<2>\g<3>', buff ) ) > > I tried > tagImg.sub( string.lower( '\g<1>\g<2>\g<3>' ), buff ) > but it doesen't work .. > > Any idea ? > > From fredrik at pythonware.com Sun Mar 17 07:58:02 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 17 Mar 2002 12:58:02 GMT Subject: xmlrpclib.Server vs xmlrpclib.ServerProxy References: Message-ID: Bengt Richter wrote: > >the original code used Server -- after all, the object is > >representing a remote server. > ^^^^^^^^^^^^ > But not functioning as? if you look at it strictly from the client end, that object represents, functions as, and for all practical purposes *is* the server. the fact that the actual service provider might be running on another machine is almost entirely irrelevant. # client configuration # define what services we'll use later on spam = xmlrpclib.Server[Proxy](URL) egg = Egg() # local # # client implementation spam.cook() egg.fry() > This is in good part an English usage issue, but > IMO the term 'proxy' should not be used except when the > proxy duplicates the function and stands transparently > in place of that for which it is a proxy. in this case, the term is used in its GOF sense: the ServerProxy object is a "remote proxy", a "local representative for an object in a different address space". (strictly speaking, the server wrapper creates method proxies on demand, and it's the method proxy that talks to the remote server, but that's an implementation detail) From aahz at panix.com Sun Mar 3 12:51:51 2002 From: aahz at panix.com (Aahz Maruch) Date: 3 Mar 2002 09:51:51 -0800 Subject: Stackless Platform Independence? References: <987e7uoo5v87fsjruq0ug6bff0vha5ear0@4ax.com> Message-ID: In article , Frederic Giacometti wrote: > >In addition to all the benefits that Christian has described so far, >stackless python would make it possible to have a different OS >multi-threading implementation for calling external C/C++ libraries; one >that does not require interpreter lock operations. > > [...] > >Stackless just means that function calls executed by the bytecode are >executed by a C function that returns immediately; thus disconnecting >the C call stack from the virtual machine call stack. In current >python, they are interleaved one-on-one; making it impossible to switch >context within the VM unnless you do Christian's last 'non-portable' >assembly language manipulation. How's that again? In the absence of pre-emptive thread scheduling, what good is the immediate return from the C function? More than that, how can you possibly call external libraries without the interpreter lock, if those libraries have any access to Python variables? If they *don't* have access to Python, how is that any different from just using the macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS? -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From skip at pobox.com Sun Mar 10 11:27:07 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 10 Mar 2002 10:27:07 -0600 Subject: range Failure? In-Reply-To: <3C8B84B6.DB3F8E9A@sympatico.ca> References: <3C8B84B6.DB3F8E9A@sympatico.ca> Message-ID: <15499.35163.932422.622100@12-248-41-177.client.attbi.com> Colin> What you say is, on reflection, obvious. Perhaps the doc could Colin> better bring this out? Yes. Can you please file a bug on SourceForge with your suggested wording change? Thx, -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) "As often happens in Net communities, people find all kinds of energy to compose incisive criticisms of the threads and postings of other members, when they could be directing that energy towards brilliant new threads and postings of their own." - Tom Neff From miah at picsel.com Mon Mar 4 06:47:03 2002 From: miah at picsel.com (Miah Gregory) Date: Mon, 04 Mar 2002 11:47:03 GMT Subject: cross platform (linux/windows) problem References: Message-ID: In message David Bolen wrote: > Miah Gregory writes: > > Simple example which works for linux: > You may need to have some per-platform support, since I do think you > need to use the popen2.Popen3 class under Unix to get exit codes, but > that isn't supported under Windows. Strangeness.. I'm getting exit codes under windows ok, just not in the expected format. This is with os.popen3. > Note that your sample Linux code might have a problem in that you > don't drain the output from the piped child until you've gotten an > exit code, but if the child generates more output than the system > pipes can buffer, the child may block and never exit until you drain > the data. Unless you know the output from the child is limited, I'd > suggest draining the data as it runs (even if you just save it for > later use). As far as output goes, I'm only expecting about 1k of text, max. If it does start to play up, I'll start reading, as you suggest. > Under Windows, you should just be able to use os.popen3 directly. Do > the same draining of data until the process exits. Then close the > files you received from os.popen3 - the final one you close (from the > full set of stdin/stdout/stderr) will return the exit code of the > child process. Yes, os.popen3 seems to work fine. Unfortunately, it's not available in python 1.5.2, which I have on my linux machine. -- Miah Gregory From Ken.Peek at Engineer.com Thu Mar 28 12:14:47 2002 From: Ken.Peek at Engineer.com (Ken Peek) Date: 28 Mar 2002 09:14:47 -0800 Subject: I am Tarage your new ruler References: <1eg4au4ntod5fe1u1eu91k51n8aovsn6gd@4ax.com> Message-ID: Lou Moran wrote in message news: > > On Sun, 24 Mar 2002 18:46:44 GMT, "Tarage" > > wrote a glowing report about my Usenet practices: > > > > That's right you stupid, inbred, > > OK You win. Can you write a Perl script to amend my signature? {...kids...} From tejarex at yahoo.com Wed Mar 20 12:20:30 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Wed, 20 Mar 2002 17:20:30 GMT Subject: Remove empty lines References: <3C98C025.7741BA58@ifi.uio.no> Message-ID: "Kristin Skoglund" wrote in message news:3C98C025.7741BA58 at ifi.uio.no... > I am trying to make a script that reads javafiles and remove comments > and empty lines. The script looks like this...... > lines=re.split("\n",str) > for line in lines: # Here I try to remove the emty lines > if line== '': > continue > elif empty: > continue What is empty? Not set in code you posted > else: > tmp.append(line) # not needed for example > newfile.write(line) > ...and everything works except the removal of empty lines. Does anyone > knoe whats wrong? No. I would make a file with known contents: completely blank, with spaces, same part with comments, bracketed by nonblank lines. Then print out before or after split to see what have after comment-removing substitution. Terry J. Reedy From bosahv at netscapenospam.net Wed Mar 20 21:13:58 2002 From: bosahv at netscapenospam.net (Bo Vandenberg) Date: Thu, 21 Mar 2002 02:13:58 GMT Subject: Python Helping Human Rights Message-ID: Wired http://www.wired.com/news/politics/0,1283,51106,00.html has an article about Patrick Ball who gathers and manages information about human rights abuses. "With the methodical manner of a forensic examiner who uses statistics and open-source software instead of scalpels and x-rays, Ball undermined Milosevic's claim that NATO and rebel forces -- and not Milosevic's own Serb army -- caused ethnic Albanian deaths and displacement in Kosovo." He used Python and MySQL to graph the rate and timing of the Kosovo murders and expulsions. "At the trial in The Hague, Ball -- a sociologist, statistician and coder -- told the court that when he mapped the locations of the deaths and the patterns of the refugee flows out of Kosovo in 1999, he saw an unmistakable method in how they occurred over time and space." He says that open source software is ideal because work in it is easily reproduced, and there is a far lower price barrier for poorer nations\organizations. What an accolade for open source and Python. Makes me feel good to be working in this software. Bo From uwe at rocksport.de Wed Mar 27 05:07:57 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 27 Mar 2002 10:07:57 GMT Subject: wxPython and wxFlexGridSizer problem References: <3C9FBE22.A72B4A27@ccvcorp.com> Message-ID: Cliff Wells wrote: | To have it in a frame, simply create another class similar to InputDialog | that uses a wxFrame instead. With this, you can also embed the panel in | something else, for instance a wxNotebook. O.k, thats very helpful and "elegant"... Thanks, Uwe -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From peter at engcorp.com Sat Mar 16 13:43:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 16 Mar 2002 13:43:14 -0500 Subject: Help Setting PATH w/Python and Win98 References: Message-ID: <3C939242.8AF08E5D@engcorp.com> Al wrote: > > I am new to programming and am currently doing a Python Tutorial at > http://softwaredev.earthweb.com/sdopen/article/0,,12382_626311,00.html > > On that page it says I must set the path in Windows to the directory > where the Python.exe is located so that I can execute Python script. > I can get around DOS a bit to do this but not sure how to do it > exactly. Could someone tell me what I must do? If you edit the PATH line in your c:\autoexec.bat file to include the path to the Python directory and reboot, it will work. If the directory is c:\python22 for example, you should add the following to the PATH line: ";c:\python22" (no quotation marks but include the semicolon. For example, you might have SET PATH=c:\windows;c:\windows\command;c:\python22 > Also it says I must make the directory containing my first script file > my CURRENT DIRECTORY from the COMMAND PROMPT IN DOS. How do I do this > too? You open a DOS prompt from the Start menu (Programs-->MSDOS Prompt) and then type 'CD directoryname' where directoryname represents the name of the folder where you saved your script. If this were in My Documents, you would type CD "My Documents" for example (include the quotation marks if there are spaces in the directory name). On the other hand, the DOS environment is really not a very good place for a beginner to work, so I would suggest you investigate using the IDLE development environment instead. If you installed Python properly, your Start menu should include a selection for Python and in that, IDLE. Run that and go from there. Much easier than DOS! Good luck. -Peter From jimd at vega.starshine.org Sun Mar 31 21:37:06 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 1 Apr 2002 02:37:06 GMT Subject: Root access with python References: <7x663krjtp.fsf@ruckus.brouhaha.com> <20020325123855.A1716@ibook.distro.conectiva> Message-ID: In article , Steve Holden wrote: >"Andy Gimblett" wrote in message >news:mailman.1017071438.28406.python-list at python.org... >> On Mon, Mar 25, 2002 at 12:38:55PM -0300, Gustavo Niemeyer wrote: >>> You have several options to do this, and all of them involve setting the >>> setuid bit in some executable. OTOH, setting setuid bit on scripts >>> usually doesn't work. If that's your case, you'll have to freeze your >>> script into a native executable, or build some kind of wrapper. Google >>> for "setuid bit scripts" for more information. >> As a general solution to this kind of problem, sudo is excellent, >> though it might be overkill for this particular case. > The problem is that sudo also required you to authenticate yourself > periodically, albeit as an ordinary user rather than root. I suppose there > may be an option to not require authentication, but any such device is > theoretically dangerous. > As far as setuid scripts goes, just say no. There are far too many security > holes in almost every Unix to think that it's safe to use setuid scripts. > regards > Steve sudo has a "NOPASSWD" modifier that can be selectively added to the /etc/sudoers file to allow specific users or groups to execute specific commands (with some controls over acceptable arguments) without performing any authentication. Naturally this option is necessary for cron jobs and the like. As for your overall "advice." It's of little value to tell someone: "don't do that" without offering any suggestion about what he or she SHOULD try. Whenever discussing computer system security I avoid proscriptive pronouncements like: "you can't do that" or "no one should ..." I start with my definition of "security" (the enforcement of policy) and I ask: what are the policies that need to be enforced. (Policies are requirements that relate of the confidentiality, availability and/or integrity of any resource or resources). From there I look at possible measures (actions taken or techniques employed to prevent, detect or recover from security violations). Finally, I select the measures that make sense (where the estimated level of risk mitigation is proportional to the cost and effort). However, when we recognize policies as just a subset of requirements we also realize that conflicting requirements need resolution. So, the OP has one stated requirement (that his or her CGI script be able to run, including a particular requirement that it run some particular privileged operation). We (in our responses) are inferring a set of *implicit* additional requirements (that the program should not be vulnerable to subversion be otherwise exploitable). When we say, "you can't do that," we're imposing requirements on the OP without regard for his or her other requirements and without regard for any risk assessment or cost/benefit analysis that he or she may have done. Unfortunately I don't know how to make SUID python scripts. In my current ignorance I'd have to recommend sperl with "taint checking," or a sudoers entry, or a small SUID C wrapper program. From fredrik at pythonware.com Sat Mar 16 04:57:02 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 16 Mar 2002 09:57:02 GMT Subject: Why I think range is a wart. References: <7UYj8.31929$l93.6269941@newsb.telia.net> Message-ID: Tim Legant wrote: > I wonder why /F thought the bar() version would be faster. I'm still at 2.1.X. but fwiw, i += 1 is still a wee bit faster under 2.2 on my bench- mark (windows build, 100000 list items, trivial loop body). From caw at cs.mu.oz.au Fri Mar 29 17:52:23 2002 From: caw at cs.mu.oz.au (Chris Wright) Date: Sat, 30 Mar 2002 09:52:23 +1100 Subject: Where's the "news" section on python.org? Message-ID: <496p8.71$l%4.11431@ozemail.com.au> It seems that the "News" section on python.org has vanished from my screen... Anyone else see this? :( Chris Wright From martin at v.loewis.de Mon Mar 18 16:46:16 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Mar 2002 22:46:16 +0100 Subject: python 2.1.2, Linux and 'os' library: bug or (bad) feature? References: Message-ID: Pawel Oleksik writes: > os.execv('/usr/X11R6/bin/X',('X',':'+`display`,)) > > I do expect in the /proc//cmdline a string like: > > 'X\x00:'+`display`+'\x00' > > and in P2.0/P2.1.1 is that. > > What I got with P2.1.2 was: '.X\x00:'+`display`+'\x00' > ^^^ > > Is that a punishment for ours bad behaviour, or what? > Has anybody met this problem? Could you carry out tests with P2.2? I think the is the doing of X itself: start the same program from the shell prompt, and you should observe the same behaviour. Regards, Martin From gminick at hacker.pl Thu Mar 14 13:09:18 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Thu, 14 Mar 2002 18:09:18 +0000 (UTC) Subject: Need advice for obfuscating Python code References: Message-ID: ** Since micro$oft is stupid it doesn't mean ** that you should be stupid too - do NOT toppost. Dnia Tue, 26 Feb 2002 16:23:05 -0600, Skip Montanaro napisa?(a): > Sandeep> I've written a product in Python and I wanted to find out how > Sandeep> best to obfuscate the code. I want the distributed files to be > Sandeep> moderately hard to reverse engineer. >Rewrite in Perl? ;-) Python's code could be obfuscated too. Need an example ? ;) -- [ Wojtek gminick Walczak ][ http://hacker.pl/gminick/ ] [ gminick (at) hacker.pl ][ gminick (at) klub.chip.pl ] From Olav.viken at kmss.no Tue Mar 5 16:59:58 2002 From: Olav.viken at kmss.no (Olav Viken) Date: Tue, 05 Mar 2002 21:59:58 GMT Subject: Pyhon and PIL Message-ID: Hi, I'm using Python Imaging Library (PIL) to convert a lot bmp-files from color to monochrome images. This works, but all images are dithered (grayscale), and what I want is to set "all colors (except white) to black". My code looks something like this: import Image im = Image.open("yellow.bmp") im = im.convert("1", dither=Image.NONE) im.save("yellow.bmp") Anyone? Thanks Olav From James_Althoff at i2.com Mon Mar 18 16:02:48 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 18 Mar 2002 13:02:48 -0800 Subject: [].keys() and [].items() (Was: Why I think range is a wart) Message-ID: [huaiyu] |What I meant was that if you define items(A) to return an iterator, |and write a program using 'for i,x in items(A)', it will work for |any sequence A. Users who supply A do not need to do anything. They have to do *something*. They have to make sure that A supports whatever protocol is assumed in the implementation of the "items" function. That is, A *has* to be a "sequence" or whatever is assumed by items(). |The implementation of items(A) might reuse some of code implementing |the implicit iterators. But it could be as simple as wrapping around |iter(A). | |On the other hand, if you define A.items(), and write a program using |'for i,x in A.items()', it only works if A.items is defined. But that also means that it *will* work if A.items is defined even if A does not implement every "sequence" method. So A.items is *more* general than items(A) in that sense. items(A) becomes more general only if it first tries to call A.items (or A.__items__, or whatever) and failing that then tries to use a sequence or other protocol as a back up. If not, then you are *restricting* things to "sequences" only (or whatever else happens to be hardcoded in the items() function implementation). |If later |on you want to use it for a different kind of A, you have to make sure |it has the right .items() method. This pushes the burden to the users |of the program. Or, depending on how you think of it, it provides *generality* to the users. Jim From shalehperry at attbi.com Sun Mar 31 18:33:04 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sun, 31 Mar 2002 15:33:04 -0800 (PST) Subject: Cannot find what I'm sure is a simple command... please help In-Reply-To: <3ca7978b.251291804@mammoth.usenet-access.com> Message-ID: On 31-Mar-2002 A. Jones wrote: > I seem to have either overlooked, or completely missed a function that > allows one to open a specific line of a file. > > I've read through my Learning Python book, and read the relevent > module docs (anything having to do with files, and the __builtins__). > I must have overlooked such a function. > > I thought the seek() function might work, but it only seems to give me > a byte offset in the file, and not a line number. > there is no way to do this with the libraries shipped with python. An obvious implementation is: def get_desired_line(filename, desired_line): fp = open(filename) lines = fp.readlines() return lines[desired_line - 1] From gimbo at ftech.net Mon Mar 11 08:41:20 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 11 Mar 2002 13:41:20 +0000 Subject: Changing Working Directory in Windows In-Reply-To: <3c8cb05d.221547919@news.earthlink.net> References: <3c8cb05d.221547919@news.earthlink.net> Message-ID: <20020311134120.GG8670@andy.tynant.ftech.net> On Mon, Mar 11, 2002 at 01:28:53PM +0000, nrk at cmcorp.com wrote: > I'm brand new to Python. Can someone tell me how to change a working > directory in a script on a Windows system? Use os.chdir() > What does the pathname specification look like? Like any other pathname specification on your platform. I use linux so it's like '/usr/local/bin', but since you're on Windows, I guess it'd be something like 'C:\WIN32\SYSTEM\' or similar? What does os.getcwd() return? That'll give you a clue as to the format you should use. On my box: >>> import os >>> os.getcwd() '/home/gimbo' Also, check out os.path.split() and os.path.join() (and all the other os.path calls!) for manipulating pathnames in a platform-sensitive manner. > Can I use an absolute path name when referring to a file? Absolutely. :-) For more information on these topics, see: http://www.python.org/doc/current/lib/module-os.html http://www.python.org/doc/current/lib/os-file-dir.html http://www.python.org/doc/current/lib/module-os.path.html -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From jeff at ccvcorp.com Tue Mar 26 17:57:44 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 14:57:44 -0800 Subject: wxPython and wxFlexGridSizer problem References: <3C9FBE22.A72B4A27@ccvcorp.com> Message-ID: <3CA0FCE8.8D8FE0D7@ccvcorp.com> Uwe Schmitt wrote: > Cliff Wells wrote: > > | That may be the case, but Jeff brought up some good points. It looks odd > | to create a window in this fashion (it looks procedural rather than OO). A > | more typical approach would be something like: > > I know what you mean, but I'd like to write a general procedure > which generates an input/output mask based on a relational database > describption. And this mask may appear in a wxFrame *or* a wxDialog. > So I use the "parent" of the mask as a parameter of my function... Then create your controls on a wxPanel, and then add that panel to either your frame or your dialog. The wxPanel will have the added benefit that, even in a frame, it will handle tabbing between controls, etc, correctly. Jeff Shannon Technician/Programmer Credit International From gimbo at ftech.net Mon Mar 11 12:27:43 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 11 Mar 2002 17:27:43 +0000 Subject: Definition problem In-Reply-To: <20020311171132.GD12733@andy.tynant.ftech.net> References: <20020311171132.GD12733@andy.tynant.ftech.net> Message-ID: <20020311172743.GE12733@andy.tynant.ftech.net> OK, forgot to attach the file... Sorry! :-) -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. -------------- next part -------------- #!/usr/bin/env python from MMTK import * from MMTK import Bonds class MyMolecule(Molecule): def __init__(self, name, atoms, bonds): self.atoms = [] self.bonds = [] self.groups = [] self.name = name for element, position in atoms: self.atoms.append(Atom(element, position = position)) for i1, i2 in bonds: self.bonds.append(Bonds.Bond((self.atoms[i1], self.atoms[i2]))) self.bonds = Bonds.BondList(self.bonds) self.parent = None # top-level object self.type = None # no database type h2 = MyMolecule('h2', [('h', Vector(0., 0., -0.05)), ('h', Vector(0.,0., 0.05))], [(0, 1)]) h2.writeToFile('test.pdb') From tdi01fhu at syd.kth.se Wed Mar 27 10:08:58 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Wed, 27 Mar 2002 16:08:58 +0100 Subject: (no subject) Message-ID: >>> Paul Rubin 03/27/02 15:48 PM >>> "FREDRIK HULDTGREN" writes: > I should have been more specific, yes I am talking about cryptology, and > sadly enough I am runnign win2k, the unix stuff goes out the window. As > for how large of numbers I am looking for, I'd say about 512bit numbers > should do it(perhaps larger, depens on how slow it becomes). Got any > URLs that explain Fermat/Miller-Rabin tests? By the way, use gmpy if you can. It's about 10x faster than Python's built-in arithmetic for long modexps. Where can I get gmpy? /fredrik From aahzpy at panix.com Sat Mar 23 02:22:06 2002 From: aahzpy at panix.com (Aahz) Date: 23 Mar 2002 02:22:06 -0500 Subject: sgmlParser infinite loop? How to empty and re-user parser object? References: Message-ID: In article , Nick Arnett wrote: > >I was getting it sometimes every dozen or two documents, but... I >realized I wasn't calling reset properly -- I was leaving off the empty >parentheses, which produces no error, but doesn't actually reset the >object, apparently. That seems to have improved things considerably, >but not completely. Not really up for dealing with your actual question, but I wanted to demonstrate the "bug" you found in a more interesting context: def red(): print "red" def green(): print "green" switch = {'red':red, 'green':green} switch[getColor()]() Fun, huh? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From tdelaney at avaya.com Wed Mar 6 22:58:48 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 7 Mar 2002 14:58:48 +1100 Subject: PEP 284, Integer for-loops Message-ID: > From: Greg Ewing [mailto:greg at cosc.canterbury.ac.nz] > > > Or is it the intention that the construct is *not* limited > strictly to the > > Python builtin classes "int" and "long"? Will it work for > any class that > > defines __lt__, __lg__, __gt__, __ge__, __add__, and > __radd__ methods, for > > example? > > So, floats will have to be treated as a special case, > and if we're having special cases, it would be better to > have *only* special cases -- i.e. restrict it to types > that we'res sure we know enough about to do the right > thing with. That means ints, longints and floats. In that case, I must strongly oppose this PEP. Adding new *syntax* to enhance only a few types in a way which looks nice, but has severe limitations, is IMO the wrong thing to do. As far as I can see, the only advantages to this PEP now are that it looks nicer than range(), and it is easier to construct in some cases. Tim Delaney From cbbrowne at acm.org Sun Mar 10 15:29:37 2002 From: cbbrowne at acm.org (Christopher Browne) Date: Sun, 10 Mar 2002 15:29:37 -0500 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> Message-ID: Centuries ago, Nostradamus foresaw when philh at comuno.freeserve.co.uk (phil hunt) would write: > On Sat, 09 Mar 2002 17:21:39 GMT, Gerson Kurz wrote: >> >>!0,1.!1,1.!2,1.!3,1.,.@?0.!4,?0.!0,?1.~4,?0.!1,?4.~2,?3.!5,?2.A5,10.-5 >> >>will print the first ten fibonacci numbers. > > I wonder what it does in Perl? I don't _want_ to know what it does. I could imagine being curious as to how TECO would cope with it, but not seriously. You might ask the "autocoding" guy if he'd be interested in adding this as an alternative syntax for his scheme; it might well be more readable than other options... -- (concatenate 'string "cbbrowne" "@acm.org") http://www3.sympatico.ca/cbbrowne/emacs.html Rules of the Evil Overlord #135. "My doomsday machine will have the advanced technological device called a capacitor just in case someone inconveniently pulls the plug at the last moment. (If I have access to REALLY advanced technology, I will include the even better back-up device known as the "battery.")" From robin at jessikat.fsnet.co.uk Sun Mar 24 12:16:12 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 24 Mar 2002 17:16:12 +0000 Subject: 2.2 open References: Message-ID: <1UtsCLAcngn8EwWc@jessikat.fsnet.co.uk> In article , Pearu Peterson writes ..... >> >> So open is now a file? That seems a bit odd to me. > >Correction: open is the type of file. > >> It seems that some built ins now have the type of the object they >> create. Pretty weird logic. > >Correction: some built ins are the type of the object they create. > >Notice that in 2.2 types and classes are unified. > yes I heard about that, but the semantics seem strange to me. open is not a file it is a function that produces an open file. It's now not even amongst the built ins. what does X==type(X()) imply? -- Robin Becker From corrado.gioannini at nekhem.com Mon Mar 11 12:29:33 2002 From: corrado.gioannini at nekhem.com (Corrado Gioannini) Date: Mon, 11 Mar 2002 18:29:33 +0100 Subject: lambda question In-Reply-To: <29A97D00F387D411AC7900902770E148044AAFEB@lcoeexc01.coelce.net> References: <29A97D00F387D411AC7900902770E148044AAFEB@lcoeexc01.coelce.net> Message-ID: <20020311182933.B1084@zephyr> On Mon, Mar 11, 2002 at 02:06:51PM -0300, Alves, Carlos Alberto - Coelce wrote: > second code: > > def exe1(f,list): > return map(lambda x:eval(f),list) > > Can someone explain to me why the first code works while second doesn't. try this: def exe1(f, list): return map(lambda x, y=f: eval(y), list) cheers, Corrado -- Corrado Gioannini Nekhem Technologies Tel.: (+39) 011 4407581 - "Thought is only a flash between two long nights, but this flash is everything." (H. Poincar?) From mstenner at phy.duke.edu Fri Mar 15 07:30:10 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 15 Mar 2002 07:30:10 -0500 Subject: line-by-line file read Message-ID: <20020315073010.A13530@phy.duke.edu> OK, so the wonderful flow of the "warty range" thread inspired me to ask the following style question: I often find myself reading and processing a file line-by-line. The way I usually end up doing it goes something like this fo = open(filename) line = fo.readline() while line: # do the processing on "line" here line = fo.readline() fo.close() In perl [this is the way to get responses on this list :)] I would do some variation on open(IN, $filename); while ($line = ) { # do the processing on "$line" here } close(IN); I like the perl way better because it seems inelegant to have the "line =" line repeated, and also because leaving off the second "line =" is a common bug, albeit one that's usually found immediately. Anyway... just wondering if there's a preferred way to do this. -Michael P.S. I'm not trying to start a perl/python thing, really. The only reason I bring it up is I've been porting most of my old perl stuff to python, and this is one of the very few things that seems "nicer" in perl. Much to my surprise, things are often _shorter_ in python, too! -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From khirmint at hotmail.com Wed Mar 13 18:08:19 2002 From: khirmint at hotmail.com (Ken) Date: Wed, 13 Mar 2002 15:08:19 -0800 Subject: Another socket/thread question References: <3C8FA777.8A5B07D1@accessforall.nl> Message-ID: I thought so as well.. but it doesn't seem to. When I call the close () function on the socket object, it just sits there untill I send another keybord interupt. I also tried the socket.shutdown function as well. Would've been an ideal solution though.. "Ype Kingma" wrote in message news:3C8FA777.8A5B07D1 at accessforall.nl... > > > Ken wrote: > > > > Hey everyone.. > > > > I've got a thread that continously listens to a socket, and reports what it > > receives. Blocking is turned on, and I would like it to stay that way since > > the only thing the thread has to do, is listen to the socket. > > > > My question is when the socket needs to be closed (program shuts down, or > > that user is being disconnected by the server) is it possible to interupt a > > socket.recv ()? > > When you close the socket from another thread or by the server, > the pending socket.recv() should terminate with some error condition. > It's best to test both situations, however. > > Have fun, > Ype From andymac at bullseye.apana.org.au Sat Mar 9 19:38:58 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sun, 10 Mar 2002 11:38:58 +1100 (EDT) Subject: broken pipes, import errors (LONG, INVOLVED) In-Reply-To: <20020309071754.GA8360@isis.gerrietts.net> Message-ID: On Fri, 8 Mar 2002, Geoff Gerrietts wrote: > When you try to import a module twice, import just does nothing (or at > least very little) after the first effort. In fact, when you first > import, Python caches a copy of the module in the global namespace. > When you subsequently import, it re-uses that cached copy. > > The cached copy is also corrupt. This sounds nasty if something is diddling with the cached copy. I skimmed, but didn't save, your original posting so the following might have already been answered:- Since it worked, have you... - changed python installations? - changed OS installations? - changed hardware? If any of these changed, describing the before and after environments might be helpfull (longshot though). -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From djc at object-craft.com.au Fri Mar 22 02:31:07 2002 From: djc at object-craft.com.au (Dave Cole) Date: 22 Mar 2002 18:31:07 +1100 Subject: [albatross-users] Re: Python embedded like PHP In-Reply-To: <1016756258.554.46.camel@localhost> References: <20020321235029.B66B438F4C@coffee.object-craft.com.au> <1016756258.554.46.camel@localhost> Message-ID: >>>>> "Ian" == Ian Bicking writes: >> The intention is that Albatross templates be valid XML - while >> Albatross will do the expected thing in the example you give above, >> it generally provides a "better" way, such as: >> >> Ian> Do you mean that you have a template tag for every kind of tag Ian> for which you would want to modify an attribute? That's every Ian> single HTML tag -- IMG is hardly the only one. A dynamic CSS Ian> class attribute, for instance, or events (onMouseOver, etc), id Ian> tags, background colors... there's a million possibilities. I think I can see your point. If I knew the perfect solution I would have tried implementing that. Ian> Plus you've got the same problems ZPT has, where it's not really Ian> proper -- or perhaps even possible -- to dynamically generate CSS Ian> or Javascript with your language, since they are generally Ian> guarded by comments and are thus opaque to XML. Ian> XML just seems so darn *hard*. I tried doing the ZPT thing - it made the template loading run like a slug on valium. You end up with at least one object for every tag and every attribute. With the Albatross templates you only end up with objects for the Albatross tags and attributes. As machines get faster this will not be such an issue. - Dave -- http://www.object-craft.com.au From eric.brunel at pragmadev.com Wed Mar 20 11:01:12 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 20 Mar 2002 16:01:12 +0000 Subject: Process to process synchronization (unix) References: <83pu20ieob.fsf@panacea.canonical.org> Message-ID: Gillou wrote: > I need to learn those named pipes. > Are there pythonic examples somewhere ? Here are an awfully simple example of two scripts speaking to each other. The principle is that the first run creates the named pipe if it doesn't already exist, then opens it and tries either to write something to it, or to read something from it. Here are the two scripts: -- Writing script -------------- import os pipeName = 'np.pipe' ## If named pipe does not exist, create it if not os.path.exists(pipeName): os.mkfifo(pipeName) ## Open pipe and say something through it print "Opening" p = open(pipeName, 'w') print "Sending..." p.write("Wot?") ## Over print "Done." p.close() print "Closed." --------------------------- -- Reading script -------------- import os pipeName = 'np.pipe' ## If named pipe does not exist, create it if not os.path.exists(pipeName): os.mkfifo(pipeName) ## Open pipe and try to read something from it print "Opening" p = open(pipeName, 'r') print "Reading..." s = p.read() ## Over print "Received %s" % s p.close() print "Closed." --------------------------- So the important function here is os.mkfifo, creating the named pipe. It just creates a pseudo-file in the current directory, which can be opened like any other file. But trying to read from it will block until there is some other process writing to it, and the same in reverse: writing is blocking until someone reads at the other end. Try the two scripts: you must run them as 2 different processes (in 2 different xterms, for example). You may start whichever you want first: it will stop, and resume execution only when the other one is started. You may also try to add some time.sleep between the opening and/or reading and see what happens. HTH. Good luck! - eric - From jeff at ccvcorp.com Thu Mar 14 20:28:59 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 14 Mar 2002 17:28:59 -0800 Subject: data persistent from run References: Message-ID: <3C914E5B.FCF22831@ccvcorp.com> Bob Roberts wrote: > What is the best way to keep data like window size and position for > the next time I run the program? I know in win2k, stuff like that is > usually stored in the registry. Are there any python commands to > store such information in a platform-independent manner? IIRC, there's a ConfigParser module in the standard library, that should do what you want. If you're using wxPython, it also includes a wxConfig class, which is what I've used. Jeff Shannon Technician/Programmer Credit International From fpm at u.washington.edu Mon Mar 4 12:07:29 2002 From: fpm at u.washington.edu (Frank Miles) Date: 4 Mar 2002 17:07:29 GMT Subject: Black Adder and PyQt References: Message-ID: In article , Wayne Pierce wrote: > >>>From the BlackAdder readme file: >>>The license of the Beta version prevents run-time components of the >>>Business Edition being distributed with your applications. This >>>restriction will be removed when the final version is released. >>> >>> >> >> Yes, but _when_ will the final version be released? > >Bad form! You need two __'s on each side! ;) > > > Not that I have anything I might want to distribute, but I see fro my > > records that I paid for the beta nearly a year ago, and in that time > > there has been one update, last summer, and since then a resounding > > silence. It would be a shame if the project just sputtered and died. > > There are all sorts of unselfish reasons for hoping that some > > company (or kompany) figures out a way to make money from Linux > > sometime. > >Same here. I haven't had a need to distribute the software I wrote yet >without source but I may have to in the future; unfortunately I didn't >catch that clause in the readme or I probably wouldn't have bought BA. > >Anyone out there have recommendations on a good IDE with form designer, >that's not Beta? Nothing too fancy...I've tried wxDesigner, but >couldn't figure out that spacer stuff for the life of me. I found glade more "intuitive" for me, once I got started. Biggest downside is that if your app needs to run on Windows, getting libglade to run on WinXX platforms can be a pain. On Linux, it's a snap. With Qt, you just pay... -frank -- From djc at object-craft.com.au Sat Mar 23 00:20:07 2002 From: djc at object-craft.com.au (Dave Cole) Date: 23 Mar 2002 16:20:07 +1100 Subject: Python Sybase mailing list released Message-ID: What is it: The python-sybase mailing list is a list where users of the Sybase module for Python can discuss issues concerning the module. Since the person who wrote the Sybase module is a hopeless joke who only has access to the Linux platform and knows less than all of the module users, the list is a good place for modules users to discuss platform issues at the very least. Where is it: https://www.object-craft.com.au/cgi-bin/mailman/listinfo/python-sybase - Dave -- http://www.object-craft.com.au From stephen at xemacs.org Fri Mar 1 00:40:22 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 01 Mar 2002 14:40:22 +0900 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87u1s0eth5.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Carel" == Carel Fellinger writes: Carel> Stephen J. Turnbull wrote: Carel> Now that we have your attention, what's your personal Carel> opinion on using something else but ascii (in whatever Carel> encoding:) for the code itself (things like keywords and Carel> variable names). My _very_ personal opinion is that identifiers can be run through an online dictionary, and I'm fortunate to be pretty good at languages, so that's fun. Nor do I do programming for a living, I can afford to concentrate on "fun." My opinion as a teacher is that I'd really like to be able to teach programming to my freshmen with a language that uses Japanese identifiers (including reserved words) and syntax (Japanese is a reverse Polish language). Carel> My Western centered view would be that it would make Carel> reading code harder, but that's probably what the rest of Carel> the world already experiences. For "real-world" use, I mostly agree that sticking to English is better, for code. None of the Japanese programmers I know feel that use of English for identifiers and reserved words hinders them. In fact, some think it may help somewhat, as it allows them to abstract from any connotations that the word may have in natural language. (Note that this implies that second courses in programming should use an English-based language.) There are exceptions, however. I maintain code that implements Japanese input methods in XEmacs, and even native speakers of Japanese sometimes get confused about what certain identifiers drawn from English, or even romanized Japanese, are supposed to mean. On the other hand, edict.el, which implements morphological transformations for dictionary lookup, uses mixed English-Japanese identifiers. The verbs (search, transform, etc) are English; the parts of speech and technical names for transformations are Japanese (ie, ideographs). Nobody (who is competent to understand what the code does) ever makes a mistake. This is a very special case, of course. But you can imagine many cases where an organization has internal practices that would best be described in native vocabulary. Then it's a tradeoff between short-term maintainability and long-term internationalizability. Carel> I even try to stick to English in my comments, just in case Carel> some foreignor might have to look at it:) If it weren't for the "groetjes, carel" in your .sig, I'd not be able to say with confidence you're not a native English-speaker. Despite the excellent English educational system, I cannot say the same for Indians in general. Most are sufficiently fluent that your practice would make sense, but many are not. And Japanese are legendarily bad at English. A correct comment in an illegible character set is harmless, although perhaps frustrating; an incorrect one that you can read is dangerous. So I'd have to say that except for the very worst cases, there are benefits to having code in English, or near-English, vocabulary. But comments should be written in a language you can use for teaching. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From nrk at cmcorp.com Mon Mar 11 08:28:53 2002 From: nrk at cmcorp.com (nrk at cmcorp.com) Date: Mon, 11 Mar 2002 13:28:53 GMT Subject: Changing Working Directory in Windows Message-ID: <3c8cb05d.221547919@news.earthlink.net> I'm brand new to Python. Can someone tell me how to change a working directory in a script on a Windows system? What does the pathname specification look like? Can I use an absolute path name when referring to a file? Thanks for any help you can give me. Norm Kashdan From gherman at europemail.com Mon Mar 4 10:41:42 2002 From: gherman at europemail.com (Dinu Gherman) Date: Mon, 04 Mar 2002 16:41:42 +0100 Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> Message-ID: In article , jimd at vega.starshine.org (Jim Dennis) wrote: > I would love to see a good book on "patterns" in Python. I'd like > it to be a simple booklet listing each of the GoF patterns, with a > couple of examples of each. It would be fine if it also covered some > additional patterns or some controversies or alternatives to the > classic GoF patterns (like the Alex Martelli's Borg vs. the GoF > Singleton). There used to be a Python Pattern-SIG in former times: http://www.python.org/sigs/pattern-sig/mission I wonder how much interest there would be in a revival? Dinu From eppstein at ics.uci.edu Tue Mar 5 20:09:48 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 05 Mar 2002 17:09:48 -0800 Subject: Status of PEP's? References: <3C8445FC.A1816810@cosc.canterbury.ac.nz> <3C855C40.9061EF31@cosc.canterbury.ac.nz> Message-ID: In article <3C855C40.9061EF31 at cosc.canterbury.ac.nz>, Greg Ewing wrote: > > the outer expressions should be or_expr to respect Python's > > precedence rules > > I can't find 'or_expr', but I'm looking at the 1.5.2 > grammar. Has it been added later? I was getting it from the 2.1 grammar. > > and the inner one should be identifier. > > That's a bit too restrictive -- any lvalue should be > allowed (as for-in does). Unfortunately there's no > grammar symbol corresponding exactly to an lvalue. Ok, right. It should be or_expr again, to match the 2.1 grammar. From shalehperry at attbi.com Fri Mar 1 12:19:52 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 01 Mar 2002 09:19:52 -0800 (PST) Subject: Python's Syntax In-Reply-To: Message-ID: > Also, another thing about Python's syntax. Are statements just sperated by > their lines, or do they have some form of seperator (like a semi-colon)? > read some more on http://www.python.org. Python is whitespace delimited. Your if statement above knew when to stop because you stopped indenting. if test: do() something() here() else: maybe() other() thing() more() Most of us who like coding in python appreciate this syntax because it makes for easier rapid development. No worrying about braces, semi-colons, etc. I just type and and type and it works. This also gets rid of the dangling else issue in languages like C. Takes some getting used to, but if it works for you, using another language feels odd. From grante at visi.com Wed Mar 27 23:54:42 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 28 Mar 2002 04:54:42 GMT Subject: seek in a file References: Message-ID: In article , Jim Dennis wrote: > Of course I recognize that this might be a multi-user > system (possibly with lots of POS terminals attached, > and the bar code scanners attached to those). In that > case consuming a meg or two of memory for the barcodes > dictionary *for each process* might get expensive. Build an index into it. Then mmap() it. You have O(1) access to any line in the file, and only the pages that get used will get pulled into RAM. As long as nobody writes to it, all processes will share copies of the pages. Let the OS worry about managing memory and disk buffers. That's what it's there for. -- Grant Edwards grante Yow! RELATIVES!! at visi.com From gavrilov at attbi.com Wed Mar 6 20:25:25 2002 From: gavrilov at attbi.com (Alexander Gavrilov) Date: Thu, 07 Mar 2002 01:25:25 GMT Subject: Working version of framework.py from win32comext\axscript\client Message-ID: <9kzh8.13764$Hf7.33821@rwcrnsc51.ops.asp.att.net> I have the same problem with IIS and win32all package that other people had too. The ASP page with Python as the scripting language loads only the first time. The subsequent loads return the blank page only. I'm aware about the Mark Hammond's suggestion to grab framework.py from win32all-133. But I can not find this version on the Mark's starship page! Could somebody (Mark?) post the working version of framework.py to the newsgroup? It would be helpful for many people, I think. Even better, Mark, could you check in the correction of this bug into CVS? Thank you, Alexander Gavrilov From anton at vredegoor.doge.nl Mon Mar 18 05:57:14 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 18 Mar 2002 11:57:14 +0100 Subject: Problem using pexports & Cygwin to build Python 2.2 extension modules References: Message-ID: On Sun, 17 Mar 2002 15:21:19 GMT, "Les Button" wrote: >Has anyone else had success building an extension module with Windows >Python 2.2 and Cygwin/gcc? Yes, I can build extensions for python 2.2 on windows 98 SE using cygwin. >P.S. I also had a problem with "Python.h" needing to have definitions of >SIZEOF_INT >and SIZEOF_LONG; these apparently didn't get defined properly (for >Cygwin/gcc) >in "pyconfig.h"?? I fixed for now by providing #define's for these two, >before the >#include "Python.h" -- I don't see why this should be related to the linker >failure. Probably you should reverse these changes for the solution below to work. >$ python setup.py build --compiler=cygwin try: setup.py build --compiler=mingw32 Good luck, Anton. From marijn at sanity.dhs.org Fri Mar 1 11:07:43 2002 From: marijn at sanity.dhs.org (Marijn Vriens) Date: Fri, 01 Mar 2002 16:07:43 GMT Subject: import Random: NV_MAGICCONST deviates too much. References: <29575ad6.0202282330.16226275@posting.google.com> Message-ID: <3C7FA749.6090005@sanity.dhs.org> Michael Hudson wrote: > marijn at sanity.dhs.org (marijn Vriens) writes: > > >>Hi all... >> >>I have get a strange exception when importing random. >>I brought it down to: >> >>Python 2.1.2 (#1, Jan 18 2002, 18:05:45) >>[GCC 2.95.4 (Debian prerelease)] on linux2 >>Type "copyright", "credits" or "license" for more information. >> >>>>>import gnome.ui >>>>>import random >>>>> >>Traceback (most recent call last): >> File "", line 1, in ? >> File "/usr/lib/python2.1/random.py", line 93, in ? >> _verify('NV_MAGICCONST', 1.71552776992141) >> File "/usr/lib/python2.1/random.py", line 88, in _verify >> raise ValueError( >>ValueError: computed value for NV_MAGICCONST deviates too much >>(computed 2,82843, expected 1) >> >>If I first import random and then gnome.ui I have no problems. my >>distr is debian woody with the standard python packages (not >>self-compiled) on an >>AMD-K6 >> >>Anybody know what's going on ? >> > > At a guess, something in gnome.ui is buggering around with locale > settings. Don't know if this actually helps -- I can't see quite how > it could produce the above error... > The work-around for this is to set the LC_NUMERIC locale after importing gnome.ui. like so: >>> import locale >>> import gnome.ui >>> locale.setlocale(locale.LC_NUMERIC, 'C') 'C' >>> import random >>> Thanks for the people at #python for helping with this issue! Cheers, Marijn From wealthychef at mac.com Fri Mar 15 13:09:23 2002 From: wealthychef at mac.com (wealthychef) Date: 15 Mar 2002 10:09:23 -0800 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> Message-ID: <2b57f654.0203151009.296bb7da@posting.google.com> grante at visi.com (Grant Edwards) wrote in message news:... > In article <2b57f654.0203141934.391d1bcc at posting.google.com>, wealthychef wrote: > > > selectables = [theProcess.childerr, theProcess.fromchild] > > (input, output, exc) = select.select([],selectables, selectables) > > It looks like you've got the first two parameters to select > reversed. After the above call, output is going to contain > writable sockets. If you're wanting to read data, you should > do: > > (output, input, exc) = select.select(selectables,[],selectables) Ding ding ding! You are correct, sir! Thanks for the help, I was doing it backwards. The python docs are a bit unclear to me on this point. Thanks for the help, it now works perfectly as expectorated. From ffjhenon at club-internet.fr Mon Mar 18 17:11:15 2002 From: ffjhenon at club-internet.fr (Fabien Henon) Date: Mon, 18 Mar 2002 23:11:15 +0100 Subject: Syntax color hightlight Message-ID: <3C966603.5010605@club-internet.fr> I am writing a text editor for POV-RAY (with Python-Tkinter) and I'd like to know if it is possible to implement syntax color highlighting for a specific language. I'd like to implement <>,(),[] matches as well. Is Tkinter powerful enough or do I have to use megawidget, wxpython. Thanks From gerhard at bigfoot.de Fri Mar 15 00:35:15 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 15 Mar 2002 05:35:15 GMT Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> Message-ID: Peter Hansen wrote in comp.lang.python: > Jonathan Gardner wrote: >> >> I have a free software program (http://sf.net/projects/bttotalcontrol/) and >> I am having great difficulty writing an installation script for windows. >> >> I don't want to use distutils because I am not writing a module - but an >> entire distribution with images, data files, and executable programs. I >> would like to put icons on the desktop and stuff in the start menu as well. >> >> I am at a major disadvantage because I don't have access to a windows >> machine, and so I can't test anything directly. However, I do have a few >> people who actively test for the project at home. >> >> Anyone have any suggestions on where I should go? Anyone can help me out >> here? > > Why not find and use one of the several free installer programs, rather > than trying to write something from scratch yourself? > > For example, try looking at google with "free windows installers" and > follow the first link you find. NSIS rocks. But AFAIR his problem is that he doesn't have a Windows box to build the installer on. The best solution to this problem is to give in and get a damn Windows box. Even a virtual one with VMWare or Bochs will do. AFAIK Bochs can run at least Windows 95 and it even runs on non-x86 hardware. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From philh at comuno.freeserve.co.uk Thu Mar 28 19:48:22 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 29 Mar 2002 00:48:22 +0000 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: On 28 Mar 2002 15:19:27 -0500, David Bolen wrote: >philh at comuno.freeserve.co.uk (phil hunt) writes: > >> IIRC in Awk you can just say: freq[word] ++ and it works >> correctly even when there is no pre-existing index of word in freq. >> >> IMO it's a pity Python isn't like that. > >I'm not so sure. Doing it that way presumes that in fact you aren't >making an error while trying to access an index (word) that doesn't >exist. Correct. IMO "try to do something sensible" should be the default. If the programmer *wants* to do it the other way round, that is easy enough to code: if word not in fred: raise SomeException fred[word] ++ But 9 times out of 10, you'll want to use a default of 0. >Python requires marginally more effort to cover this case (e.g., you >have to explicitly use a method like .get to include a default value >if you know the key might not yet be present), but that also means >that the code explicitly highlights that the scenario is anticipated >and being handled. Having to explicitly state things like this is a sign of low levelnmess in a lang. Next you'll be arguing that explicit storage management is a good thing.... :-) >Sure, in a simple example like an increment operation it seems a bit >much, but as a general case, I think it's the smarter and more >maintainable default behavior. I have never had maintainability problems with the other way round. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From geoff at gerrietts.net Wed Mar 6 22:58:51 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Wed, 6 Mar 2002 19:58:51 -0800 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: <20020307035851.GA23955@isis.gerrietts.net> Quoting Jeff Hinrichs (jlh at cox.net): > "Geoff Gerrietts" wrote in message > news:mailman.1015439904.7322.python-list at python.org... > > Quoting Ramkumar Kashyap (rkashyap at sympatico.ca): > > For the space of around three years, a child is immersed almost > > constantly, from waking to sleep, and even sometimes while asleep, in > > language. For those first three years, the child is almost completely > > incapable of making him or herself understood. > > *BUZZ* Sorry, but as a parent I can firmly say that children can > make a point well before 3 years. In fact, by 12-16 months they have > the ability to utter rudimentary words, associate action and > reaction and are deeply focused on interpersonal relationships, > among other things. First words are normally, familial (i.e > mom/dad/et al), then "NO," then "More" with a slew of words of > interest to them come next. I'm a parent, too, and there's a big difference between "daddy", "mommy", and the pronouncements that come from a child anywhere on up to 18 months and spoken language. At three (in April), my son speaks more or less complete sentences with occassional nods to the rules of grammar. About 3/4 of the time my wife and I understand him. About 1/4 of the time, others can understand him. And he's pretty advanced for his age; a lot of parents guess him at older. That's like saying that I speak French because I know how to say "oui" and "merci". You might make that claim, but expecting a Parisian to hold a conversation with me is somewhat unreasonable. What is it about internet discussion forums that makes everyone struggle to find grounds to argue rather than make an effort to understand? > > People don't get smarter as they get older, they just have a better > > foundation for building on. It would be just as difficult for someone > > to learn programming through reading or transcribing lots of text as > > it would be for someone to learn French by riding the Metro all day > > long. > This depends on how you define "smart." I refer to smart as the mixture of > wisdom + experience + ability to intuit. Again, this is begging the question, and after two pointless arguments niggling over the semantics of "smarter", I'm starting to get a little annoyed. I can define smarter as "having a higher IQ", as "best educated", or as "most able to solve a given problem" and all of them work pretty well. Right now I'm talking about ability to ingest raw information and retain it. It's clear I should have been a little more explicit; I guess terms like "smarter" are just begging for people to fight. > > My belief is that most people find computer programming to be > > difficult because logic is not the natural way people think; it is a > > forced mode. People tend to think intuitively, using "gut feelings" > > and good guesswork. That's the way we tend to summarize the knowledge > > of our experiences: as gut feelings. > I agree with you here. I think a previous poster has pointed out that I oversimplify here by reducing abstract thinking to intuition and gut feelings, but I think we all kinda get the point, when we're thinking in that mode. > I do believe that Ramkumar's point is valid. Children, especially > the young, suffer from fewer of the social pressures that retard adult > learning. The most salient, is the disregard for being wrong. Adults, I > believe, hamper their own learning process by limiting their questions or > not asking them if they feel that by exposing their "knowledge holes" they > are negatively impacting the social surroundings. (i.e. Don't want to look > stupid in front of the class.) Unfortunately, the fastest way to learn > something new is to expose your limited knowledge to the > teacher/instructor/peers so that they can more effectively rid you of > misconceptions and fill-in those "knowledge holes." I have a strong > suspicion this is why adults have a relatively more difficult time learning > new spoken languages than children do. (vocabulary that is, pronunciation is > another issue) I'm not sure that adults do. I think that your average diplomat who needs a speed-training in a foreign language, can master conversational language within a few months, and can be highly fluent inside a year. It requires careful coursework supplemented by a great deal of practice. Immersion is helpful, which (when we get back to the start of the thread) is the sentiment that started the whole thing. By contrast, the child can't converse effectively with his peers for three to four years, and can't hold his own in a conversation with an adult for even longer than that. Maybe a slight switch in topic: if the logical constructs are disorienting, how would we approach instruction? Hello World seems to go okay, right? (Do we have anything like a consensus from this?) But then where do we go? More examples? I'm not sure what my goal is here, but it seems like we started with an idea on how we could make computer programming more accessible for everyone, including those whose relationship with logical thought can only be described as "dysfunctional", but starting with those who are at least making occassional sallies at the task of learning. So where do we go next? If not "if", then what? Or do we go ahead with "if" and "else", but abuse it with lots of examples? Looking back at the pieces of pedagogical literature I've been exposed to, I'm led to believe that learning (at least in children) occurs in response to encountered frustrations with the limits of the current knowledge base. Can we assemble something that looks like a cooked series of examples or sample problems that exploit this? --G. -- Geoff Gerrietts I AM YOUR KING! BOW BEFORE ME, PEASANT! -- Dogbert From werner.hartnagel at web.de Mon Mar 11 13:58:58 2002 From: werner.hartnagel at web.de (Werner Hartnagel) Date: Mon, 11 Mar 2002 19:58:58 +0100 Subject: starting Comands from Python Message-ID: <3C8CFE72.80108@web.de> Hi Im a Python newbie and starting a small Project to learn Python better. Its a GUI for the Image Magick Convert Tool. The Application has a GtkCList with the Files to Convert. My Problem is I dont understand how to start a Application (convert) as a new Process. I use "posix.system(cmd_str)" to Test the Program, and of course the GUI freeze :-( It should wait for finish converting the File and start start again if not "Cancel" is selected. You make me very happy with some Source, urls, any hints. regards werner hartnagel From justin at iago.org Sat Mar 2 11:37:56 2002 From: justin at iago.org (Justin Sheehy) Date: Sat, 02 Mar 2002 11:37:56 -0500 Subject: Python 2.2 seriously crippled for numerical computation? In-Reply-To: (Huaiyu Zhu's message of "Fri, 1 Mar 2002 20:51:26 -0800 (PST)") References: Message-ID: Huaiyu Zhu writes: > There appears to be a serious bug in Python 2.2 that severely limits its > usefulness for numerical computation: > # Python 2.2 > >>>> 1e-200**2 > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: (34, 'Numerical result out of range') I suspect that this is a problem with your local compiler or math library. On the two most convenient platforms to me, this is properly handled. Python 2.2 (#1, Dec 28 2001, 09:54:53) [GCC 2.96 20000306 (experimental)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 Python 2.2 (#4, Jan 25 2002, 15:55:24) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 I don't know a lot of details about platform math implementations, but if you post your compiler and OS, I suspect that people here will be more likely to be able to provide useful advice. -Justin From bokr at oz.net Mon Mar 18 19:01:50 2002 From: bokr at oz.net (Bengt Richter) Date: 19 Mar 2002 00:01:50 GMT Subject: Format profile-data into "nice" HTML ? References: <0S9l8.11822$TU3.312633@news4.ulv.nextra.no> Message-ID: On Mon, 18 Mar 2002 19:53:28 GMT, "Thomas Weholt" wrote: >Posting a notice to let the group know of my very early and very simple >attempt at html-formatting on output from the profile/pstats-module. > >The module is available at http://home.online.no/~t-weh/releases/hspstats.py >and a preview of the output is available here >http://home.online.no/~t-weh/releases/prf.html > >Please let me benefit from comments and improvements ( there are room for >plenty :-) ) by sending me a mail etc. > >Best regards, >Thomas Weholt > > Hi, I didn't post this. I happened to look at the source of your example HTML. It isn't required for HTML format, but if you start your

    and
    and ), but it will still be much better. And it should be trivial to implement :) -- Ian Bicking From cwazir at yahoo.com Sun Mar 31 11:30:17 2002 From: cwazir at yahoo.com (Chirag Wazir) Date: 31 Mar 2002 08:30:17 -0800 Subject: Most important extensions? References: Message-ID: <79c178a9.0203310830.6ec5acd0@posting.google.com> Hi, IMHO it's very difficult to choose three specific extensions without deciding an application domain. There are just so many goodies out there :-) If it's of any use to you, I did an introductory two hour Python seminar at my local ACM chapter and I've put up the slides (which contain a list of resources, extensions & applications) at my home page - http://chirag.freeshell.org Chirag Wazir aahz at pythoncraft.com (Aahz) wrote in message news:... > I'm teaching Python for [Perl] Programmers at OSCON this July. I've > already decided to mention mxODBC, NumPy, and PIL, plus PythonPoint (aka > ReportLab) gets a mention on my title page. I'd like this group to vote > on the most important extensions for me to add to this list. Please vote > for no more than three. From mwh at python.net Tue Mar 19 08:00:50 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 19 Mar 2002 13:00:50 GMT Subject: Dictionary Comprehension References: <3mbe9usoufc2f5ppjmk7lh6ks71pgb45f9@4ax.com> Message-ID: Dale Strickland-Clark writes: > What ever happened to the idea of dictionary comprehension discussed > (well, mentioned in a timid whisper) in the middle of last year? > > I'm doing some dictionary work right now where I keep seeing all sorts > of neat applications for the idea. > > I'd really like a concise way to work on a filtered subset of a > dictionary. It got made into a PEP: http://python.sourceforge.net/peps/pep-0274.html The "Parade of the PEPs" says: PEP 274 - Dict Comprehensions - Warsaw If we were to adopt dict comprehensions, this PEP says everything that needs to be said. But I don't even want to think about this for Python 2.3; I think it's way too minor a feature. This would be a lot easier to adopt if there was a working implementation in patch form. Sometimes it would be nice if things like this could be defined using hygienic macros or some other kind of preprocessor or whatever, and imported from a module, rather than requiring major hacking in the parser, the bytecode compiler, and the virtual machine. Cheers, M. -- The above comment may be extremely inflamatory. For your protection, it has been rot13'd twice. -- the signature of "JWhitlock" on slashdot From peter at engcorp.com Mon Mar 11 08:00:51 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 11 Mar 2002 08:00:51 -0500 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8C82D3.CA4220CA@earthlink.net> Message-ID: <3C8CAA83.9EBBC03E@engcorp.com> Tim Hammerquist wrote: > > Hans Nowak graced us by uttering: > [ snip ] > > It sure smells like a hoax. I mean, really: > > > [ snip ] > > > > "Open and unrestricted"? It sure seems ludicrous to see these > > words in the same sentence with "Microsoft". > > Didn't you know? Microsoft invented Open Source! ;) No, that was Al Gore! From jgardn at alumni.washington.edu Mon Mar 11 02:57:24 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Mon, 11 Mar 2002 16:57:24 +0900 Subject: scripting Outlook express with Python References: Message-ID: Sandy Norton scribbled with his keyboard: > Does anyone have any experience, code, etc...? I guess my first > question should be: is it possible? > If you want to customize your mail client, you're using the wrong OS. All the customizability is over here in Linux, with procmail and sendmail and fetchmail and all sorts of great stuff that you've never even dreamed of - even in those really wild dreams where you use your computer for a month and it doesn't crash once. Jonathan From brad-g-johnson at uiowa.edu Fri Mar 15 15:44:45 2002 From: brad-g-johnson at uiowa.edu (Johnson, Brad) Date: Fri, 15 Mar 2002 14:44:45 -0600 Subject: Parsing string into fixed-width pieces Message-ID: <412F4D3C5614D211853600A0C99E563F0D0D80ED@com83-173.medicine.uiowa.edu> Hello, I'm new to Python and have been combing the documentation and the message archive here for information on splitting a string into fix-width pieces. I assume their is an easy way to do this, I just don't seem to be able to find it in the reference material. Any suggestions? Thanks. Brad ____________________________________ Brad Johnson Department of Pediatrics - Neurology 200 Hawkins Drive, 2505 JCP Iowa City, IA 52242-1083 Voice: +1 319 356 1851 Fax: +1 319 356 4855 e-mail: brad-g-johnson at uiowa.edu From phlip_cpp at my-deja.com Wed Mar 27 14:08:26 2002 From: phlip_cpp at my-deja.com (Phlip) Date: Wed, 27 Mar 2002 19:08:26 GMT Subject: Why does this work? References: <3CA1BB93.FC00D40D@pop.ntlworld.com> Message-ID: "Terry Reedy" wrote: > > "Phlip" wrote: ... > > And we wrap all data members in get/set pairs, so the above would > have been: > > > > x.setTiles([]) > > 'we'? The wisdom/folly of using get/set pairs is a matter of > continuing dispute. Some of us find the extra work and inefficiency > distastful. We at my day gig. We find just >having< a style guideline slightly more important than the value of any few marginal items in it. And we like to find ways to cure the "magic member bug". If you can think of any others, please share. -- Phlip From tim-dated-1015911613.b601d0 at catseye.net Tue Mar 5 00:40:12 2002 From: tim-dated-1015911613.b601d0 at catseye.net (Tim Legant) Date: 04 Mar 2002 23:40:12 -0600 Subject: Python song? (Re: Python isn't necessarily slow) In-Reply-To: <3C8451E1.B2CD032@cosc.canterbury.ac.nz> References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> <3C8451E1.B2CD032@cosc.canterbury.ac.nz> Message-ID: <864rjvh8sj.fsf@skitty.catseye.net> Greg Ewing writes: > Siegfried Gonzi wrote: > > > > Python isn't necessarily slow: > > That sounds like a great title for a Python > song: "It Ain't Necessarily Slow!" > > Anyone want to contributes some lyrics? Things that you're liable To read in Deitel & Deitel Ain't necessarily so... Hmm. Not exactly right... Strings that you're liable To search for, from Friedl Ain't necessarily slow! That's better, Tim From aahz at panix.com Tue Mar 5 12:34:34 2002 From: aahz at panix.com (Aahz Maruch) Date: 5 Mar 2002 09:34:34 -0800 Subject: Reorganizing python.org (was: Why isn't pychecker...) References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> <3C841006.634D0059@tds.net> Message-ID: In article <3C841006.634D0059 at tds.net>, Edward K. Ream wrote: > >python.org > a page about releases of python itself > a download page > a page about major tools, idle, pychecker, pyunit, > with links to the commercial products page, > a page about related products & tools, > MacPython, Jython, Pippy, Tkinter, etc. > a links page, containing subpages or subsections for > commercial products > an events page > the commercial products page. > etc. One of the items on my plate for Real Soon Now is to reorganize the python.org sections dealing with development into a section called something like "Python Development (bug reports, patches, and feature requests)". -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From martin at v.loewis.de Fri Mar 15 19:06:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Mar 2002 01:06:45 +0100 Subject: Windows NT shell + extended characters. Bug or what? References: Message-ID: "Jason Orendorff" writes: > Alas, the PC console uses a different character set called CP437, > which is not Latin-1 compatible. In CP437, the pound sign > is 156 and the yen sign is 157. This isn't really true. The console on Windows (I believe both Win9x, and NTx) use what MS calls the "OEM" charset. Which code page that is depends on the Windows installation. In the US English installation, it is indeed CP437. In the European installations, it is CP852 most of the time. > [in Win2K console] > >>> ord(u'?') > 156 # uhhh, no > >>> ord(u'\N{POUND SIGN}') > 163 # correct answer > > I think it's fair to say this is a deficiency in current > versions of Python. I believe it will be fixed This is rather unlikely, I doubt the interactive interpreter will ever be able to properly identify the encoding of the console window. More likely, this line will give an error, since no encoding has been declared. Regards, Martin From george at cc.gatech.edu Sat Mar 9 15:09:30 2002 From: george at cc.gatech.edu (George Thomas) Date: Sat, 9 Mar 2002 15:09:30 -0500 Subject: List of lists: caveat? Message-ID: Hi everyone, I just tried creating a 2D array the 'list-of-lists' way as follows: two_d_array = [ [0] * 20] * 10 # Creates a 10 * 20 array -- (I) two_d_array[0][3] = 1 # Sets element [0][3] to 1 I expected nothing unnerving, except that print two_d_array[1][3] gives me 1 as does print two_d_array[any valid index from 0 to 9][3] What are the exact semantics of the line marked (I) above? If there is a caveat, is there any way I can get around it without installing separate modules that define array/matrix objects? rgds -- ------------------------------------------------------------------------- who : george thomas reduce (lambda c,d:chr(ord(d)-2)+c, 'ofcpqkekhhC"zwpkN"fgtgyqR/pqjv{R') that is all ------------------------------------------------------------------------- From grante at visi.com Sat Mar 9 19:13:22 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 00:13:22 GMT Subject: Tkinter + Button widget References: <3c8a943b$1_3@nopics.sjc> Message-ID: In article <3c8a943b$1_3 at nopics.sjc>, Adonis Vargas wrote: > when i start a button widget, it automatically fires the command? > > def HideNewClient(self, frame): > frame.configure(bd=0, width=0, height=0) > return > > pdb_btnSearch = Button(pdb_frmCommands, > text="Search", > relief=GROOVE, > font=("Tahoma", 10), > width=16, > command=self.HideNewClient(pdb_frmNewClient)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You're "firing the command" right there. You probably want to do something like: pdb_btnSearch = Button(pdb_frmCommands, [...] command = lambda x=pdb_frmNewClient: self.HideNewClient(x) or def cmdProc(): return self.HideNewClient(pdb_frmNewClient) pdb_btnSearch = Button(pdb_frmCommands, [...] command = cmdProc -- Grant Edwards grante Yow! Can you MAIL a BEAN at CAKE? visi.com From msx at crs4.it Fri Mar 15 06:04:58 2002 From: msx at crs4.it (Federico Caboni) Date: Fri, 15 Mar 2002 12:04:58 +0100 Subject: Dear Guru, I have added def and it doesnt work Sincerly, F References: Message-ID: On 15-03-2002 9:09, in article B8B76AE7.D16%msx at crs4.it, "Federico Caboni" wrote: > On 15-03-2002 4:01, in article slrna92leq.6n5.gerhard at lilith.my-fqdn.de, > "Gerhard H?ring" wrote: > > [SNIP] > >>>> No wonder this doesn't work, as you've apparently haven't made very >>>> much effort to understand what you're doing here. >>>> >>>> Sorry to be so blunt, but you can't write software just by guessing >>>> about the syntax. >>> >>> Really? I do some of the time, when I don't remember it and can't be >>> bothered to look in the manual. >> >> Me too, mostly by trying stuff out at Python prompt, for instance if I >> forgot the semantics of slicing again. >> > > I discovered "eval" by guessing.... > I thought something like "It would be cool if existed a statement like > that". > I guessed the name too =). > Well...I agree that this is not the right way to learn Python anyway ;) > BTW... I think that's a proof of Python's beauty. The statement worked exactly as I espected, and had the same name I Expected too... I don't think I could just do the same with C pointers ;) ____ ____ ____ _ _ ____ _ _ ____ / ___)| __ \/ ___)/ /| | / ___)| \| |/ ___) Federico Caboni (msx at crs4.it) | (___ | /\___ \\__ | * \___ \| |\___ \ Software & Network Solutions \____)|_|\_\(____/ |_| (____/|_|\_|(____/ Phone: +39 070 2796 368 CRS4, Center for Adv. Studies, Research and Development in Sardinia From -$P-W$- at verence.demon.co.uk Sun Mar 17 18:57:03 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 17 Mar 2002 23:57:03 -0000 Subject: Eliminate Spam Now... >g< Python w/DNS/&POP3 References: Message-ID: In article , Benjamin Schollnick wrote: > I'm attempting to use the (py)DNSlib (sourceforge project), to look >up Spammers via ORBZ (or similiar group)... > > And I'm able to pull up the DNS information, but every entry I try >response with a valid root level DNS entry.... Can anyone enlighten me >regarding the operations of the black hole lists? I can't seem to find >any of the sights that explain the actual functionality. http://groups.google.com/groups?selm=8uund5%242et%241%40verence.demon.co.uk&oe=ISO-8859-1&output=gplain -- Paul Wright | http://pobox.com/~pw201 | From jeff at ccvcorp.com Fri Mar 15 19:05:33 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 15 Mar 2002 16:05:33 -0800 Subject: Windows NT shell + extended characters. Bug or what? References: <10095d00.0203150319.12f9cbf9@posting.google.com> Message-ID: <3C928C4D.20BF73C8@ccvcorp.com> Noel Smith wrote: > However I've recently installed python 7.2 on Windows NT4 Wow! 7.2 ? They really *have* sped up the release cycle... > and found it > gives the following results when using the command line shell: > > >>> print ord('?') > 156 > >>> print ord('?') > 157 > > Which is clearly wrong although strangely enough when I type the same > thing into IDLE on Windows NT, it produces the correct results. I believe that the issue here is that Windows does not typically use the Latin-1 codepage. You'll have to use the unicode methods to convert to Latin-1. Jeff Shannon Technician/Programmer Credit International P.S. Not that I know what I'm talking about, but hey, this is Usenet -- when has that ever stopped anyone?? From logstx at bellatlantic.net Tue Mar 5 18:00:03 2002 From: logstx at bellatlantic.net (logistix) Date: Tue, 05 Mar 2002 23:00:03 GMT Subject: Order of constructor/destructor invocation References: Message-ID: Yeah, exactly. h = HTML() is equivilent to: HTML* h; h = new HTML; and not HTML h; In C++ terms, all the variable names are reference counting "smart pointers", and we know how fun those are to implement. Over and over and over and over again. From duncan at NOSPAMrcp.co.uk Fri Mar 22 03:53:22 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 22 Mar 2002 08:53:22 +0000 (UTC) Subject: Sorting distionary by value References: Message-ID: Artur Skura wrote in news:slrna9lqj1.9n1.arturs at aph.waw.pdi.net: > Is there an idiom in Python as to sorting dictionary by value, > not keys? I came up with some solutions which are so inefficient > that I'm sure there must be a simple way. How do you know they are inefficient? Have you profiled your application and found this to be a bottleneck? Anyway, the idiomatic way to sort a dictionary by value, when the key doesn't have to be saved: values = myDictionary.values() values.sort() Or, if you want both keys and values: items = [ (myDictionary[k], k) for k in myDictionary ] items.sort() items = [ (k, v) for (v, k) in items ] -- 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 inerte at hotmail.com Wed Mar 6 14:14:30 2002 From: inerte at hotmail.com (Julio Nobrega) Date: 6 Mar 2002 11:14:30 -0800 Subject: Web scripting with Python (1st post here, also :-) Message-ID: <40c3f5da.0203061114.18f7fea6@posting.google.com> Hi! I am used to do web scripting using PHP. As a new adventure, I am trying to learn Python. I really wished I could write 'desktop' apps with Python, but from what I read (and from what I am planning), that's a little far away from my current trouser snake knowledge (I also heard you all like those kind of quotes ;-) So, I am looking for examples that might help me. Yes, I saw Zope. Waaaaay too much. Also read Web Programming Topic Guide on python.org, way less practical than I like. Picky, ain't I? :-) I searched for complete (yet simple), or incomplete (yet with explanations) apps on cgi-resources, parnassus and hotscripts, but I don't have background to decide what's good or bad Python. And surely I don't want to start with the wrong foot :-) Well, enough is enough, isn't? Where do I start? It's for a weblog (Kuro5hin-like) system. Anyone have a tip for me? Examples? Squisdot is the way to go? Btw, sorry for any grammer mistakes. My coconuts are in a tropical zone and english is not my primary language. If anyone does want to talk in Portuguese, I can :-) Thanks a lot, Julio Nobrega. From mrlee at davesupply.com Tue Mar 5 15:40:51 2002 From: mrlee at davesupply.com (Mr.Lee) Date: Tue, 05 Mar 2002 20:40:51 GMT Subject: Updating Python...Newbie alert! Message-ID: Hi all, Being quite new to Linux, I am having a bit of a problem when it comes to updating my installed version of Python(1.5.2) to the version that I have now(2.2). My problem is that I compiled Python in the directory that I downloaded and now I don't know where to put all of the files that were generated! It works, I ran the tests and it all came out fine, but I just don't know where to put the files for maximum efficiency. Thanks in advance, Lee McLain -- ------------------------------------- Dave Supply Company Industrial Diesel Power & Generators (330) 798-0215 Phone (330) 798-0276 Fax www.davesupply.com From donn at u.washington.edu Fri Mar 1 16:21:45 2002 From: donn at u.washington.edu (Donn Cave) Date: 1 Mar 2002 21:21:45 GMT Subject: Securely passing arguments when opening a pipe to a program References: <3C7FE115.9832EE5C@olen.to> Message-ID: Quoth Joonas Paalasmaa : | I am using Gnokii to send SMS messages with Python. Gnokii is started | with | popen2.popen2 like this: | | gnokiiRead, gnokiiWrite = popen2.popen2("gnokii --sendsms %s" % | phonenumber) | gnokiiWrite.write(message) | gnokiiWrite.close() | response = gnokiiRead.read() | gnokiiRead.close() | | The problem is that the phonenumber string is not safe; it can even be | "000; rm -fR ~/*". How can I securely pass arguments when opening the | pipe? | Is there a way to pass the arguments like in os.execv. Yes! I hear this isn't documented as well as it could be, but popen2 accepts either a string or a sequence, and in the latter case the sequence is argv, like in os.execv. Donn Cave, donn at u.washington.edu From rjones at ekit-inc.com Sun Mar 31 17:10:19 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Mon, 1 Apr 2002 09:10:19 +1100 Subject: OT: Daylight savings time (was Re: Subclass sadness (was Re: [Python-Dev] PEP 285: Adding a bool type)) In-Reply-To: <3CA73486.72B4059F@engcorp.com> References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <3CA73486.72B4059F@engcorp.com> Message-ID: <200203312210.WAA03664@crown.off.ekorp.com> On Mon, 1 Apr 2002 02:08, Peter Hansen wrote: > Richard Jones wrote: > > Hrm, just following this thought here, possibly for no good reason at all > > (hey, it's Sunday, and daylight savings just ended so I've got a whole > > _hour_ extra to waste today :)... > > In which country? Good thing it's not a work day, since I took your > word for it last night... or was that another advance April Fools joke? Australia, in Victoria at least - don't know about the other states :) Richard From carifio.nospam at nospam.usys.com Fri Mar 1 13:49:47 2002 From: carifio.nospam at nospam.usys.com (Mike Carifio) Date: Fri, 01 Mar 2002 18:49:47 GMT Subject: __abs(self)__? Message-ID: I'm reading about special method names. __abs__(self), which maps to the abs() method seems unneccessary(?). So: class ExampleNumber: def __init__(self, initializer): self.value = initializer def __abs__(self): return abs(self.value) >>> x = ExampleNumber(-1) >>> x.abs() 1 seems no different from: class ExampleNumber: def __init__(self, initializer): self.value = initializer def abs(self): # name isn't special? return abs(self.value) abs is a builtin function, so why do I need a special name for a function? I'm missing something... From tim.one at comcast.net Wed Mar 20 21:29:38 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 20 Mar 2002 21:29:38 -0500 Subject: A question about generators In-Reply-To: Message-ID: [Richard J Kuhns] > That's pretty much what I ended up doing -- I put a "while 1:" loop > around the rest of the code in the generator, and I test a "reset > generator" variable after each yield. If it's set, "continue" the > while loop. It's kind of nasty-looking, but it seems to work. Make the generator a method of a class. Give class instances a "reset generator" variable. Give the class a reset() method to set this variable. Then it's all nice, abstracted, reusable, and self-contained. a-feature-in-isolation-is-a-feature-doomed-to-misuse-ly y'rs - tim From ftobin at neverending.org Mon Mar 11 23:39:59 2002 From: ftobin at neverending.org (Frank Tobin) Date: Tue, 12 Mar 2002 04:39:59 GMT Subject: Homepage of Gadfly not available? In-Reply-To: References: <3C8C8DA1.5040901@med.uni-tuebingen.de> <20020311140817.L25769@phd.pp.ru> <3C8CA56B.7050505@med.uni-tuebingen.de> Message-ID: <20020311233409.A30846-100000@palanthas.neverending.org> Oleg Broytmann, on 2002-03-11, wrote: > > Are the sources available somewhere? > > Is there a new home page for Gadfly? > > Is there anybody who will maintain such a page? > > My answer is no better than http://sourceforge.net/projects/gadfly/ Except for the fact that that project was registered over 2 years ago, and has had 0 activity... -- Frank Tobin http://www.neverending.org/~ftobin/ From skip at pobox.com Tue Mar 5 18:10:28 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 5 Mar 2002 17:10:28 -0600 Subject: Need feedback - What are the elements of a good hosting service? Message-ID: <15493.20580.46393.626539@beluga.mojam.com> About two months ago I started working on a "hosting" page similar to the "editors" page I maintain) for the python.org website. It went idle for awhile, but I want to pick it back up and make something available for the community. It's clear from the traffic on the subject that this would be useful for people. In parallel, I have been working on a website for what I hope to be my own software consulting company. Viewing it as more of a marketing tool than anything else, I selected a company I thought was fairly well tuned into the Python community. During this startup period, I've been struggling to master elements of their service and have found that standard questions like * What version of Python is installed? * Can I write my own CGI scripts? * How much disk space do I get? * How much does it cost? were definitely *not* sufficient to decide if the service is going to be adequate to meet my needs. I don't want things to get too out-of-hand or I'll never release anything, but I would like some feedback from people on what they find to be the important secondary issues over and above the obvious stuff above. I won't bias the discussion at this point with my own experiences (besides, I have to get home and cook dinner ;-), but will post something in the next day or three myself. Hint: I suspect many of these same secondary issues would be important no matter how you choose to implement a website that contains programming elements (CGI scripts, Zope, Webware, mod_python, whatever) implemented in just about any language (Perl, Python, Tcl, Ruby, C, VB, ...). -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From jfg.removeplease.noospaam at netinfo.fr Mon Mar 25 16:24:21 2002 From: jfg.removeplease.noospaam at netinfo.fr (jeff) Date: Mon, 25 Mar 2002 21:24:21 +0000 (UTC) Subject: PHP to Python Message-ID: I'm looking for a tool to translate code from PHP to Python. Does it exists ? From dortmann at lsil.com Tue Mar 26 15:46:01 2002 From: dortmann at lsil.com (Daniel Ortmann) Date: 26 Mar 2002 14:46:01 -0600 Subject: hang in urllib.read()? References: Message-ID: "Nick Arnett" writes: > The (presumably) infinite loop that I thought was in sgmllib, about > which I posted earlier, actually seems to be when I call read() on an > urllib.urlopen object. It's terribly non-reproducible, though -- I'm > retrieving lots of pages and sometimes it'll go for dozens and dozens, > no problem. Other time it hangs after just a few. And it won't do it > on the same page twice, as far as I can see. > I've been unable to find anything like this searching... sound > familiar to anyone, or any suggestions for nailing it down, short of > gruesome stepping through with a debugger, hoping I can catch one...? > This is on Win2000 with Python 2.2. Haven't tried on other platforms > yet. Hello, Could this information help? The web page, "Known bugs in Python 2.2", says: "The ftplib module's FTP class was supposed to default to paassive mode. Unfortunately it doesn't. This means that urllib.urlopen() doesn't work from inside most firewalls. If you have this problem, delete or comment out line 117, 'self.passiveserver = 0', from file ftplib.py". -- Daniel Ortmann, LSI Logic 3425 40th Av NW, Suite 200, Rochester, MN 55901 dortmann at lsil.com / 507.535.3861 (w) / 6-3861 (int) ortmann at isl.net / 507.288.7732 (h) From nbecker at fred.net Fri Mar 8 10:21:17 2002 From: nbecker at fred.net (N Becker) Date: 8 Mar 2002 07:21:17 -0800 Subject: Where is quote (again)? Message-ID: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Back in 1999, I asked "where is quote?". I was looking for a way to quote a function (delay evaluation). I wonder if there is anything new. It looks to me that the best answer is to use lambda. example: def f(): return lambda: os.chmod(""/root/.rhosts", 0644) def g(): f() From quinn at pfennig.ugcs.caltech.edu Sat Mar 9 00:21:36 2002 From: quinn at pfennig.ugcs.caltech.edu (Quinn Dunkan) Date: 9 Mar 2002 05:21:36 GMT Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: On 3 Mar 2002 22:11:50 GMT, Bengt Richter wrote: >>It should give an error - 5 is not a sequence, so 'i in 5' is nonsense. >> >No, it's not nonsense. 'i in 5' is a probability, so > > for i in 5: > do_this() > >should have an i/5.0 chance of executing do_this(). Reminds me of icon's 'random' operator. Along with its 500 other operators. From mhammond at skippinet.com.au Tue Mar 12 04:03:12 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 12 Mar 2002 09:03:12 GMT Subject: Redirecting output in Windows NT References: <96e9dee5.0203120044.33a1e19c@posting.google.com> Message-ID: <3C8DC473.2070809@skippinet.com.au> Paul Lydon wrote: > Running Python 2.2 on Windows NT 4 Workstation. > Suppose I have a Python program named 'splat.py' consisting of: > "print 'splat'". > > If I type 'splat' and hit 'Enter', NT knows that it must run the > Python interpretor and I see 'splat' on the screen. If I redirect the > output to a file: > 'splat > splat.txt', the resulting file is 0 bytes long and empty. > > If I run the same program directly by typing 'python splat.py', again > I see 'splat' on the screen and when the output is redirected 'python > splat.py > splat.txt' I get a file containing the string 'splat' (as > you would expect). > > Any ideas why the output redirection doesn't work in the first place? It is a bug in the NT command prompt. Works OK in Win2k. I believe there is a FAQ on it too. Mark. From bokr at oz.net Fri Mar 29 22:42:00 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Mar 2002 03:42:00 GMT Subject: Newbie: List of instances? References: <3CA4C09B.D9D15464@bellsouth.net> Message-ID: On 29 Mar 2002 19:59:17 GMT, bokr at oz.net (Bengt Richter) wrote: >On Fri, 29 Mar 2002 14:29:31 -0500, Jeff Layton wrote: > >>Hello, >> >> I'm still learning Python and I'm playing around with some >>code that creates a class. I've mastered that stage already. >>However, what I want to do is create multiple instances of >>the class and put them into a list. >> If the class is called Bob, then I want to do something like, >> >> >>a = [] >>a[0] = Bob('input1') >> >> >>and so on. Everytime I try something like this I get the following >>error message: >> >> >>a[0] = Bob( 'localhost' ) >>IndexError: list assignment index out of range >> >Because there is no a[0] yet if a is [] >> >> I also tried it this way, >> >> >>a = [] >>a.append = Bob('localhost') >> >That much should work. Can you copy and paste an actual interactive snippet? E.g., > Oops, misread that, sorry. That really should have gotten you the error (on 2.2 at least): message AttributeError: 'list' object attribute 'append' is read-only which would have been a good clue. The following is verbatim from my screen however (see how much more reliable that is? ;-) > >>> class Bob: > ... def __init__(self,v): > ... self.v = v > ... def show(self): > ... print 'This is a Bob instance with v = %s' % self.v > ... > >>> a = [] > >>> a.append(Bob('localhost')) ^^^^^^^^^^^^^^^^^^^^^^^^^^-- what I thought I read above, which is why I "reproduced" it. > >>> a > [<__main__.Bob instance at 0x007CF4A0>] > >>> a[0] > <__main__.Bob instance at 0x007CF4A0> > >>> a[0].show() > This is a Bob instance with v = localhost > >> >>and I get the error message: >> >> >>a[0] = Bob( 'localhost' ) >>IndexError: list assignment index out of range >> >a must have still been [], but who can tell from what you posted? > >> Can anyone shed some light into how I do this? Or is >>there a better way? >> >Post a log of minimal failing code sufficient for anyone >to duplicate your problem. > Always best. Regards, Bengt Richter From emile at fenx.com Sat Mar 23 13:13:01 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 23 Mar 2002 10:13:01 -0800 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: phil hunt > >> `ht2html', which transforms .ht template files into .html files. > > Is the source for this available? > Look in the Tools directory - I found a copy there. -- Emile van Sebille emile at fenx.com --------- From skip at pobox.com Sun Mar 17 11:24:50 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 17 Mar 2002 10:24:50 -0600 Subject: XML-RPC Bug? In-Reply-To: References: Message-ID: <15508.50002.132189.479966@12-248-41-177.client.attbi.com> Jesper> With xmlrpclib & SimpleXMLRPCServer it is possible to call Jesper> procedures remotly, which return various simple python types. Jesper> If I call a procedure that returns nothing, I get a Jesper> "" Jesper> Surely that is a bug? Actually, no it's not. XML-RPC supports a limited set of data types. It doesn't support a nil or None type. For details, check the XML-RPC spec: http://www.xmlrpc.com/spec -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From m.faassen at vet.uu.nl Sat Mar 23 08:54:10 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 23 Mar 2002 13:54:10 GMT Subject: "Zope-certified Python Engineers" [was: Java and Python] References: Message-ID: A.M. Kuchling wrote: > In article , > John J. Lee wrote: >> [OT: A question I've asked many times and got no answer to is 'why has >> nobody done self-consistent ranking for academic papers'? I fear the > Have you seen CiteSeer, at http://citeseer.nj.nec.com/cs ? It crawls > the Web for papers, and then assembles a graph of citations. Also known as www.researchindex.org. An extremely useful resource. I sometimes marvel about how the internet, especially with resources like researchindex, allows small independent developers to benefit from so much research. A decade ago there was nothing like this available; what there was was in university libraries and the libraries of large companies that can afford a research department -- and it was far less convenient to boot. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From haep1004 at dreamwiz.com Tue Mar 5 11:46:01 2002 From: haep1004 at dreamwiz.com (Haeyoung Kim) Date: 5 Mar 2002 08:46:01 -0800 Subject: fork and thread and signal... oooooops Message-ID: <87550ef1.0203050846.2166835e@posting.google.com> I know little about system programming, so my code has become a monster. My situation is : 1) used /etc/init.d script functions such as daemon, killproc to start/stop python script. 2) python script is composed of two tasks. launching java server program and running script that connects that server to see if it's alive or dead. so, I programmed python script like this. PID = 0 ISALIVE = 1 def exitProgram(): ISALIVE=0 killServer() def killServer(): if PID: os.kill(PID,SIGINT) PID = 0 class Monitor(Thread): def run(self): # connect to server and check its heartbeat # and call restartServer and exit when server is dead. def launchServer(): pid = fork() if not pid: execv('java',args) #launch server else: PID = pid #start cheking server heartbeat Monitor().start() #and set PID for killing server. p, e = os.wait() #wait until server is killed #because of killServer or restartSErver. #hope to clean up java server when shell script 'killproc' terminate #this script signal.signal( SIGINT, exitProgram ) signal.signal( SIGHUP, exitProgram ) if __name__==__main__: pid = fork() if not pid: os.exit else: pid = fork() if not pid: os.exit else: #now start main program while ISALIVE: launchServer() Yes, it's stupid. But I didn't imagined such a picture at first. When shell script calls killproc(in init.d script), it sends signal, and kill server-using os.kill(java_server_pid)- and get out of os.wait() and died out generously - just my hope. But it betrayed my hope. it throws TypeError on os.wait(), killed anyway, but there are still my java program. :( I think signal doesn't call exitProgram() - why? Is there any clean solution to such a matter? thanks in advance your kindness for reading my naive code. From robin at jessikat.fsnet.co.uk Fri Mar 8 14:00:50 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 8 Mar 2002 19:00:50 +0000 Subject: Autodiscovery of proxy settings from a python script References: Message-ID: <7EHvmJAipQi8Ew$x@jessikat.demon.co.uk> In article , Andy Robinson writes >A firm we are working with want to demonstrate some Python web services >software, which will connect from a windows desktop to a known server on the >internet. It is a safe bet that the demos will be given behind firewalls, >but that the customers will be able to browse the web from either IE or >Netscape. The problem is that both the guys giving the demos and the >potential customers will not be very technical, and saying "what's your >proxy server settings" will likely spark fear, paralysis and wasted visits >:-) If they have a locked down IE distribution, the settings will just say >"auto detect" and the salesman won't be wiser. > >Ideally I'd like a script that knew where IE and Netscape and a few other >packages kept their proxy settings, and also know about the most common >auto-discovery protocols. It could try various things in succession until >it made a comnnection, or gave up and asked. The salesmen could email a >small program to the client and say "try this" ahead of time and would at >least know what to expect. We're already committed to installing python and >COM so can use just about any tools needed. > >Has anyone done this before? Any suggestions how to go about it? > > >Best regards, > >Andy Robinson >ReportLab Inc. > > I found the following using google find proxy server python http://www.google.com/url?sa=U&start=10&q=http://compnetworking.about.com/library/weekly/aa061000b.htm&e=922 http://www.faqts.com/knowledge_base/view.phtml/aid/4970/fid/245 The first mentions the wpad protocol which is recognized by IE. -- Robin Becker From drew at level3.net Fri Mar 29 10:35:39 2002 From: drew at level3.net (Drew Fisher) Date: 29 Mar 2002 08:35:39 -0700 Subject: Function problem In-Reply-To: References: Message-ID: <1017416139.1508.51.camel@beast.l3.com> > > G'day: > > Can someone tell me why this function stops printing after looping through > the " % (entry, entry) print "" . . This just does the one query and pulls out all of the data at one time. The c.fetchone() hits the database each time the while loop repeats. Hope this help. Drew Fisher From gerhard at bigfoot.de Sat Mar 23 07:09:00 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 23 Mar 2002 13:09:00 +0100 Subject: MySQLdb In-Reply-To: References: Message-ID: <20020323120859.GA325@lilith.hqd-internal> * Dave Cole [2002-03-23 23:36 +1100]: > Michael> Is this the right list for general questions about using the > Michael> MySQLdb module? It's an OK place. MySQLdb author Andy Dustman has recently also opened up a mailing list for his Python modules. It can be found on his personal homepage, IIRC. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fdrake at acm.org Thu Mar 14 18:09:19 2002 From: fdrake at acm.org (Fred L. Drake) Date: Thu, 14 Mar 2002 18:09:19 -0500 (EST) Subject: [development doc updates] Message-ID: <20020314230919.8838E18ECEF@grendel.zope.com> The development version of the documentation has been updated: http://python.sourceforge.net/maint-docs/ Current version of docs in preparation for the 2.2.1 candidate. From greg at cosc.canterbury.ac.nz Thu Mar 21 20:25:09 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 22 Mar 2002 13:25:09 +1200 Subject: A question about generators References: Message-ID: <3C9A87F5.8EA76936@cosc.canterbury.ac.nz> Richard J Kuhns wrote: > > That's EXACTLY what I did :). The main reason I had problems to start with > is that almost everything I've done with python feels more-or-less > "elegant", and this doesn't. Well, generators weren't designed for the sort of problems that require restartability. Is there some reason you absolutely can't just create a new instance of the generator each time you need to restart? That would be the most elegant way, if you can manage it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From tim at vegeta.ath.cx Mon Mar 11 05:16:20 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Mon, 11 Mar 2002 10:16:20 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> Message-ID: Eric Brunel graced us by uttering: > Hans Nowak wrote: >> It's not April 1st yet... It's not a joke. In fact, it's been discussed several times in this NG. http://groups.google.com/groups?hl=en&selm=slrn9uvnid.pe3.tim%40vegeta.ath.cx > Can anyone using a recent version of Microsoft development tools > confirm whether it's a hoax or not? Yup. I don't use the software, but MS still has the EULA on their site. Here's the link... still good after these several months. http://msdn.microsoft.com/Downloads/eula_mit.htm > If it isn't, this is bad news... AFAIK, this is only on this (and maybe a few other packages of) software. I'd be interested to see if Microsoft tries this again, what with their pseudo-victory and several more pending lawsuits... ...which reminds me... * off to http://userfriendly.org/ * ;) Tim Hammerquist -- No prisoner's dilemma here. Over the long term, symbiosis is more useful than parasitism. More fun, too. Ask any mitochondria. -- Larry Wall in <199705102042.NAA00851 at wall.org> From syver-en+usenet at online.no Tue Mar 26 07:38:21 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 26 Mar 2002 12:38:21 GMT Subject: running python on win2k References: Message-ID: "stclaus_imi" writes: > hi, all of you. > > i downloaded python for win2k. i wonder how to run it via the command > > line and over the apache/iis web server. > For using in cgi script with IIS use inetmgr (mmc snap in for iis) and configure the App Mappings for the .py ending to python "%s" %s. -- Vennlig hilsen Syver Enstad From jason at jorendorff.com Mon Mar 4 18:16:07 2002 From: jason at jorendorff.com (Jason Orendorff) Date: 4 Mar 2002 17:16:07 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 4) Message-ID: <94973796EA6A3423.37249018D69BC20F.284B57DC21EAB740@lp.airnews.net> QOTW: "What I find most amusing about com and .NET is that they are trying to solve a problem I only had when programming using MS tools." -MaxM http://groups.google.com/groups?th=5e0d677b44e1e91a "I suppose the fact that I get 20 emails in response to this question is a sign, I know you couldn't get 20 positive third party comparisons of VB to Python." -Stefan Kuzminski on Python advocacy http://groups.google.com/groups?th=f1ec289d99f2be87 "It COULD be a feature despite its creepy-crawly, six-legged, hive-dwelling, crumb-eating nature." -Raymond Hettinger on a little-known Python quirk http://groups.google.com/groups?selm=a5v1r1%24aji%241%40bob.news.rcn.net "As Zenin points out, Python uses objects to emulate closures, whereas Lisp uses closures to emulate objects." -Martin v. L?wis http://groups.google.com/groups?th=7ae69320e338064a Martin v. L?wis revives and revises PEP 263. It aims to treat Python code itself as Unicode data, enabling programmers to include Unicode strings in Python programs more naturally. http://groups.google.com/groups?th=ae0e91b136e81f15 http://python.sourceforge.net/peps/pep-0263.html Gerhard H?ring shows how to play an MP3 file using pygame. (Five lines of code.) http://groups.google.com/groups?selm=mailman.1015034704.11911.python-list%40python.org http://www.pygame.org/download.shtml Papercut is a multi-threaded news server written in Python. http://pessoal.org/papercut/index.php Decompyle converts Python byte-code back into Python source. http://www.goebel-consult.de/decompyle/ TWAIN is an industry standard API for scanners, digital cameras, and other imaging equipment. A new extension provides TWAIN for Python. http://twainmodule.sourceforge.net/ JPE 2.0 is released. JPE, the Java-Python Extension, allows CPython programs to call Java code - and vice versa. http://jpe.sourceforge.net/ The UN Bot intelligently navigates Quake 2 game worlds. The goal: human-like exploration behavior. (Scriptable in Python, of course.) http://bots.ai-depot.com/UN-Bot.html py2html.py version 0.7 converts Python code to color-coded XHTML. http://www.egenix.com/files/python/SoftwareDescriptions.html#py2html.py http://www.egenix.com/files/python/py2html.py.html PyChecker checks Python programs for common mistakes. A mailing list has been created for PyChecker discussion: http://lists.sourceforge.net/lists/listinfo/pychecker-list PyBoids - Flocking behavior fun in Python. http://www.dma.org/~tw/pyboids/ ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning, ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From eppstein at ics.uci.edu Wed Mar 6 22:19:42 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 19:19:42 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , "Arthur Siegel" wrote: > >And please avoid the ad-hominems ("too lazy to learn the >language"), it > doesn't contribute to rational debate. > > And I would beg you to amend your PEP to remove reference to novice users. > This has become the Mom and Apple Pie of PEP writers. And I have yet to see > it in the context of the most straight forward meaning - to remove barriers > to learning to program for people motivated to learn to program. I apologize for the unclarity. I meant to refer to competent programmers in other languages who are novices at Python programming. But maybe that is not the best group of people to refer to, otherwise we would be debating proposals for C-like for(x;y;z) syntax. From SBrunning at trisystems.co.uk Thu Mar 21 08:26:59 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 21 Mar 2002 13:26:59 -0000 Subject: How to install pychecker? Message-ID: <31575A892FF6D1118F5800600846864DCBCE6A@intrepid> > From: Dale Strickland-Clark [SMTP:dale at riverhall.NOTHANKS.co.uk] > In the absence of any instructions (that I can find) I tried unzipping > it to a directory and running setup.py. > > I got this: > > C:\Program Files\pychecker-0.8.10>setup.py > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: no commands supplied setup.py install Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From phd at phd.pp.ru Mon Mar 4 12:38:34 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 4 Mar 2002 20:38:34 +0300 Subject: open() error ---- what am I missing? In-Reply-To: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com>; from torstenson@no-spam.oti-hsv.com on Mon, Mar 04, 2002 at 11:31:46AM -0600 References: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com> Message-ID: <20020304203834.C11643@phd.pp.ru> On Mon, Mar 04, 2002 at 11:31:46AM -0600, Eric Torstenson wrote: > self.fLog=open(filename, mode='w') > IOError: invalid argument: w Do you have the os module imported? Especially in the form "from os import *" or "from os import open"? Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From eric.brunel at pragmadev.com Mon Mar 4 10:03:05 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 4 Mar 2002 15:03:05 +0000 Subject: Response to resizing window References: Message-ID: Hi Xiao-Qin, Xiao-Qin Xia wrote: > I want to redraw the chart whenever the window is resized. Anybody > can show me how to do it? (I guess I need something like WM_DELETE_WINDOW) A regular binding on "" events should do the trick. HTH - eric - From mstenner at phy.duke.edu Fri Mar 15 10:05:41 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 15 Mar 2002 10:05:41 -0500 Subject: line-by-line file read In-Reply-To: <7xhenix861.fsf@ruckus.brouhaha.com>; from phr-n2002a@nightsong.com on Fri, Mar 15, 2002 at 05:38:46AM -0800 References: <7xhenix861.fsf@ruckus.brouhaha.com> Message-ID: <20020315100541.A17443@phy.duke.edu> On Fri, Mar 15, 2002 at 05:38:46AM -0800, Paul Rubin wrote: > Michael Stenner writes: > > I often find myself reading and processing a file line-by-line. The > > way I usually end up doing it goes something like this > > > > fo = open(filename) > > line = fo.readline() > > while line: > > # do the processing on "line" here > > line = fo.readline() > > fo.close() > > ... > > Anyway... just wondering if there's a preferred way to do this. > > fo = open(filename) > for line in fo.xreadlines(): > # process the line > fo.close() Ahh... thank you, Paul (and others). I had been looking at the 1.5.2 docs (for good reason). I've been finding lots of reasons to go with 2.x lately... looks like I found another one :) -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From bokr at oz.net Sun Mar 3 17:11:50 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Mar 2002 22:11:50 GMT Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: On 3 Mar 2002 12:50:24 GMT, scarblac at pino.selwerd.nl (Remco Gerlich) wrote: >Cromwell, Jeremy wrote in comp.lang.python: >> If python was to allow "for i in 5:", is there any other meaning that would >> be appropriate besides the one detailed in PEP 276? > >Yes. > >It should give an error - 5 is not a sequence, so 'i in 5' is nonsense. > No, it's not nonsense. 'i in 5' is a probability, so for i in 5: do_this() should have an i/5.0 chance of executing do_this(). ;-)) From tejarex at yahoo.com Sat Mar 23 10:23:12 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 23 Mar 2002 15:23:12 GMT Subject: Sorting distionary by value References: <7xd6xwntgx.fsf@ruckus.brouhaha.com> Message-ID: "John Machin" wrote in message news:c76ff6fc.0203230339.48961684 at posting.google.com... > Paul Rubin wrote in message news:<7xd6xwntgx.fsf at ruckus.brouhaha.com>... > > counts = {} > > a = string.split(open(sys.argv[1],'r').read()) > > for w in a: > > if counts.has_key(w): > > counts[w] += 1 > > else: > > counts[w] = 1 > > > > words = counts.keys() > > words.sort() > > words.reverse() > > > > for w in words: > > print words[w], w > > Sorry, but this doesn't work. If you were to actually *run* your code, > you would get this result [after adding > > import string, sys > > at the start of the script]: > > print words[w], w > TypeError: sequence index must be integer ... > Try replacing the last part of the script with: > > words = [(-count, word) for word, count in counts.items()] > words.sort() > for count, word in words: > print word, -count or, I believe, change the last line to print counts[w], w From grante at visi.com Wed Mar 20 14:58:32 2002 From: grante at visi.com (Grant Edwards) Date: Wed, 20 Mar 2002 19:58:32 GMT Subject: Attachments to the list/group - OK? (Was Re: Popular style document?) References: Message-ID: In article , brueckd at tbye.com wrote: > On Wed, 20 Mar 2002, Andy Gimblett wrote: > >> I've just noticed that most people seem to embed their code directly >> into their messages. Is attaching .py files (or any other >> non-binaries) frowned upon around here? > > I won't speak for others, but the likelihood of me opening an attachment > to look at code is close to zero... just too annoying. I wasn't aware that the "attachment" concept was even applicable to Usenet articles. -- Grant Edwards grante Yow! If I had a Q-TIP, I at could prevent th' collapse visi.com of NEGOTIATIONS!! From jkraska at san.rr.com Fri Mar 15 23:16:53 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 16 Mar 2002 04:16:53 GMT Subject: Help Required References: Message-ID: d1,uid2,uid3....and so on.( Notice there is no space) > >However when i am trying to create the uid list it gives >uid1, uid2, uid3,...and so on. The interpreter is your friend: >>> mylist = [] >>> for i in range(1,10): mylist.append( "myitem" +`i` ) >>> mylist ['myitem1', 'myitem2', 'myitem3', 'myitem4', 'myitem5', 'myitem6', 'myitem7', 'myitem8', 'myitem9'] >>> C// From martin at v.loewis.de Tue Mar 12 15:51:44 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Mar 2002 21:51:44 +0100 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: "Samuele Pedroni" writes: > And what datapoints we acquire through the article? I think the article states a number of facts properly: "Despite his best efforts, there just isn't a lot of interest from the community in seeing Python move further into the Microsoft compound." Certainly true; there is little interest in Python.NET in the Python community (just as there is little interest in other branches, such as Stackless, Psyco, and, to some degree, Jython). "Hammond says Python developers tend to be wary and sceptical of Microsoft's motives" I'm quite sure Hammond said that, and I also agree with Mark. I'm myself wary and sceptical of Microsoft motives, and I know many other people who are. "Hammond was working for Active State, a Canadian software tools developer, but was laid off two months ago." This fact is not news to us, but may be to other readers. "One of the problems Hammond and de Icaza face is the morass of confusion surrounding the exact nature of .NET. Microsoft may have deliberately muddied the waters, confusing the casual IT user and business managers especially." That is certainly not overstated. I find confusion over what .NET exactly is and does among my peers, and I agree that Microsoft itself is source of some of the confusion. Regards, Martin From loredo at astro.cornell.edu Mon Mar 25 17:41:15 2002 From: loredo at astro.cornell.edu (Tom Loredo) Date: Mon, 25 Mar 2002 17:41:15 -0500 Subject: Installing Piddle plotting 1.014 on a Macintosh. Problems. References: <250320021555391378%pecora@anvil.nrl.navy.mil> Message-ID: <3C9FA78B.B7E0E902@astro.cornell.edu> Lou- I can't vouch that Piddle has been updated to work properly this way on the Mac, but what you should try is to drop the "setup.py" file on the *Interpreter* (not the IDE), and when a command window pops up, type in "build" (to build the package in the current directory) or "install" (to build it and copy it to your site-packages directory so it is accessible elsewhere). As long as Piddle doesn't do something out of the ordinary, this should work on a Mac (though if Piddle builds C extensions, you'll need to have a copy of Codewarrior somewhere on your drive, and if you don't have the newest version check the MacPython page for info on what to change to get compatibility with old Codewarrior). -Tom Loredo From James_Althoff at i2.com Tue Mar 5 15:03:48 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 12:03:48 -0800 Subject: Status of PEP's? Message-ID: [Fernando P?rez] > When 'for i in 5' becomes valid, what we are saying is, the object '5' > knows how to count. *You* can say that if you like; but PEP 276 doesn't say that . It just proposes an iterator for class int whereby said iterator generates the -- well, I was about to use the word "natural", but I think I'll skip that -- "useful" sequence 0,1,...,n-1. > Apparently this is ok, but I see problems: '5' is an integer, > but there are also negative numbers in the integers. So how do we > interpret 'for i in -3'? PEP 276 (currently) proposes that "for i in -3" acts just like "for i in xrange(-3)" currently does. Carel Fellinger suggests that it might be quite handy to have it act just like "for i in xrange(-1,-3-1,-1)", instead. And Emile van Sebille, with only a semi-smiley attached (a smiley semi-attached?) suggests that the reverse ordering would be better, should the empty set not be returned in such a case. > While one can argue that 0..4 is a 'natural' way to count for > positive integers, the same argument becomes difficult to make > for negative numbers. And by the way, as far as counting goes one > could argue that 1..5 is even more natural, as it truly spans the > set of the natural numbers of which 5 is a member, as opposed to Bet you didn't think *that* was going to be so controversial . > the less 'standard' set of the 'non-negative integers less than 5'. > But that's a minor nit-pick. Easy answer: forget about "counting" and consider this interesting excerpt from range.__doc__ "For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements." Take special note of the last sentence . > The problem in my view is that when something is an object, its > methods should do something which is reasonably natural and well defined > for _all_ instances of a class. So when we ask the integers to have a > counting method (via an iterator), I would want to have that counter > behave sensibly for _any_ integer. And unfortunately, there's just no way > to make such a definition IMHO. Why is there "just no way to make such a definition"? Please consider the following: for integer n, iter(n) produces the same values as iter(xrange(n)) > So this ends up introducing lots of context-sensitivity and > special-casing (things work _this_ way for non-negative integers, > which is not too clean but commonly useufl, and do _that_ for negative > ones because someone thought it would be a usefu default...) Down that > road lies Perl, and it seems to break very harshly the 'explicit is better > than explicit' principle of Python design which I feel has served the > language so well thus far. That seems a lot more complicated than PEP 276 . > So in summary, it's not that I dislike integers being treated > truly as objects, but rather that I want them to be clean objects. > Objects whose methods behave in sensible ways for all instances of a > class, not full of special defaults. PEP 276 merely suggests that "for i in -3" should crash your program in the same way that "for i in xrange(-3)" does . Jim From mcfletch at geocities.com Mon Mar 11 03:40:41 2002 From: mcfletch at geocities.com (Mike C. Fletcher) Date: Mon, 11 Mar 2002 03:40:41 -0500 Subject: How to compute sunset and dawn times with python? References: <22722a23.0203080841.3ed7166a@posting.google.com> Message-ID: <3C8C6D89.2090302@geocities.com> Since it seems no-one has responded, I put together a quicky module showing a way to do this. The code is taken from a US Gov't (SRRB) web-site, but it's billed as "low accuracy", so don't take it as gospel (it's off by a minute in 2 of the 6 test dates I tried against the online (accurate) one). This web-site has a javascript implementation of certain of the functions that are used in the online version someone who wanted could translate those. The Python module is available here: http://members.rogers.com/mcfletch/programming/ (sunriseset.py) SRRB Sunrise Calculator: http://www.srrb.noaa.gov/highlights/sunrise/sunrise.html HTH, Mike Tist Verdonck wrote: > Does anyone know how to compute sunset and dawn times with python? > > thanx, > Tist > _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From d_blade8 at hotmail.com Mon Mar 25 18:50:12 2002 From: d_blade8 at hotmail.com (Lemniscate) Date: 25 Mar 2002 15:50:12 -0800 Subject: Random... References: Message-ID: <7396d2b2.0203251550.6abf0664@posting.google.com> I would tend to agree with this approach, for simplicity. One could take it to an extreme and have a program that creates a file and writes large random numbers to the file until the file is nothing but a huge (HUGE) string of numbers (with a file size in the MBs). What you may end up with a number that is a couple of million digits long. Then, you write a module to access it. The module will ask the user how many digits they desire in their random number, the module will start off at a arbitrary point in the file and read that many digits. The module will convert the string of numbers into a L and return it. Alternatively, write a program that will seed a random number [0-9] and add it to a string 'x' times where x is the number of digits desired. Something like: def CustomRandom(NumberOfDigits = 95): myDigits = NumberOfDigits #if you want some sort of default use this line, not the next myDigits = raw_input("How many digits?\n>>> ") myString = "" for x in range(myDigits): random_num = myString += random_num You just have to make sure you use a good method to generate your random digits. I used something like this once to test some software for stuff like buffer overflow problems. It was relatively easy once I got started. Later. Uwe Schmitt wrote in message news:... > FREDRIK HULDTGREN wrote: > | I want to generate random numbers, very large random numbers. If I use > | randrange() I get an out of bounds error since it only supports numbers > | up to (2**31)-1. However, I can use uniform(), but then I get the number > | returned in 7.9655120654553743e+018 or something simaler, and I would > | rather have it in a "L" format(796551206545537430183218312890381031L). > | How do I do this? > > | thanx > | /Fredrik > > You could generate two random numbers and clue them together to > a longer number. > > there is a mp (multip precision) library at http://gmpy.sourceforge.net > > Greetings, Uwe From ozren_lasic at yahoo.com Tue Mar 5 21:43:20 2002 From: ozren_lasic at yahoo.com (Ozren Lasic) Date: 5 Mar 2002 18:43:20 -0800 Subject: Why KeyError ??? Message-ID: <7dee885c.0203051843.36efa5c2@posting.google.com> Why KeyError ???. Microsoft(R) Windows NT(TM) (C) Copyright 1985-1996 Microsoft Corp. C:\>python -S Python 2.1.2 (#31, Jan 15 2002, 17:28:11) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> import sys >>> sys.setdefaultencoding("cp1250") >>> a = "\xe7\xd0\x9f\x86\xa7" # Croatian characters >>> b = unicode(a) >>> b u'\xe7\u0110\u017a\u2020\xa7' >>> c = {} >>> c[a] = 1 >>> c[b] Traceback (most recent call last): File "", line 1, in ? KeyError: šđčćž >>> a == b 1 Thanks !!! From rloisel at helicon.net Wed Mar 20 17:03:16 2002 From: rloisel at helicon.net (Rodney Loisel) Date: Wed, 20 Mar 2002 17:03:16 -0500 Subject: error:"_imaging C module is not installed" References: <3C989278.9189857C@helicon.net> Message-ID: <3C990724.E6DFDF53@helicon.net> Fredrik Lundh wrote: > Rodney Loisel wrote: > > > Have 2 files (_imaging.pyd and _imagingtk.pyd) which I assume are the > > C imagaging modules and have put copies of them in all the directories > > that they might be accessed in > > for some more clues, try this: > > c:> python -v > Python 2.2.1c1 ... > >>> import _imaging > > and see what happens. > > C:\WINDOWS\Desktop>python -v # C:\PYTHON22\lib\site.pyc matches C:\PYTHON22\lib\site.py import site # precompiled from C:\PYTHON22\lib\site.pyc # C:\PYTHON22\lib\os.pyc matches C:\PYTHON22\lib\os.py import os # precompiled from C:\PYTHON22\lib\os.pyc import nt # builtin # C:\PYTHON22\lib\ntpath.pyc matches C:\PYTHON22\lib\ntpath.py import ntpath # precompiled from C:\PYTHON22\lib\ntpath.pyc # C:\PYTHON22\lib\stat.pyc matches C:\PYTHON22\lib\stat.py import stat # precompiled from C:\PYTHON22\lib\stat.pyc # C:\PYTHON22\lib\UserDict.pyc matches C:\PYTHON22\lib\UserDict.py import UserDict # precompiled from C:\PYTHON22\lib\UserDict.pyc # C:\PYTHON22\lib\copy_reg.pyc matches C:\PYTHON22\lib\copy_reg.py import copy_reg # precompiled from C:\PYTHON22\lib\copy_reg.pyc # C:\PYTHON22\lib\types.pyc matches C:\PYTHON22\lib\types.py import types # precompiled from C:\PYTHON22\lib\types.pyc # C:\PYTHON22\lib\__future__.pyc matches C:\PYTHON22\lib\__future__.py import __future__ # precompiled from C:\PYTHON22\lib\__future__.pyc Python 2.2.1c1 (#32, Mar 18 2002, 13:23:09) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import _imaging Traceback (most recent call last): File "", line 1, in ? ImportError: DLL load failed: One of the library files needed to run this application cannot be found. >>> rod loisel From jeff at ccvcorp.com Thu Mar 28 15:01:15 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 28 Mar 2002 12:01:15 -0800 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: <3CA3768B.32BB6AC9@ccvcorp.com> phil hunt wrote: > IIRC in Awk you can just say: freq[word] ++ and it works > correctly even when there is no pre-existing index of word in freq. > > IMO it's a pity Python isn't like that. I disagree. I'm just as happy that Python doesn't try to guess what would be a suitable "default" value for non-existent keys. It seems to me to be entirely consistent with the philosophy of "explicit is better than implicit". Why presume that somedict[key] should default to 0, instead of to an empty string, or to None, or to [], or... ??? Jeff Shannon Technician/Programmer Credit International From timr at probo.com Sun Mar 10 02:15:37 2002 From: timr at probo.com (Tim Roberts) Date: Sat, 09 Mar 2002 23:15:37 -0800 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> Message-ID: morton at dennisinter.com (damien morton) wrote: >Ok, I see how this works. > >' in ' would always returns false; as the elements >of a are all characters you can never find amongst >them (unless its a string of length 1). > >Its counter-intuitive for someone playing with strings as strings >rather than as sequences of characters, however. Many things that are "intuitive" are also wrong. >'c' in 'the quick brown fox' -> 1 >'fox' in 'the quick brown fox' -> 1 (instead of TypeError) > >Is there any circumstance where youd expect (or want) the later not to >work? I expected and wanted it to work (but instead got an error), its >quite a clear and unambiguous expression (for strings only). It would be a clear and unambiguous expression _if_ the "in" operator was a substring search operator, but it is not. It is a set membership operator. It works EXACTLY the same way on all sequence types: the right-hand operand is a sequence, and the left-hand operand is something that can be an element of that sequence type. You are suggesting an unorthogonal change just because it is easier to type than: 'the quick brown fox'.find('fox') No. That is NOT a good reason to change a language in an inconsistent way. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From weeks at vitus.scs.agilent.com Mon Mar 4 20:48:21 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Tue, 5 Mar 2002 01:48:21 +0000 (UTC) Subject: HP-UX 10.2 deprecated? Message-ID: <1015292901.342132@cswreg.cos.agilent.com> Is HP-UX 10.2 deprecated for more recent versions of Python? There is at least one problem with the Python 2.2 ./configure for HP-UX 10.2 (see below). And when the problem is patched, the resulting "python" executable still doesn't pass "make test". On the other hand, when the system is built and tested on HP-UX 11 (even without the patch), everything is fine. Greg PS: Here's the problem with the Python 2.2 ./configure for HP-UX 10.2. To determine if _POSIX_THREADS is defined in unistd.h, it runs the C preprocessor on a file with the contents: #include #ifdef _POSIX_THREADS yes #endif Unfortunately, with the C preprocessor invocation used by ./configure, the indented #ifdef is not recognized, which results in the #ifdef construct being mindlessly echoed, which is erroneously interpreted as the answer "yes". This causes _POSIX_THREADS to not be defined in pyconfig.h, resulting in a bunch of undefined thread-related functions at link time. When I removed the indentation from the above #ifdef construct, the "make" of the executable was successful. Unfortunately, "make test" did not pass. From grey at despair.dmiyu.org Wed Mar 6 17:25:02 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 06 Mar 2002 22:25:02 -0000 Subject: The language vs. the environment References: <15494.34706.724985.628479@beluga.mojam.com> Message-ID: On Wed, 06 Mar 2002 13:21:35 -0800 (PST), Sean 'Shaleh' Perry wrote: > help release more python modules so perl mongers will quite wagging CPAN in > front of our faces. Quality over Quantity. :) -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From a.martin at perfectwww.de Mon Mar 11 17:47:07 2002 From: a.martin at perfectwww.de (Andreas Martin) Date: 11 Mar 2002 14:47:07 -0800 Subject: Ho to use a regular expression group reference as hash key Message-ID: Hallo ! I'm a Python newbie and I have the following problem: A hash person={"entry1":"value1","entry2":"value2"} and I would like to do a substitution with regular expression (an easy example) like this: pat = re.compile(r'(entry1)') t = pat.sub(person[\1],"something...entry1...something") I would like to substitute the "entry1" string by the respective hash element with the group reference \1 as hash key, that is to say t="something...value1...something". Similar in Perl: s/(entry1)/%person($1)/ I hope my problem is understandable. Thanks From bergeston at yahoo.fr Mon Mar 11 12:46:10 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Mon, 11 Mar 2002 18:46:10 +0100 Subject: lambda question References: Message-ID: lambda questionBoth work on my computer: PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> def exe1(f,list): ... return map(lambda x:eval(f),list) ... >>> f='x**3+2*x' >>> list=[0,1,2,0] >>> map(lambda x:eval(f),list) [0, 3, 12, 0] >>> exe1(f,list) [0, 3, 12, 0] >>> If you give us the kind of error, problem hou have, you will help us to help you. TIA ;-) "Alves, Carlos Alberto - Coelce" wrote in message news:mailman.1015866267.21439.python-list at python.org... Hi all, Look at the two codes below first code: f='x**3+2*x' list=[0,1,2,0] map(lambda x:eval(f),list) second code: def exe1(f,list): return map(lambda x:eval(f),list) Can someone explain to me why the first code works while second doesn't. Carlos Alberto COELCE/DPRON-Departamento de Projetos e Obras Norte Fone: 677- 2228 e-mail: calves at coelce.com.br \|||/ (o o) --ooo0-(_)-0ooo-- From greg at cosc.canterbury.ac.nz Wed Mar 6 21:14:06 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Mar 2002 15:14:06 +1300 Subject: Status of PEP's? References: <3C861BEB.60701@destiny.com> <20020306135242.GB10985@andy.tynant.ftech.net> Message-ID: <3C86CCEE.49E68592@cosc.canterbury.ac.nz> Andy Gimblett wrote: > > I've just seen PEP 212 which contains this very proposal... I've just looked at this PEP. Near the bottom it says: Implementations For all three solutions some more or less rough patches exist as patches at SourceForge: ... All of them have been pronounced on and rejected by the BDFL. Does that mean the whole idea has been rejected, or just those particular implementations? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From jadestar at idiom.com Thu Mar 14 20:50:55 2002 From: jadestar at idiom.com (James T. Dennis) Date: 15 Mar 2002 01:50:55 GMT Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> Message-ID: Dean Goodmanson wrote: >> I wonder how much interest there would be in a revival? >> Dinu > YES! > I've found Python to be an excellent learning environment for personal > development in software engineering and computer science. > Especially since the advent of > href="http://www.mindview.net/Books/TIPython" > Bruce Eckel's _Thinking in Python_ > and > http://vig.pearsoned.com/store/product/0,,store-562_banner-0_isbn-0130409561,00.html" > Thomas Christopher's _Python Programming Patterns_ > Best Regards, > Dean Christopher's book has almost nothing to do with "Patterns." While the "patterns" community is somewhat vague about the definition of "design patterns" Christopher employs a definition that's so nebulous as to be completely meaningless? It's sort of like saying "Chair: anything that could be sat upon, and the act of sitting, standing, or being, or anyone that sits, stands or is" (as in the chair of the meeting sat on the lawn, which was her chair). It's sort of like that, except that Mr. Christopher isn't nearly so clear or definitive on the topic of patterns. In a twenty chapter book he devotes one specifically to patterns. He lists twenty patterns that roughly correspond to most of the GoF patterns; but he doesn't ennumerate them so the reader who is familiar with the seminal GoF volume is left to wonder which three GoF design patterns were silently omitted, or to wonder if some were merged in some way. Mr. Christopher doesn't describe alternatives or controversies in the patterns (such as Martelli's "Borg" vs. the GoF "Singleton") However, the worst failing of this book is that it doesn't include cogent code examples. It seems to be floor clippings from scripts or small programs that he's used in his projects. The points under discussion in the running text are not isolated or highlighted in the code listings and the examples have little pedegogical value. One of his examples implements a priority queue by treating a list as a "heap" (his term); his example takes over 50 lines of code and he doesn't clearly show sample usage of this class. After awhile I abandonned my pondering of his code and wrote my own from scratch (as a dictionary of queues with a list of the keys to sort into priority order). I won't argue that mine code was better than his (since I didn't understand his code and I didn't have a clear API to emulate). However my code only took about 25 lines to implement, allowed me to have arbitrary priority designations (integers, reals, letters, anything sequence that was comparable and "sortable") and should have been pretty fast and lightweight (though I didn't rigorously profile it). The API I offered for mine was a superset of what I saw in his, adding items to a queue automatically created new queues as necessary (or could optionally raise an exception if one set an instance flag); empty queues are automatically removed from the dictionary and keylists; call ".next()" (with no specific priority) gets the first item in the "highest priority" queue); "highest priority" could be set at instantiation --- increasing or reverse sort/lexical order; etc. (The point is that his code example was confusing and long; and it would seem to be unnecessarily so if a mere student such as myself can produce something shorter, simpler and with roughly similar functionality. If his example offered some functional advantage that I could not discern, it suggests that it was not a good example or that it lacked supporting exposition in the accompanying text). In short I disliked this book. None of the code examples even approached the claim of "enterprise ready" that was proudly touted on the cover. These were examples of "programming in the small" rather than "in the large." (It did have one saving grace: the chapter or so on threading was clear and concise. I can't assure you that it was either comprehensive or entirely correct --- but it was a very good introduction to concurrency problems and to Python's elegant and simple threading support). From emile at fenx.com Thu Mar 7 08:16:13 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 7 Mar 2002 05:16:13 -0800 Subject: time date math problem References: Message-ID: Felix Seeger > Hi > > What I want: > > Date: > > 20.03.2002 > > 20.05.2002 - 21.00.0000 = 30.04.2002 > > mxDateTime includes that and more. Take a look at http://www.egenix.com/files/python/mxDateTime.html -- Emile van Sebille emile at fenx.com --------- From Oschler at earthlink.net Mon Mar 4 12:51:13 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Mon, 4 Mar 2002 12:51:13 -0500 Subject: Can Python do this? Message-ID: Hello, Python newbie here. Let's say I'd like to build a method name into a string variable (e.g. "FuncCall" + "1" to attempt to call "FuncCall1"). Can I then call that method by somehow having the interpreter evaluate the string variable into a call to the desired method? (I know this is usually done in a language like Prolog or Lisp but I'm hoping Python can do it too.) If so, can you point me to a good article or example of such that would show me the relevant Python syntax. Thanks. From ws at mystrobl.de Sun Mar 10 16:59:33 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Sun, 10 Mar 2002 22:59:33 +0100 Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> <1a9n8us1629mrvei40hdkuuerc1j6p318m@4ax.com> Message-ID: <9okn8ucu390vhk8nfhvb98c3aqotm2dllu@4ax.com> Sun, 10 Mar 2002 20:05:24 GMT, grante at visi.com (Grant Edwards): >I would think that for an isolated app, .so's would slow down >load times. With a statically linked program all you do is a >single memmap() call (well, ignoring a few details). With >.so's you've actually got to resolve all of the symbols and do >the linking step (not required for statically linked images). Windows DLLs are already linked. Please have a look at http://www.wd-mag.com/articles/2000/0012/0012b/0012b.htm Or find "Rebasing Win32 DLLs: The Whole Story" by Ruediger R. Asche on MSDN. Two quotes from that article: "All other things being equal, the size of the DLL does not matter; that is, the costs for loading a small DLL and a large DLL are pretty much equal. Thus, if possible, you should avoid writing a lot of small DLLs and instead write fewer large DLLs if load time is an issue for you. ..." "The single biggest factor that slows down the loading of DLLs is the location of the DLL. The documentation for LoadLibrary describes the algorithm that the operating system uses for locating the DLL image; a DLL located at the first search position (the current directory) loads in typically 20 percent or less of the time as the same DLL located deep down in the path loads. ..." -- Thank you for observing all safety precautions From jeffbi at jetsoft.com Thu Mar 21 12:39:52 2002 From: jeffbi at jetsoft.com (Jeff Bienstadt) Date: Thu, 21 Mar 2002 09:39:52 -0800 Subject: IntSpan? References: <3c97c886@news.nwlink.com> <3C99F049.5A78B149@metaslash.com> Message-ID: <3c9a1ae9$1@news.nwlink.com> "Neal Norwitz" wrote in message news:3C99F049.5A78B149 at metaslash.com... > Jeff Bienstadt wrote: > > > > Does there exist for Python something akin to the Set::IntSpan module for > > Perl? > > > > I'm looking for something that inteligently handles and manipulates spans > > of integers, such as: > > 2-356,456,458-500 > > I'm not familiar with IntSpan, but have you looked at the builtin range()? > >>> print range.__doc__ > range([start,] stop[, step]) -> list of integers > > Return a list containing an arithmetic progression of integers. > range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. > When step is given, it specifies the increment (or decrement). > For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! > These are exactly the valid indices for a list of 4 elements. > > > range(2, 356) > range(458, 500) > > or if you want the list above to be all together: > > range(2, 356) + [456] + range(458, 500) > > There aren't sets in python, but you can use a dictionary to emulate > sets. To create an intset with a dictionary: > > intset = {} > for i in range(2, 356) + [456] + range(458, 500): > intset[i] = 1 > > print intset.has_key(55), intset.has_key(457) > print intset.keys() > > I'm sure there are set implementations on ASPN. > > HTH, > Neal Thanks for your reply. Yes, I knew about range, but that's not quite what I'm looking for. Using range to create the full list of integers seems prohibitively expensive --- spans in the range 1-400000 are not at all out of line. I'm envisioning a class that stores (for example) a list of tuples and/or integers to express each portion of the span, such as [(2,356), 456, (458,500)] Then, the class might be asked to insert the value 457 into the span, which would then result in a "merging" of the items in the internal list, such as: [(2,356), (456, 500)] Other operations (removing a value or a sub-span, merging another span, etc.) would be useful as well. I can see from your reply how range could be useful in the implementation, for creating temporary lists of values to work with but again, since the spans could be quite long, this seems expensive. I'm sure that I can implement something like this myself, but I was hoping that such a thing already existed, because a) I would prefer to not have to re-invent the wheel, and b) existing code would almost certainly be better that anything I could write given my current (week-old!) knowledge of Python. (Also, the fact that the Perl module I mentioned uses Set is not really important, it just came up while I was searching --- further searching also turned up an Array::IntSpan Perl module. I'm not a Perl guy at all, and attempting to translate code from a language that I don't know at all into one that I am just learning strikes me as painful :-> ) If I can't find anything that already does what I'm looking for, I'll go ahead and tackle it myself. Again, thanks for your reply. ---jkb From martinkaufmann at yahoo.com Thu Mar 14 21:30:02 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Fri, 15 Mar 2002 02:30:02 +0000 (UTC) Subject: Question about scientific calculations in Python References: <1pgu8u4nqjj8hbghv20s9osn9721uhlevg@4ax.com> Message-ID: On Thu, 14 Mar 2002 01:21:43 +1300, Martin Kaufmann wrote: > On Wed, 13 Mar 2002 00:13:50 -0600, "Jason Orendorff" > wrote: > >>Keep in mind, though, that the code I wrote creates a huge 2D array >>when it is presented with largeish 1D arrays as arguments. >> >>So if s_vector is 10000 elements and r_vector is 10000 elements, >>then a 800-MB array is created. If you've got the RAM, this is >>okay; otherwise you're in trouble. > > The machine I'm using for my calculations has 2 GB of memory. And the > vectors probably have only about n00-n000 entries. Well, unfortunately I have to add that my estimate was too low. For smaller clusters the numeric solution runs fine and is fast, but for clusters over 1000 atoms it crashes ("MemoryError: can't allocate memory for array"). I also found out that my colleague is able to run his C program (containing similar calculations) about 1'000'000 in 10 hours. He does need that many cycles for Reverse Monte Carlo simulations. As I will probably have to do similar simulations in the future I guess I have to switch to C completely. Regards, Martin From shalehperry at attbi.com Thu Mar 28 15:24:27 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 28 Mar 2002 12:24:27 -0800 (PST) Subject: ConfigParser -> Section name through Option value In-Reply-To: <3CA375B1.9070802@flexis.de> Message-ID: On 28-Mar-2002 domi wrote: > Hi, > > can somebody help me with this ConfigParser (ini-file) problem: > Is it possible to get a Section name through an Option value > (ConfigParser), e.g.: > > [foo] > name = python > ... > > how can I get the section name 'foo' through the option value 'python'? > Any idea??? > doesn't look possible without touching the classes internal data structures. The file format is just not meant to be used in this way. You also seem confused over the term option and section. 'section' refers to 'foo' in your example. 'name' is an option whose value is 'python'. From niemeyer at conectiva.com Fri Mar 22 13:36:48 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Fri, 22 Mar 2002 15:36:48 -0300 Subject: Python & IRC In-Reply-To: <20020321043439.GA2043@lilith.hqd-internal> References: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> <20020321043439.GA2043@lilith.hqd-internal> Message-ID: <20020322153648.A11825@ibook.distro.conectiva> > xchat's Python support sucks. They even admit it in the docs. I've rewritten it from the ground. This new version has full thread support, output directly into XChat window, python console to play around, a more pythonic API, etc. It will probably be included in XChat 2.0+. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From cfelling at iae.nl Sat Mar 2 00:12:13 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 2 Mar 2002 06:12:13 +0100 Subject: Status of PEP's? References: Message-ID: Jeff Hinrichs wrote: > What you are asking everyone to agree with is: > 5 = [0,1,2,3,4] No he isn't:) He explicitly says he doesn't think of sequences at all. ... > If you were to restate the above as: > f(5)=[0,1,2,3,4] > Then, I believe, that you wouldn't have any problem convincing a large > majority that it is possible for f() to produce such an output. That being And this is precisly what he's proposing, f is called iter in his case. He comes from the camp that sees everything as an object, so numbers are objects to. Hence integers know to do things, like adding, subtracting, and ... counting! Three knows how to count from zero upto but not including three. If you accept this, then the discussion is not whether integers are sequences, but whether it's natural to stretch Python's `for' construct to mean `count' or `over its preceding numbers' in case of an integer. Like the `for' construct recently got stretched to mean `over all lines' and `over its keys' for text-files and dictionaries. Admitted in those cases it still was a clear `iterate over', but the what was debatable. > said, I would find that the argument favors the use of range/xrange over the > concept of iterable integers. I'm still concerned how it releates to `programming for everybody', as that goal is a sure measure to keep Python lean and simple. -- groetjes, carel From cfelling at iae.nl Fri Mar 1 16:54:11 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 1 Mar 2002 22:54:11 +0100 Subject: __abs(self)__? References: Message-ID: Mike Carifio wrote: > I'm reading about special method names. __abs__(self), which maps to the > abs() method seems unneccessary(?). > So: > class ExampleNumber: > def __init__(self, initializer): > self.value = initializer > def __abs__(self): > return abs(self.value) >>>> x = ExampleNumber(-1) >>>> x.abs() > 1 strange, you haven't defined a method `abs' for `ExampleNumber's! I would expect: Traceback (most recent call last): File "", line 1, in ? AttributeError: ExampleNumber instance has no attribute 'abs' >>> unless you typed: >>> abs(x) in which case x.__abs__() is called under the hoods. > abs is a builtin function, so why do I need a special name for a function? > I'm missing something... many builtins work on instances of user defined classes by expecting a special named method (those methods names are easily recognizable due to the leading and trailing double underscores) So you have a generic builtin fucntion abs, you use it on integers and homebrew number classes alike, `abs(instance)' and all works as it should. -- groetjes, carel From Greg.Lindstrom at acxiom.com Mon Mar 18 13:42:13 2002 From: Greg.Lindstrom at acxiom.com (Lindstrom Greg - glinds) Date: Mon, 18 Mar 2002 12:42:13 -0600 Subject: py2exe and Tkinter Message-ID: Please excuse me if this is not the correct forum, and gently point me to the correct list. I am attempting to create a standalone application that has a GUI generated with Tkinter. I have a myfile.exe that was generated from py2exe, but when I try to execute it (both by double clicking and trying to launch it from a DOS command line) I get nothing. Do I need to do anything "special" to my all to work? I'm on Windows 2000 "Professional" using Python 2.2. Thanks! --greg ********************************************************************* The information contained in this communication is confidential, is intended only for the use of the recipient named above, and may be legally privileged. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication is strictly prohibited. If you have received this communication in error, please re-send this communication to the sender and delete the original message or any copy of it from your computer system. Thank You. From stefan.heimann at web.de Wed Mar 6 04:39:24 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 6 Mar 2002 09:39:24 GMT Subject: Getting stdout and stderr from popen Message-ID: Hi! I want to launch an external process and have stdout and stderr redirected to one output stream, something like f = os.popen('cvs status 2>&1') does the right thing, but does not work on all platforms. If I write pin, pout, perr = os.popen3('cvs status') I get the output of stderr and stdout but not in the right order. I tried also sys.stderr = sys.stdout f = os.popen('cvs status') f.read() but still I get only the output from stdout (what cvs outputs on stderr is written directly to the console). Any help would b great! Thanks and bye Stefan From kfarmer at thuban.org Mon Mar 18 01:23:28 2002 From: kfarmer at thuban.org (Keith Farmer) Date: Mon, 18 Mar 2002 06:23:28 GMT Subject: Windows Scripting Component weirdness Message-ID: I modified \Python\Lib\site-packages\win32com\test\testPys.sct into WSCTest.wsc, source below. Running the testPyScriptlet.js code (also below) seems to reveal that I am unable to set properties on the instantiated object. No errors are brought up -- the code just behaves as if I never assigned new values to the properties. What am I doing wrong, assuming that the WSH is behaving properly? ---------- Keith J. Farmer kfarmer at thuban.org http://www.thuban.org ########## WSCTest.wsc: ########## testPyScriptlet2.js: function print(msg) { WScript.Echo(msg) ; } var thisScriptEngine = ScriptEngine() ; var majorVersion = ScriptEngineMajorVersion() ; var minorVersion = ScriptEngineMinorVersion() ; var buildVersion = ScriptEngineBuildVersion() ; var m = "" ; WScript.Echo(thisScriptEngine + " Version " + majorVersion + "." + minorVersion + " Build " + buildVersion) ; var scriptlet = new ActiveXObject("Thuban.Test.WSCTest") ; print("Getting PyProp1"); m = scriptlet.PyProp1 ; print("PyProp1 = " + m) ; m = scriptlet.PyProp2 ; print("PyProp2 = " + m) ; print("PyMethod1() = " + scriptlet.PyMethod1()) ; m = scriptlet.PyProp1 ; print("PyProp1 = " + m) ; print("PyMethod2() = " + scriptlet.PyMethod2()) ; scriptlet.PyProp2=scriptlet.PyMethod2() ; m = scriptlet.PyProp2 ; print("PyProp2 = " + m) ; From ark at research.att.com Mon Mar 11 10:10:25 2002 From: ark at research.att.com (Andrew Koenig) Date: Mon, 11 Mar 2002 15:10:25 GMT Subject: Python on Windows soon forbidden by Micro$oft? References: Message-ID: Eric> Hi all, Eric> Found the following link on comp.lang.tcl. A bit long, but worth reading... Eric> http://groups.google.com/groups?hl=en&selm=3B40A4A7.6E39BD%40brad-aisa.com&rnum=1 I must say that the words of the license agreement do not seem to me to have the effect that the article claims that they have. Rather, it seems to me that Microsoft is saying that they will not allow their products to be used in any way that might potentially compel Microsoft to disclose any of their own source code. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From robin at jessikat.fsnet.co.uk Fri Mar 29 16:04:14 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 29 Mar 2002 21:04:14 +0000 Subject: string copying Message-ID: Is there some special reason why python inhibits string copying. I suppose there's some attempt being made to make these constants. To make differing versions of 'abc' one has to resort to silliness like 'ab'+'c' PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32.Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> s='abc' >>> import copy >>> s is copy.copy(s) 1 >>> s is copy.deepcopy(s) 1 >>> s is 'ab'+'c' 0 >>> -- Robin Becker From oivvio at polite.se Tue Mar 26 10:26:58 2002 From: oivvio at polite.se (oivvio at polite.se) Date: Tue, 26 Mar 2002 16:26:58 +0100 Subject: Optimizations (was Re: reduce vs. for loop) In-Reply-To: References: Message-ID: <20020326152658.GB907@matijek> On Tue, Mar 26, 2002 at 10:05:19AM -0500, Aahz wrote: > > def fact3(n): > mul = operator.mul > return reduce(mul, range(1L, n+1) ) faster than fact1 slower than fact2 > > "We should forget about small efficiencies, about 97% of the time. > Premature optimization is the root of all evil." --Knuth I know. I was just curious :) -- oivvio polite cell +46 (0)709 30 40 30 / phone +46 (0)8 669 64 18 / fax +46 (0)8 84 00 18 varvsgatan 10A / s-117 29 stockholm / sweden From QnickQm at alum.mit.edu Thu Mar 7 14:23:59 2002 From: QnickQm at alum.mit.edu (Nick Mathewson) Date: Thu, 07 Mar 2002 19:23:59 GMT Subject: [GERMAN] "ziegenproblem" References: Message-ID: In article , stefan antoni wrote: [...] > i want to write this basic code in python: > http://www.google.de/search?q=3Dcache:Uugc3CH9SOQC:home.spektracom.de/ellri= > ch/Ziegen.htm+ziegenproblem+basic+programm&hl=3Dde Sadly, I don't know enough German to understand what is going on, but given the original basic: 140 CLS : RANDOMIZE TIMER: PRINT 150 PRINT "Von 2000 Wechseln waren ": PRINT 160 FOR i = 1 TO 10 170 r = 0: f = 0 180 FOR j = 1 TO 2000 190 a = INT(3 * RND + 1) 200 w1 = INT(3 * RND + 1) 210 m = INT(3 * RND + 1) 220 IF (m = a) OR (m = w1) THEN 210 230 w2 = 6 - m - w1 240 IF w2 = a THEN r = r + 1 250 IF w1 = a THEN f = f + 1 260 NEXT j 270 PRINT "richtig:"; r; "falsch:"; f 280 NEXT i 290 END This is the most literal Python translation I could write: import random def rnd(): ' returns one of (1,2,3) at random. ' return int(3*random.random() + 1) print "\nVon 2000 Wechseln waren \n" for i in range(1,11): r = 0; f = 0 for j in xrange(1,2001): a = rnd() w1 = rnd() m = rnd() while m in (a, w1): m = rnd() w2 = 6 - m - w1 if w2 == a: r += 1 if w1 == a: f += 1 print "richtig: %s falsch: %s" % (r,f) I'm-guessing-the-last-pair-is-true-or-false-but-darned-if-I-know- what's-going-on-ly yrs, -- Nick Mathewson Remove Q's to respond. No spam. From tim.one at comcast.net Sun Mar 31 12:56:52 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 31 Mar 2002 12:56:52 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Message-ID: [Ralph Corderoy, to Guido] > What do you think of `truth(x)' for all the good reasons listed > elsewhere in the thread? You used truth yourself instead of Boolean > above. Actually, he didn't. True story: we (PythonLabs) recently chatted with Jim Fulton (Zope Corp's CTO, Guido's boss, and very long-time Python user) about truth values in Python. Jim declaimed that he always wished Python had a function to convert Python's notion of true/false into an integer 1/0, and suggested that "truth()" would be a good name for it. He didn't realize that operator.truth() was already there, and does exactly what he asked for. I had a nagging suspicion, so dug into the CVS history then, and discovered that operator.truth() was added for Python 1.4 -- and the code was contributed by (tada!) Jim Fulton. He did the work in the last millennium, and simply forgot all about it then. So if anyone on c.l.py ever feels silly about asking for a feature that's already there, don't -- the people who *implement* features sometimes do the same thing. e.g.-i-still-wish-math.log(2L**100000)-didn't-blow-up-ly y'rs - tim From huaiyu at gauss.almadan.ibm.com Tue Mar 26 14:17:25 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 26 Mar 2002 19:17:25 +0000 (UTC) Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: On 25 Mar 2002 15:19:59 -0500, Aahz wrote: >In article , >Huaiyu Zhu wrote: >>On 24 Mar 2002 00:14:00 +0100, Martin v. Loewis wrote: >>>>>> To maintain www.python.org, we use a web page templating system called >>>>>> `ht2html', which transforms .ht template files into .html files. >>>> >>>> Is the source for this available? >>> >>>It's in the CVS. >> >>Is it very new? I've got a cvs copy a few weeks old, and it's not there. > > Try http://ht2html.sf.net Yes, it's there. Thanks. I was confused because someone mentioned that it's in the Tools directory. It's not in the python Tools directory. Then someone said it's in CVS... Huaiyu From gminick at hacker.pl Fri Mar 29 07:37:21 2002 From: gminick at hacker.pl (Wojtek Walczak) Date: Fri, 29 Mar 2002 12:37:21 +0000 (UTC) Subject: Random... References: <%slo8.20800$cB5.20607@atlpnn01.usenetserver.com> Message-ID: ** Since micro$oft is stupid it doesn't mean ** that you should be stupid too - do NOT toppost. Dnia Wed, 27 Mar 2002 10:22:10 -0500, Steve Holden napisa?(a): >While you correctly interpret netiquette, might it not have been more >considerate to this list if you had *mailed* the OP rather than giving >her/him a public dressing down which many others also had to read >unnecessarily? Or is it OK to waste *my* time by chastising the OP publicly? This note is automatically added to all my posts. It wasn't directed to the OP of that thread, it's directed to anybody who don't know about it. I haven't sent my post to attack OP's person, I answered his question (by giving an url to him). -- [ Wojtek gminick Walczak ][ http://hacker.pl/gminick/ ] [ gminick (at) hacker.pl ][ gminick (at) klub.chip.pl ] From quinn at riyal.ugcs.caltech.edu Sun Mar 3 13:34:21 2002 From: quinn at riyal.ugcs.caltech.edu (Quinn Dunkan) Date: 3 Mar 2002 18:34:21 GMT Subject: "pass by reference?" References: <1014509237.42236@cswreg.cos.agilent.com> Message-ID: On Sun, 24 Feb 2002 00:07:17 +0000 (UTC), Greg Weeks wrote: >Tripp Scott (tripps81 at yahoo.com) wrote: >: a = -1 >: make_abs(a) >: print a # = 1 > >It is good to see that I'm not the only person who still uses "pass by >reference" to mean that a function can rebind its argument variable. I think my preferred terminology nowadys is that python is exclusively pass by value. With a note that, in C, a value is an area of memory, and in python, lisp, etc., a value is a pointer to an area of memory. From jschmitt at ati.com Tue Mar 5 13:05:48 2002 From: jschmitt at ati.com (John Schmitt) Date: Tue, 5 Mar 2002 10:05:48 -0800 Subject: Deitel and Deitel Book... Message-ID: My favourite C++ book is probably the Anderson & Anderson book: http://www.amazon.com/exec/obidos/ASIN/0135327482/qid%3D1015351143/ref%3Dsr% 5F11%5F0%5F1/002-4476754-6161625 If I were teaching again, this book would be high on my list of textbooks. I'd love to get other people's opinion on it, since we're on the subject of C++ books. Caution: I might be biased because I met Paul Anderson and thoroughly enjoyed talking to him. John -----Original Message----- From: Dennis Roark [mailto:denro at NSPAMearthlink.net] Sent: Monday, March 04, 2002 2:43 PM To: python-list at python.org Subject: Re: Deitel and Deitel Book... First books in C++ are mostly a dissappointing lot, surprisingly so. [...] -------------- next part -------------- An HTML attachment was scrubbed... URL: From erno-news at erno.iki.fi Sun Mar 24 17:46:55 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 25 Mar 2002 00:46:55 +0200 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> Message-ID: In article <3c9e2692$0$24819$e4fe514c at dreader3.news.xs4all.nl>, Boudewijn Rempt writes: | That's the received opinion indeed. It still leads to problems. | I mean -- it's why you can kill a process, but not a thread. But in | an agent system, every agent (presumably running a thread, although | I've implemented systems where agents share threads, cooperative | multi-tasking agents) is on its own, and shouldn't own objects | or locks. maybe forking separate processes won't take much more memory than threads in that case, if they don't change memory pages inherited from the parent. -- erno From jimd at vega.starshine.org Sun Mar 31 23:07:16 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 1 Apr 2002 04:07:16 GMT Subject: Streaming XML-RPC? References: <3C9F51EE.5000203@jerf.org> <3C9FAF96.5DE9A0@bgb-consulting.com> Message-ID: In article , Magnus Lie Hetland wrote: >In article , Jim Dennis wrote: >>In article , Magnus Lie Hetland wrote: >>>In article , Skip >>>Montanaro wrote: >>>> Don> Are there any decent (finished/tested) Jabber libraries for Python? >>>>Don't know what its status is, but there is jabberpy: >>>> http://jabberpy.sourceforge.net/ >>> It's LGPL, which may make it unsuitable for some projects (like the >>> standard Python library). But it seems to support the basic protocol. >> Why would LGPL be allergic to the Python License? > I don't think it is, but AFAIK you couldn't include GPL or LGPL > software in the Python standard library, for instance. (But then > again, if that were an issue, the authors would probably donate the > code to the PSF anyway...) IANAL, but: I thought that PSF and Guido came up with a GPL compatible license. Since I'm not releasing any code that mixes GPL and Python code I haven't scrutinized the licenses in detail. So I don't know which versions of Python are covered by GPL compatible licenses, nor am I sure that the two licenses *are* actually compatible. However, it seems that the LGPL should be freely linkable even to proprietary or other non-GPL code. I was under the impression that this was the whole point of the *L*GPL. From bkelley at wi.mit.edu Fri Mar 29 10:21:45 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Fri, 29 Mar 2002 10:21:45 -0500 Subject: vwait in Python? References: <1017315455.8141.1.camel@lewis> Message-ID: <3CA48689.402@wi.mit.edu> Ken Guest wrote: > On Thu, 2002-03-28 at 11:37, Ken Guest wrote: > >>Anybody know if there's an equivalent to TCL's vwait keyword in Python? > > > So is there no way, short of a 2 line while statement, to have code > hang around until the value of some variable has been changed? You can always create a function to do this (see below) and create a one liner. > > I have tried using variations of the simple while statement, but they > only result in the application hanging (going into an infinite loop > no doubt). > > > k. > Here is an encapsulated vwait function. I can't say I recommend this as I far prefer the observer pattern described before, but here you go :) from Tkinter import * import time def vwait(root, var, timeout=0.1): """(master, var, timeout=0.1)->given a tk master and an observable variable i.e. var.get() returns a value wait for the variable to change. WARNING timeout defaults to subsecond precision, might not be available on all systems. WARNING vwait can only be called after the mainloop has been started. See test example below """ start = var.get() while 1: root.update() time.sleep(timeout) if var.get() != start: break if __name__ == "__main__": def go(): """function that is called after mainloop is started. uses vwait to wait for a variable change""" var = IntVar() top = Toplevel() button = Checkbutton(top, text="Click ME", var=var) button.pack() label = Label(top, text="Vwait Starting") label.pack() # wait for var to change vwait(top, var) # once var is changed alter the label label.configure(text="Vwait done") root = Tk() button = Button(root, text="Start", command=go) button.pack() mainloop() From aahz at panix.com Mon Mar 4 12:09:21 2002 From: aahz at panix.com (Aahz Maruch) Date: 4 Mar 2002 09:09:21 -0800 Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> Message-ID: [Frederic, please make sure to keep attributions, even for your own quotes. This makes it easier to hold discussion among multiple people.] In article <3C838150.97A86F52 at arakne.com>, Frederic Giacometti wrote: >Aahz Maruch wrote: >>Frederic: >>> >>>Just reverse the paradigm: have the python VM run in a single thread, >>>using stackless microthreads for python multithreading, and run the C >>>calls in a pool of threads. This way: no lock is needed, since only >>>one thread runs the VM, with the help of microthreads, and C calls run >>>in other threads. >> >> This doesn't make any sense unless you assume OS-level threads, and I >> thought part of the point of Stackless was to avoid requiring OS-level >> threads. > >More precisely, the point of stackless is to dispense from OS threads >(and Python lock) overheads for running threaded Python bytecode. >However, OS threads are still required to take charge of calls to >blocking C function (usually from external C libraries) that one want >to run asynchronously to the PVM; there is no turn around to this. Sure there is: just use Python's standard threading capabilities and release the Global Interpreter Lock, just like you do now. I will grant that it's not the most convenient thing in the world, and maybe we'll want to fix this in the future, but I think that getting Stackless done and squared away is more important than resolving this in the cleanest possible fasion. practicality-beats-purity-ly y'rs -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From Thilo.Ernst at dlr.de Mon Mar 4 12:40:25 2002 From: Thilo.Ernst at dlr.de (Thilo Ernst) Date: Mon, 04 Mar 2002 18:40:25 +0100 Subject: need to safely spawn subshells from multithreaded server - how? Message-ID: <3C83B189.999E2BA6@dlr.de> Hello c.l.py, I'm building something best described as a 'job dispatcher' . This program is intended as a long-running process which takes requests via an easy-to-talk-to remote object protocol such as XML-RPC or PYRO (the requests come from another Python interpreter process), and according to these requests starts, stops and otherwise supervises lots of child processes. The child processes will be Unix (platform for the whole thing is Linux/x86) command line applications to be started in subshells. As each child process will typically run a few seconds or even minutes, and there will be lots of concurrent requests which should not block each other, I want the dispatcher server to be multithreaded. This in principle is no problem - multithreading is supported by available Python implementations of the protocols above. Using one of these, the situation will be that the dispatcher server has a "main thread" listening for requests, and as soon as a request comes in it is handed over to a "handler thread" created for the purpose, freeing the main thread to listen for further requests. However after researching the web for similar problems/approaches I came to suspect I might be in for unpleasant surprises with the above design. Python multithreading combined with the spawning of child processes is said to be dangerous. All popen() variants, os.system(), and pty.spawn() rely on fork() which produces a full-blown clone of my server process. As long as I cannot make 100% sure that only the intended thread - the "handler thread" for the current request- continues to run in the child process, it seems that I might end up with two competing server threads (one in parent, one in child). Now my questions. Execuitve summary: "can it be done, and how?" 1. Did I get something utterly wrong here? Is the danger of getting two interfering server threads a real one at all? This isn't the type of question a quick prototype reliably answers. Interestingly, from Zope (which is a multithreaded server, too), I've been fork()ing subshells happily and ignorantly for years already with no apparent problems, and so will other people have done. But I'd rather be on the safe side. I don't want inexplicable failures due to rare race conditions or something similar later on. 2. Can I enforce (from Python) that only the handler thread continues to run in the child process? My current idea is to somehow block the server main thread right before the fork(), and unblock it immediately afterwards - but only in the parent process. Would that be safe? And could I perhaps reach that goal without having to substantially change the implementation of my chosen remote object system? 3. Any other ideas? Is there any other, fork()-less way to spawn a subshell (from Python, on Linux)? The following Tim Peters quote (from ) doesn't sound too encouraging... > The Python C API defines a PyOS_AfterFork() function, which platforms can > fill with whatever crud they need to do after a fork. On all platforms to > date, it calls (in both parent and child) PyEval_ReInitThreads(), and resets > the Python signal module's notion of what the current pid is. However, > mixing threads with fork is a frigging mess on the best of platforms, and it > generally takes a bona fide platform expert to guess what happens in the end Any hints much appreciated. Best regards, Thilo Ernst From jeff at ccvcorp.com Thu Mar 21 19:34:52 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 21 Mar 2002 16:34:52 -0800 Subject: Popular style document? References: <1016641355.370859@cswreg.cos.agilent.com> Message-ID: <3C9A7C2C.E93DA440@ccvcorp.com> phil hunt wrote: > On Wed, 20 Mar 2002 13:52:35 +0000 (UTC), Greg Weeks wrote: > > > >1. I use "me" instead of "self" in method definitions. > > I think it's a good idea, if a bit unconventional. In what way is "me" preferable to "self", other than being two characters shorter? And is saving those two characters really such a big deal? > IMO the requirement to say self everywhere in methods is the worst > feature of python. What "requirement"? It's explicitly allowed to call the first parameter of a method whatever you like -- self, me, JimBob, MyNiftyVariablePointingToTheObjectThisMethodIsBeingCalledOn... it's just convention to call it self, because when you're talking about code with someone else, everyone knows what you mean when you say self. If you're referring to the need to refer to instance attributes as 'self.foo' instead of just 'foo' -- Ugh. The misfeature of allowing implicit attribute references is one of the most confusing things about C++. There's a reason that most C++ member variables started taking on 'm_' prefixes -- because otherwise you can't tell what's a member and what isn't, and it becomes impossible to keep track of whether a given code segment calculates a temporary value or changes the object's state in a more permanent fashion. When I was trying to grok MFC, long ago, every time I looked at example code I had to spend hours flipping around in the class reference, trying to guess *where* a given variable or method came from... Explicit is better than implicit, and this particular example is one of the clearest proofs of *why* that is so. Jeff Shannon Technician/Programmer Credit International From amckay at merlinsoftech.com Wed Mar 13 14:30:24 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Wed, 13 Mar 2002 11:30:24 -0800 Subject: Why Don't Scripts Run ? In-Reply-To: <3C8F9C59.F9408D47@mcn.net> References: <3C8F9C59.F9408D47@mcn.net> Message-ID: <200203131929.g2DJTiq25090@mail.merlinsoftech.com> On March 13, 2002 10:37 am, jrc wrote: > 'python script.py' > > completely fails (syntax error). Please post your error and script (if its short). If you are getting a syntax error, it would seem Pyhon is running and then failing on your script and hence generating a syntax error. Thats not Python's fault. -- Andy McKay From bosahv at netscapenospam.net Thu Mar 28 02:09:51 2002 From: bosahv at netscapenospam.net (Bo Vandenberg) Date: Thu, 28 Mar 2002 07:09:51 GMT Subject: Zope Install probs on Mandrake 8.2 References: Message-ID: <3lzo8.173$m12.137@news02.bloor.is.net.cable.rogers.com> Can I install the python 2.2rc2 source right over the Mandrake 2.2? "Petri Savolainen >" < wrote in message news:pan.2002.03.28.08.11.15.814275.2239 at nospam.yahoo.com... > Do you have Python development package / libraries installed? > > You need them to build Zope from source. > > On Thu, 28 Mar 2002 07:16:38 +0200, Bo Vandenberg wrote: > > > I'm trying to install Zope from source on a fresh install of Mandrake > > 8.2. I'd appreciate it if anyone here has advice for this. > > > > > > "python wo_pcgi.py" fails building the extension modules saying "cannot > > stat `/usr/lib/python2.2/config/Makefile.pre.in': No such file or > > directory. > > > > This is indead true. > > > > Is there something a beginner should do at this point? > > > > Zope claims to run on python 2.1 will it run on 2.2??? > > > > Thanks in advance. From jason at jorendorff.com Sat Mar 9 21:35:06 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sat, 9 Mar 2002 20:35:06 -0600 Subject: should i learn it first ? In-Reply-To: Message-ID: Qiang.JL wrote: > Do you guys not agree to master C/C++, a large amount of time will be > required (somewhere on the net i saw it's appro 3-4 years. whew!!) > In one i want to learn it but on the other this time consuming > issue scare me .as the bad tradeoff -- it's smarter to use a language > that uses the machine's time less efficiently, but your time much > more efficiently. > > am i whining? , :-) Yeah. :) Go get an account on a Linux box, buy "The C Programming Language" by Kernighan and Ritchie, and get to work. You can work your way through it in a month or two. It's more than worth your time. If nothing else, you'll be more able to read all the excellent existing books about programming that include examples in C. Also, sometime next week, read this: http://www.python.org/doc/current/tut/ You can work your way through it in an evening. It might be worth your time, too. ## Jason Orendorff http://www.jorendorff.com/ From philh at comuno.freeserve.co.uk Sun Mar 10 20:08:32 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 11 Mar 2002 01:08:32 +0000 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: On Sun, 10 Mar 2002 19:21:08 -0500, Christopher Browne wrote: >In an attempt to throw the authorities off his trail, philh at comuno.freeserve.co.uk (phil hunt) transmitted: >> On 10 Mar 2002 10:15:06 -0800, Aahz Maruch wrote: >>>In article , >>>phil hunt wrote: >>>>On Sat, 09 Mar 2002 22:57:42 -0500, Peter Hansen wrote: >>>>> >>>>>I agree with much of what you say, especially the "consider skipping >>>>>C++ and just learn C part", but _what_ pragmatic point of view is it >>>>>that has one learning Perl, Java, or C++ when one uses Python already? >>>>>Not dissing those languages, but when would you really need them? >>>> >>>>I can think of several tasks for which C++ is better than Python, >>>>e.g. writing operating systems, network stacks, windowing systems, >>>>run-time interpreters, crypto algorithms, etc. >>> >>>But are there any tasks for which C++ (or C++/Python) is really better >>>than C/Python? >> >> Any task for whiich OO is useful, which means essentially all >> programs >5000 lines (and most smaller ones), will benefit from C++ >> over C. > >Would that include the implementation of runtime code for an >at-the-bare-iron OS kernel to support: > a) vtables, and > b) memory management? > >Remember, when you're sitting at that level, you have no runtime >support code, and so can make no use of: > - Virtual functions > - Constructors > - Destructors > >I would tend to think that figuring out the usable subset of C++ would >become painful enough to discourage its use. Good point. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From wurmy at earthlink.net Wed Mar 27 00:16:50 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Wed, 27 Mar 2002 05:16:50 GMT Subject: python, cvs, win32 -- slightly ot References: Message-ID: <3CA15642.7FA3E117@earthlink.net> dsavitsk wrote: > > i have registered and had approved a project on sourceforge. never having > used cvs before, i am looking for some help on how to use cvs with python > files on win2k. any links on where to look? > > project-to-be-anounced-as-as-soon-as-possible ly 'yrs I use WinCVS: http://www.wincvs.org/ Then there's this page with lots of info on CVS: http://www.cvshome.org/ You might need Cygwin for ssh (although there are other ssh alternatives out there): http://www.cygwin.com/ HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From martin at v.loewis.de Sun Mar 31 05:25:13 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 12:25:13 +0200 Subject: PEP 285: Adding a bool type References: Message-ID: philh at comuno.freeserve.co.uk (phil hunt) writes: > On Sat, 30 Mar 2002 08:38:00 -0500, Guido van Rossum wrote: > >Tim must be missing something. The obvious way to turn a bool b into > >an int is int(b). > > Will this work on old versions of python? I've just checked that it > works on 2.0, but what about 1.5.1 or 1.6? > > I'd guess (b*1) would work on everything, however. The way Guido meant this is really "turn a *bool* into an int". There are no bools in 2.0, so I wonder what you've checked. If you want to change an arbitrary object into 0/1, int() certainly won't work: >>> int([]) Traceback (most recent call last): File "", line 1, in ? TypeError: object can't be converted to int To turn an arbitrary object into a bool, you could have used operator.truth so far, since Python 1.4. To turn that into 0/1 pair, you could write int(operator.truth(obj)). This will also work back to Python 1.4, since truth already returns 0/1; passing that to int() was always allowed. Regards, Martin From shredwheat at attbi.com Fri Mar 29 12:37:23 2002 From: shredwheat at attbi.com (Pete Shinners) Date: Fri, 29 Mar 2002 17:37:23 GMT Subject: python2.2 LESS docstring'able Message-ID: <3CA43762.9010705@attbi.com> I've got an extension object and a function to create the object. MyObj() # create new MyObj MyObjType # the type for MyObj in pre-2.2 i can have a docstring for each of these. my question is now that i'm "combining" the type and the little constructor, what is the best way to merge the docstrings? i'd like my object to still have the docstring for that type. but i'd really like to be able to see the calling syntax for the constructor in docstrings as well? so that's my little confusion. not the end of the world. i've just got 2 nice docstrings here, and only a slot for one of them. does the PythonType structure need another slot? tp_new_doc? a docstring for the Type, and a docstring for instanced objects? hmm, well that still might not solve everything. what's a humble extension writer to do? i suppose i could use a little #if magic and combine the docstrings when python 2.2 is being used. is that the only real solution? From chris.gonnerman at newcenturycomputers.net Wed Mar 27 22:06:54 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Wed, 27 Mar 2002 21:06:54 -0600 Subject: IDiscMaster interface Message-ID: <009901c1d605$b8fc2f40$0101010a@local> I have been investigating the IDiscMaster interface implemented in Windows XP. It appears to be a COM interface (I'm a Linux/Unix type of guy and know very little about Windows internals), but I can find no type library. Has anyone else used this interface (component, whatever) via Python? I'd really like to be able to burn CD's automatically for backup purposes. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From ffjhenon at club-internet.fr Tue Mar 26 11:40:48 2002 From: ffjhenon at club-internet.fr (Fabien =?iso-8859-1?Q?H=E9non?=) Date: Tue, 26 Mar 2002 17:40:48 +0100 Subject: Tkinter -> spawn external cmd -> return stdout and stderr to back Tkinter Message-ID: <3CA0A490.4C88C20C@club-internet.fr> I need some help for firing up an external program from Tkinter. I am writing an editor for POV-RAY linux under using Tkinter. The pov-ray scripts are edited in that editor and can be raytraced from within. When POV raytraces, it outputs the image being raytraced and the line number being raytraced. When the raytrace is over, it outputs to the console the stats( how long the process was, number of objects,...), or the error if there is an error in the script I use 'spawnv' to fire up POV to start it as a new process. Which command should I use to get interactive stdout and stderr back to my Tkinter application.(do you have any running examples of popen ? the doc is not clear) I also would like to be able to stop the raytrace when it is started. I heard about subproc. I can't get to find it in ftp.python.org Thanks for any help Here is the code - still a bit messy the problem is at line 340 8<------------------ cut here --------------------->8 #! /usr/bin/env python import sys, os, string from string import split from os import spawnv, P_NOWAIT from Tkinter import * from tkFileDialog import askopenfilename, asksaveasfilename # ajouter undo # ajouter buffers pour multifen?tres # ajouter close dans menu # ajouter les 'insert' pov avec cascades # ajouter chemin pour executable class mainWin: def __init__(self,tkRoot): self.tkRoot=tkRoot self.createWidgets() return None global params global filename plat=sys.platform class App: ## ---------------------- Create GUI ---------------------- def __init__(self, master): ## ---------------------- Mainframe ---------------------- mframe = Frame(master) mframe.pack(expand=1, fill=BOTH) frame_input=Frame(mframe) ## ---------------------- Menu ---------------------- menubar=Menu(frame_input) filemenu=Menu(menubar,tearoff=0) filemenu.add_command(label="New",command=self.clr) filemenu.add_command(label="Open",command=self.enter_text) filemenu.add_command(label="Close") filemenu.add_command(label="Save",command=self.save) filemenu.add_command(label="Save As",command=self.saveas) filemenu.add_separator() filemenu.add_command(label="Quit",command=sys.exit) menubar.add_cascade(label="File",menu=filemenu) editmenu=Menu(menubar,tearoff=0) editmenu.add_command(label="Cut") editmenu.add_command(label="Copy") editmenu.add_command(label="Paste") menubar.add_cascade(label="Edit",menu=editmenu) rendermenu=Menu(menubar,tearoff=0) rendermenu.add_command(label="Render", command=self.render) rendermenu.add_command(label="Options", command=self.render) menubar.add_cascade(label="Render",menu=rendermenu) insertmenu=Menu(menubar,tearoff=0) insertmenu.add_command(label="Animation", command=self.render) # CSG insertmenucsg=Menu(insertmenu,tearoff=0) insertmenucsg.add_cascade(label="difference", command=self.render) insertmenucsg.add_cascade(label="intersection", command=self.render) insertmenucsg.add_cascade(label="inverse", command=self.render) insertmenucsg.add_cascade(label="merge", command=self.render) insertmenucsg.add_cascade(label="union", command=self.render) insertmenu.add_cascade(label="CSG Operations", menu=insertmenucsg) insertmenu.add_command(label="Expressions", command=self.render) insertmenu.add_command(label="Headers", command=self.render) insertmenu.add_command(label="Light sources", command=self.render) insertmenu.add_command(label="Misc directives", command=self.render) insertmenu.add_command(label="Ready made scenes", command=self.render) insertmenu.add_command(label="Shape modifiers", command=self.render) # SHAPES insertmenushape=Menu(insertmenu,tearoff=0) insertmenushape.add_cascade(label="bicubic_patch",command=self.render) insertmenushape.add_cascade(label="blob",command=self.render) insertmenushape.add_cascade(label="box",command=self.render) insertmenushape.add_cascade(label="cone",command=self.render) insertmenushape.add_cascade(label="cubic",command=self.render) insertmenushape.add_cascade(label="cylinder",command=self.render) insertmenushape.add_cascade(label="disc",command=self.render) insertmenushape.add_cascade(label="fractal",command=self.render) insertmenushape.add_cascade(label="height_field",command=self.render) insertmenushape.add_cascade(label="lathe",command=self.render) insertmenushape.add_cascade(label="mesh",command=self.render) insertmenushape.add_cascade(label="plane",command=self.render) insertmenushape.add_cascade(label="polygon",command=self.render) insertmenushape.add_cascade(label="polynomial",command=self.render) insertmenushape.add_cascade(label="prims",command=self.render) insertmenushape.add_cascade(label="quadric",command=self.render) insertmenushape.add_cascade(label="smooth_triangle",command=self.render) insertmenushape.add_cascade(label="sphere",command=self.render) insertmenushape.add_cascade(label="superellipsoid",command=self.render) insertmenushape.add_cascade(label="sor",command=self.render) insertmenushape.add_cascade(label="text",command=self.render) insertmenushape.add_cascade(label="torus",command=self.render) insertmenushape.add_cascade(label="triangle",command=self.render) insertmenu.add_cascade(label="Shapes", menu=insertmenushape) insertmenu.add_command(label="Statements", command=self.render) insertmenu.add_command(label="Standard colors", command=self.render) insertmenupattern=Menu(insertmenu,tearoff=0) insertmenupattern.add_cascade(label="agate", command=self.render) insertmenupattern.add_cascade(label="average", command=self.render) insertmenupattern.add_cascade(label="boxed", command=self.render) insertmenupattern.add_cascade(label="bozo", command=self.render) insertmenupattern.add_cascade(label="brick", command=self.render) insertmenupattern.add_cascade(label="bumps", command=self.render) insertmenupattern.add_cascade(label="checker", command=self.render) insertmenupattern.add_cascade(label="crakcle", command=self.render) insertmenupattern.add_cascade(label="cylindrical", command=self.render) insertmenupattern.add_cascade(label="density_file", command=self.render) insertmenupattern.add_cascade(label="dents", command=self.render) insertmenupattern.add_cascade(label="gradient", command=self.render) insertmenupattern.add_cascade(label="granite", command=self.render) insertmenupattern.add_cascade(label="hexagon", command=self.render) insertmenupattern.add_cascade(label="leopard", command=self.render) insertmenupattern.add_cascade(label="mandel", command=self.render) insertmenupattern.add_cascade(label="marble", command=self.render) insertmenupattern.add_cascade(label="onion", command=self.render) insertmenupattern.add_cascade(label="planar", command=self.render) insertmenupattern.add_cascade(label="quilted", command=self.render) insertmenupattern.add_cascade(label="radial", command=self.render) insertmenupattern.add_cascade(label="ripples", command=self.render) insertmenupattern.add_cascade(label="spherical", command=self.render) insertmenupattern.add_cascade(label="spiral1", command=self.render) insertmenupattern.add_cascade(label="spiral2", command=self.render) insertmenupattern.add_cascade(label="spotted", command=self.render) insertmenupattern.add_cascade(label="waves", command=self.render) insertmenupattern.add_cascade(label="wood", command=self.render) insertmenupattern.add_cascade(label="wrinkles", command=self.render) insertmenu.add_cascade(label="Patterns",menu=insertmenupattern) insertmenufinish=Menu(insertmenu,tearoff=0) insertmenufinish.add_cascade(label="ambient", command=self.render) insertmenufinish.add_cascade(label="attenuation", command=self.render) insertmenufinish.add_cascade(label="brilliance", command=self.render) insertmenufinish.add_cascade(label="caustics", command=self.render) insertmenufinish.add_cascade(label="crand", command=self.render) insertmenufinish.add_cascade(label="diffuse", command=self.render) insertmenufinish.add_cascade(label="ior", command=self.render) insertmenufinish.add_cascade(label="irid", command=self.render) insertmenufinish.add_cascade(label="metallic", command=self.render) insertmenufinish.add_cascade(label="phong", command=self.render) insertmenufinish.add_cascade(label="phong_size", command=self.render) insertmenufinish.add_cascade(label="reflection", command=self.render) insertmenufinish.add_cascade(label="roughess", command=self.render) insertmenufinish.add_cascade(label="specular", command=self.render) insertmenu.add_cascade(label="Finish",menu=insertmenufinish) menubar.add_cascade(label="Insert",menu=insertmenu) root.config(menu=menubar) ## ---------------------- Buttons ---------------------- frame_buttons=Frame(mframe) self.button_open = Button(frame_buttons, text="Open..", fg="blue", command=self.enter_text) # self.button_open = Button(frame_buttons, image="open.xpm", command=self.enter_text) self.button_open.pack(side=LEFT) self.button_render = Button(frame_buttons, text="Render..", fg="red", command=self.render) self.button_render.pack(side=LEFT) frame_buttons.pack(expand=0, fill=BOTH) ## ---------------------- Editor ---------------------- self.text = Text(frame_input) self.yscroll_i = Scrollbar(frame_input,orient=VERTICAL, command=self.text.yview) self.yscroll_i.pack(side=RIGHT, fill=Y) self.text['yscrollcommand']=self.yscroll_i.set self.text.pack(side=LEFT,expand=1, fill=BOTH) self.yscroll_i.pack(side=RIGHT, fill=Y) frame_input.pack(expand=1, fill=BOTH) bind_class=self.text.bind_class bind_class('UPD','',self.keyPress) bind_class('UPD','',self.keyPress) bind_class('UPD','',self.keyPress) bind_class('UPD','',self.keyPress) oldtags = self.text.bindtags() self.text.bindtags(oldtags+('UPD',)) ## ---------------------- Output ---------------------- frame_output=Frame(mframe) self.text_out = Text(frame_output,state=NORMAL,height=6) self.text_out.pack(side=LEFT,expand=1, fill=BOTH) self.scroll = Scrollbar(frame_output, command=self.text_out.yview) self.text_out.configure(yscrollcommand=self.scroll.set) self.scroll.pack(side=RIGHT, fill=Y) frame_output.pack(expand=0, fill=BOTH) ## ---------------------- Status Bar ---------------------- frame_status_bar=Frame(mframe) self.parameters = Label(frame_status_bar,text="Parameters : ", anchor="w",bg='gray70') self.parameters.pack(side='left') self.fill_params=Entry(frame_status_bar,bg='gray100') self.fill_params.insert(INSERT,"+w320 +h240 -f +dgt +p") self.fill_params.pack(side='left', expand=1, fill=BOTH) self.status_filename1 = Label(frame_status_bar,text="File : ",width=5, anchor="w",bg='gray70') self.status_filename1.pack(side=LEFT ) self.status_filename2 = Label(frame_status_bar,text="",width=20,relief=SUNKEN, anchor="w", bg="gray90") self.status_filename2.pack(side=LEFT) self.status_line = Label(frame_status_bar,padx=1, relief=SUNKEN,bg="gray90", width=10, anchor="w", # textvariable=affi_Ligne text="1" ) self.status_line.pack(side='right') self.status_linetext = Label(frame_status_bar,padx=1,bg='gray70', width=7, anchor="w", text="Line : ") self.status_linetext.pack(side='right') frame_status_bar.pack(side=LEFT,expand=1, fill='x') ## ---------------------- Open file ---------------------- def enter_text(self): filetypes = ( ( "Pov files","*.pov"), ( "Include files","*.inc"), ( "All","*")) self.filename = askopenfilename(filetypes=filetypes) if self.filename: self.text.delete(1.0, END) fd = open(self.filename) for line in fd.readlines(): if line.endswith("\r\n"): line = line[:-2] + "\n" self.text.insert(END, line) fd.close() self.status_filename2.config(text=os.path.split(self.filename)[1]) root.title("POV-RAY editor | "+self.filename+" |") buf=self.text.get('1.0','end') # print buf ## ---------------------- Clear ---------------------- def clr(self): self.text.delete(1.0, END) self.status_filename2.config(text="") root.title("POV-RAY editor") ## ---------------------- Save ---------------------- def save(self, forPrt=None): try: script = self.text.get(1.0, END) if script: fd = open(self.filename, 'w') for line in string.split(script, '\n'): fd.write(line) fd.write('\n') fd.close except: self.saveas() ## ---------------------- Saveas ---------------------- def saveas(self, forPrt=None): script = self.text.get(1.0, END) if script: # global filename # self.filename=".pov" filetypes = ( ( "Pov files","*.pov"), ( "Include files","*.inc"), ( "All","*")) self.filename = file = asksaveasfilename(filetypes=filetypes) fd = open(self.filename, 'w') for line in string.split(script, '\n'): fd.write(line) fd.write('\n') fd.close self.status_filename2.config(text=os.path.split(self.filename)[1]) root.title("POV-RAY editor | "+self.filename+" |") ## ---------------------- Render button ---------------------- def render(self): global params params=self.fill_params.get() script = self.text.get(1.0, END) if script: fd = open(self.filename, 'w') for line in string.split(script, '\n'): fd.write(line) fd.write('\n') fd.close if plat=="linux-i386": app = '/usr/bin/x-povray' # a remettre spawnv(P_NOWAIT, app , ('x-povray', "+i"+self.filename+" "+params)) # a remettre if plat=="win32": app = 'c:\\image\\3d\\pov31\\bin\\pvengine' # a remettre spawnv(P_NOWAIT, app , ('pvengine.exe', "+i"+self.filename+" "+params)) # a remettre # appli = split(app)[1] # os.spawnl(os.P_NOWAIT, app , params) # os.popen3(app +' '+params) # os.system("dir" +params+" > foo.txt 2>foo.error.txt") # os.system("dir *.py" >"foo.txt") # os.popen3(app +"+i"+self.filename+" "+params) # a remettre ## ---------------------- Render keyboard ---------------------- def render_kb(self,event): global params params=self.fill_params.get() app = r"C:\perso\bureautique\Microsoft Office\Office\excel.exe" appli = split(app)[1] # os.spawnl(os.P_NOWAIT, app , params) # os.system(app +' '+params) # os.system(app) spawnv(P_NOWAIT, app, (appli, params)) ## ---------------------- Top-Level Command line button ---------------------- def parameters_button(self): self.tl=Toplevel() self.lb=Label(self.tl, text="Render parameters:") self.cl=Entry(self.tl,width=40) self.ok=Button(self.tl, text="OK", fg="red", command=self.get_parameters) self.ok.pack(side=BOTTOM) self.cl.pack(side=RIGHT) self.lb.pack() #self.stdout = sys.stdout ## ---------------------- Prints the current line number and contents ---------------------- # line, col = string.split( self.iText.text.index( 'insert'), '.') # self.linecolLabel.config( text="Line %s Col %s" % (line,col)) # self.status_line def lin(self): Ligne, column = string.split( self.text.index(INSERT),'.') self.status_line.config(text="%s" % (Ligne)) ## ---------------------- Called when a key is pressed ---------------------- def keyPress(self,event): self.lin() root = Tk() affi_Ligne=StringVar() #params=StringVar() larg = root.winfo_screenwidth() haut = root.winfo_screenheight() app = App(root) #root.geometry("%dx%d+0+0" % (larg,haut)) root.title("POV-RAY editor") root.mainloop() 8<------------------ cut here --------------------->8 From bergeston at yahoo.fr Wed Mar 13 03:44:16 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Wed, 13 Mar 2002 09:44:16 +0100 Subject: how to give an object as argument for a method References: <3C8E49ED.1C524CC1@ccvcorp.com> Message-ID: I fully agree with Jeff : IMHO, it can only be a 'last chance' solution in various situations (debug, plug-in development, test module...) but I advice to never design an application from scratch on such an assumption or even rely on that for business development. B. "Jeff Shannon" wrote in message news:3C8E49ED.1C524CC1 at ccvcorp.com... > > > Marco Herrn wrote: > > > [snip] > > > ... def sayNo(self): > > > ... caller = sys._getframe(1).f_locals['self'] > > this is the only line, that looks a bit ugly. It actually does the same > > as when giving caller as parameter. So what can be a reason to implement > > it this way? It looks much less readable to me. And I have to say I not > > even understand it fully.... > > Actually, it does *not* do the same as giving the caller as a parameter, in > general. What this does, is that it gets the intepreter's stack frame in which > the current object was created. In this case, that happens to be the > Egg.__init__() frame. It then searches this stack frame for a local name > 'self'; if that name doesn't exist, this will throw an exception. This means > that Spam can *only* be created from inside of another method which uses the self > convention; you cannot create a Spam object globally or inside of a top level > function. And, indeed, in the rare instances where a method uses some name other > than self to represent its bound instance, this will fail as well. A metaphor > would be that, instead of simply being told who your parents are, you're > searching through a phone book for a name that you *think* belongs to them -- but > you might have the name wrong, they might have an unlisted number, or they might > not even *be* in that phone book. (Note also that even if it *does* work, it's > inappropriate to call the object found the "owner" or "caller" of the current > instance; it would be the *creator*, which is not necessarily the same thing at > all, especially when you consider object factories and such.) > > In short, this is black magic. It might work, most of the time... but if you > turn your back on it, it's liable to blow up on you. Use only with caution, and > only when you're *sure* that you know what you're asking for. :) > > Jeff Shannon > Technician/Programmer > Credit International > > From eppstein at ics.uci.edu Fri Mar 15 21:35:04 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 15 Mar 2002 18:35:04 -0800 Subject: Shot in the Dark: Minimum-weight perfect matching algorithm References: Message-ID: In article , Paul Magwene wrote: > Does anybody happen to have a Python implementation of a minimum-weight > perfect matching algorithm? Or a Python interface to one? > > I'm aware of (some) of the literature on this topic, but as a non-computer > scientist I'd rather not have to twist my mind around one of the Blossum > algorithms. I take it you need nonbipartite perfect matching? Bipartite is much easier. (I don't have Python even for that, but I do have some simple C code...) -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From jimd at vega.starshine.org Tue Mar 26 18:22:57 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 26 Mar 2002 23:22:57 GMT Subject: list element of a class with the for statement References: Message-ID: In article , cedric_briner wrote: > hi, > I'm interesting to know which method of a class I have to define to > list the __records of this class: > class CRdb: > __fieldsName= [] > __keyname= [] > __records = ['first','secnd','third'] > __iRecord= 0 > because I would like to write something like: > db=CRdb() > for entry in db: > print entry > and then get > first > secnd > third > please let me know any pointer refering this topic...or even better a > quick solution .. Topics: read "What's new in Python 2.2" by A.M. Kuchling at: http://www.amk.ca/python/2.2/index.html and pay particular attention to the discussion of "iterators." in section 3 (amusingly referred to by a URL referencing section 00040*; probably an artifact of the editing process and the use of LaTeX2HTML): http://www.amk.ca/python/2.2/index.html#SECTION000400000000000000000 Meanwhile I wrote a long answer before I actually understood what you were asking. The "quick solution" is all the way at the bottom. I was lead astray by the fact that your CRdb class here shows only some class members with no methods and no instance members (which would normally be initialized by an object's __init__() method. So I rambled on at great length about using class methods and properties to manage your class members (and a little bit about the effect of using __ prefixes on those member names, in any event). > thanks. Briner You've created a class with a set of "class members" (as opposed to "instance members"). By using the __ precedents in these names you asked Python to "mangle" them for you as shown in this transcript from an interactive Python session: >>> class CRdb: ... __fieldsName = [] ... __keyname = [] ... __records = [ 1, 2, 3, 4 ] ... __Irecord = 0 ... >>> CRdb.__dict__ {'_CRdb__records': [1, 2, 3, 4], '__module__': '__main__', '_CRdb__Irecord': 0, '_CRdb__fieldsName': [], '__doc__': None, '_CRdb__keyname': []} >>> >>> class CRdb: ... __fields = [] ... __keyname = [] ... __records = [ 1, 2, 3, 4 ] ... Rdb) ['_CRdb__Irecord', '_CRdb__fieldsName', '_CRdb__keyname', '_CRdb__records', '__doc__', '__module__'] >>> dir(CRdb) ['_CRdb__Irecord', '_CRdb__fieldsName', '_CRdb__keyname', '_CRdb__records', '__doc__', '__module__'] >>> This mangling is primarily of interest in cases where you might subclass CRdb (since the _CRdb__* members will retain their mangled names in >>> class subCRdb(CRdb): ... pass ... >>> dir(subCRdb) ['_CRdb__Irecord', '_CRdb__fieldsName', '_CRdb__keyname', '_CRdb__records', '__doc__', '__module__'] >>> So, to access these members from outside the class you could simply use: CRdb._CRdb__FieldsName ... or any of the other name that you used in your class. However, that's considered poor OOP since it violates the intention of encapsulating access to the members through class/instance methods. Under Python 2.1 (?) and ealier it was not possible to create class methods. All functions had to be *instance* methods (they *had* to be presented with a "self" argument as their first parameter). If you added the following to your class definition: class CRdb: # ... (your extant members) def setFields(self,fields) self.__fieldsName = fields def getFields(self) return self.__fieldsName ... then you'd be adding "get" and "set" methods to your class, which could be used through any instance. So to call these you'd need to instantiate from CRdb like so: inst = CRdb() inst.getFields() inst.setFields(['one','two','three']) ... and so on. In Python 2.2 (?) some features have been added that could be used to create class methods (so that you could rewrite the getFields method such that it didn't require a "self" argument, and you could call CRdb.getFields() directly, without instantiating and going through one of the instances. Here's an example: >>> class tst(object): ... __foo = 0 ... def setfoo(cls,val): ... cls.__foo = val ... setfoo = classmethod(setfoo) ... >>> tst._tst__foo 0 >>> tst.setfoo(1000) >>> tst._tst__foo 1000 >>> ... notice that, in order to bind classmethods (or staticmethods, not shown here) into my class, I have to subclass one of the Python 2.2 "new style" classes; such as the archetypical "object." A class method takes a class reference as its first argument (which is analogous to the "self" reference we'd expect in instance methods). The tricky part is how we have to rebind our class method by sort of passing it through a "classmethod()" factory. I don't fully understand what this does, but it allowed Guido et al to make this change without any fundamental syntactic change to the core language. We don't need a new keyword and/or changes to the parser since it was never a syntax error to define methods in classes with no references to "self." (Any attempt to use such a method in a "classical (old style) class" was doomed, since the arguments would be all wrong, but that was a runtime issue, not a parsing or syntactical problem per se). So where have we come: You can access the members of your class directly by applying our a priori knowledge of how the names are mangled. This would be considered "bad practice (TM)" by OOP purists (and in fact it's tacky enough that I have to cry foul even though I'm a bit of an anti-OOP neanderthal). You can create methods to set and get these members through instances (but you need to instantiate and go through them). That seems inelegant, since if "feels" like you're going though the back door to get to the class members. But it's the only way for earlier versions of Python (other than the "even-more-uglier-ly" technique of reaching in from outside the class entirely). You can subclass "object" and use class methods (under 2.2 or later). But that's not all. You might also be able to use another classy new Python 2.2 feature called "properties" to manage access to your class (or instance) members. Here's an example of that: >>> class tst(object): ... def getfoo(cls): ... return cls.__foo ... getfoo = classmethod(getfoo) ... def setfoo(cls,val): ... cls.__foo = val ... setfoo = classmethod(setfoo) ... __foo = property(getfoo, setfoo, None, "tst class' foo member") ... >>> tst._tst__foo >>> tst.getfoo() >>> tst.setfoo("tst") >>> tst.getfoo() 'tst' >>> The important points above are: I define a pair of functions (using the convention "get" and "set" names) to manipulate __foo. I then make them classmethods. Now I use the property "factory" to create my member *and* to bind it to a set of "accessors" (get, set, and del functions). In this example I'm binding the property "__foo" to the accessors "getfoo" and "setfoo" (following the common naming conventions), and I've omitted binding it to a delete function. (I have also associated __foo with a doc string, as shown). In my example I see that tst._tst__foo is initially bound to a "property object." I see that accessing it via the getfoo() class method returns a reference to exactly the same object. In practice I might want to set an initial value to such a member (in my class definition) since I don't know what happens if other code encounters this "property object" (by access tst.getfoo() before any tst.setfoo() calls). Oddly enough I found that I couldn't just add: tst.setfoo(0) to my class definition (I still get the property references from an initial "tst.getfoo()" call). However, adding a line like: __foo = 0 (or whatever) after the call to __foo = property(...) does seem to work. __foo then contains a value *and* it retains its special "properties" of being accessible via the get and set methods that I bound to it. So, that answers a question which is implicit to yours: how can you the the class members at all? Now on to your real question: how can you define an iterator for instances of your class, and bind that iterator to a specific member sequence? At this point I have to assume that your pasted code is completely bogus. It would make no sense to create __records as a *class* member. I must assume that you really want it to be an *instance* member (which would presumably be instantiated or bound through your __init__() method). (Silly me! I spend all of that time explaining how to work with "private" (__mangled) *class* members before understanding your question). "Iterators" are another new Python 2.2 feature. Here's a trivial example (similar to the one you'd want in your code): class tstIter: # Notice, works with "classical" classes # and with "classy" new classes __foo = [1,2,3,4,5,6,7] def __iter__(self): return iter(self.__foo) Now it is possible to say: stoopid_example = tstIter() for each in stoopidexample: print each ... which seems straightforward enough. However, it probably make no sense in reality. You probably need for __records to be an *instance* variable (member). That would look a little more like: class CRdb: __fieldsName= [] __keyname= [] __iRecord= 0 def __init__(self, recs=None): if recs: self.__records = recs else: self.__records = [] def __iter__(self): return iter(self.__records) That (minimally) would allow your sample code to run as you *probably* intended it. Of course you might want to combine this with a set of accessor functions to ensure that self.__records is always some sort of sequence. You could write get* and set* functions and bind them to self.__records with a call to property() I'll leave all of that as an exercise. From bt98 at doc.ic.ac.uk Mon Mar 4 06:21:36 2002 From: bt98 at doc.ic.ac.uk (Benjamin Tai) Date: Mon, 04 Mar 2002 11:21:36 +0000 Subject: what is happening at __init__ Message-ID: <3C8358C0.81D97AD8@doc.ic.ac.uk> Hi, I was simply curious, finding out what is happening at the class constructor. The followings are the questions/answers that I come up with, in related with my program attached: Q 1) "self" is already assigned to the instance of the class at the point entering the constructor. Q 2) Although "self" is assigned to a new value within the function, it is in a local scope. Q 3) A constructor must return None, it cannot return "self". Q 4) The address of instance matches with the instance within the constructor. Q 5) Even though the constructor returns None, the instance is properly initialised (with inherited attributes). The following is my program: ############# class A: x = 100 class B(A): def __init__(self): # Q1 print 'inside constructor self is ', self self = 300 # Q2 print 'inside constructor self is ', self # Q3 return None b = 200 b = B() print 'after constructor instance b is ', b # Q4 print 'instance b contains attribute x, valued ', b.x # Q5 ############ The following is the trace: prompt > inside constructor self is <__main__.B instance at 0x80e9c94> prompt > inside constructor self is 300 prompt > after constructor instance b is <__main__.B instance at 0x80e9c94> prompt > instance b contains attribute x, valued 100 Could anyone tell me whether the explanation is correct or not? Any comments would be appreciated. Thanks Ben From gmcm at hypernet.com Sun Mar 10 09:50:59 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 10 Mar 2002 14:50:59 GMT Subject: win32 extension: rare PythonService problem References: Message-ID: Zihong Lu wrote: > I use the win32 extension PythonService to write a windows service for > our project. The service runs fine on most NT, win2k machines. > Recently our customers reported that for some PCs, the command "python > MyService.py start" returned as usual, no traceback, but the service > did not start at all. I would suspect permissions. I had a similar experience when moving a service from a test box to prod. Eventually the sys admin created a new account and things started working. As a lowly contractor I wasn't allowed to find out what he actually did, though ;-(. -- Gordon http://www.mcmillan-inc.com/ From peter at engcorp.com Sun Mar 31 01:38:31 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 01:38:31 -0500 Subject: list subscripting (nested lists) References: Message-ID: <3CA6AEE7.FCA19F98@engcorp.com> les ander wrote: > > is it possible to have nested lists indexing in python? > i.e. index=[3,1,1] and List1=['a','b','c','d'] > then List1[ index ] should print out ['d','b','b'] > > I think this would be a cool feature to add if not already present. It's already present... >>> index = [3, 1, 1] >>> list = ['a', 'b', 'c', 'd'] With list comprehensions: >>> [list[i] for i in index] ['d', 'b', 'b'] Any Python: >>> map(list.__getitem__, index) ['d', 'b', 'b'] Good enough? From peter at engcorp.com Fri Mar 1 06:23:59 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 01 Mar 2002 06:23:59 -0500 Subject: ASV module, CVS modules References: <61ff32e3.0202281525.3e9bb102@posting.google.com> <3C7F4014.7090800@stroeder.com> Message-ID: <3C7F64CF.771E7319@engcorp.com> Michael Str?der wrote: > > John Machin wrote: > > > > You 2: On Windows, either use forward slashes "c:/test_data.csv" (it > > works!) > > AFAIK this does not work on W2K anymore. I might be wrong. Since Win2K is just WinNT relabelled, I suspect you're wrong. I could be wrong though. :) From rjones at ekit-inc.com Fri Mar 29 18:38:59 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sat, 30 Mar 2002 10:38:59 +1100 Subject: Anyone need a program written? In-Reply-To: References: Message-ID: <200203292339.XAA17559@crown.off.ekorp.com> On Sat, 30 Mar 2002 04:52, rasmussn at lanl.gov wrote: > On Friday, March 29, 2002, at 10:46 AM, phil hunt wrote: > >> "Fused" wrote in > >> message news:3ca43ef4.3666136 at news.tudelft.nl... > >> > >>> I'm currently trying to master Python, but to succeed I need to > >>> exercise. However, I detest building programs that have already been > >>> built a kazillion times and aren't of use to anyone. > >>> Can anyone think of a program that I could build that would actually > >>> have use to someone (you?)? I'm trained in Delphi, know some Java and > >>> rudimentary C, so the programs don't need to be newbie-easy ( I like a > >>> challenge: the greater the challenge, the faster I'll learn ;-) ). > > How about a Python substitute for make. Isn't that what SCCons is all about? http://www.scons.org/ Richard From facelle at jumpy.it Fri Mar 15 14:02:04 2002 From: facelle at jumpy.it (Fabrizio) Date: Fri, 15 Mar 2002 20:02:04 +0100 Subject: Access to shared directories Message-ID: Hi, Newbie. Python 2.1.2 on Win98. I just want to read a .txt file that I have in a shared directory on another PC which is part of a WindowsNT/98 LAN. What path should I use in order to read that file from my PC ? Thanks in advance, Fabrizio From aahz at panix.com Fri Mar 8 11:24:04 2002 From: aahz at panix.com (Aahz Maruch) Date: 8 Mar 2002 08:24:04 -0800 Subject: how to pass by reference?? References: Message-ID: [after letting this sit for a couple of weeks, I decided I wanted to make a couple more additions; I'm leaving this mostly unsnipped for clarity.] In article , Steve Holden wrote: >"Aahz Maruch" wrote in message >news:a3sklt$7vr$1 at panix2.panix.com... >> >> Um, that's not IMO/IME a particularly useful way to look at it. I don't >> remember who first proposed it, but I find talking about "names" and >> "bindings" to be much clearer. When talking about parameter passing, one >> would say that the function parameters create new names that get bound to >> the passed in objects. Any time one uses assignment on the function >> parameter names (or any other name in Python, for that matter), the name >> gets rebound to a different object. >> >Maybe we should beat this one to death with a rock ;-) I should point out >this is not for Aahz' benefit, since he knows it already. > >Any time one uses assignment, one causes a name to be bound to an object. >Argument passing is actually binding a name (the argument name, present in >the function's local namesspace) to an existing object -- whatever was >passed as an argument, whether it was written as a complex expression (which >could create an object "on the fly") or simply as an existing name (which >would be a simple reference to an existing object). > >Assignment to the argument name inside the function, as Aahz points out, >simply rebinds the argument name to a new value. Which means that such an >assignment will not change the object passed as an argument. > >Assignment to *a component of the argument*, however, is a completely >different case (as I think someone else has already pointed out). So, if you >pass in to a function an argument arg, the assignment > > arg = something_new > >will leave the argument object completely unaltered. However, the assignment > > arg[0] = something_new > >will modify a list argument, and this modification will be visible outside >the function as well as inside it. You have mutated the object passed as an >argument, and so all names bound to that object will access the mutated >value. Similarly with arg.attr = something.new, arg.append(something), and >so on. In the case of arg[0], this is Python's special syntactic sugar for turning an assignment into a method call: arg.__setitem__(something_new) As pointed out earlier, this still involves a binding (because methods are functions), but it's hidden through the method call. In fact, there are actually two bindings, one for the method call itself and one inside the method when it mutates the object. In the case of arg.attr, I think it should be made clear that in Python the "." is a signifier for namespace access. That is, "arg.attr" should probably be written as namespace.attr for the purpose of this discussion. That makes it clearer that you can do things like this: import foo foo.bar = something_new def f(): pass f.a = something_new >> If the object is mutable and mutated, all names that are bound to that >> object see the changes. Mutation, by definition, *never* involves a >> rebinding of the object being mutated (that is, mutation never takes >> place in an assignment -- though of course the assignment expression >> might involve mutation as a side-effect). >> >You have to be careful to distinguish here between simple assignments (x = >expr) and augmented assignments (x += expr), since the latter are explicitly >allowed to mutate the object referenced by the name, but need not do so if >the implementation of the object concerned chooses not to. The former, I >agree, are simple rebindings. Again, augmented assignment translates into a method call; whether the method returns the original object or a new one depends primarily on whether the object implementing the method is mutable or immutable. >> (Yes, you're talking about binding, but you don't go whole hog, which >> confuses the issue.) >> >I didn't get where I am today by not going the whole hog . > >luckily-tim's-at-developers'-day-ly y'rs - steve Not anymore! (I'm doing this followup primarily for myself, as part of the tutorial I'm hoping to do for OSCON this year.) -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From l0819m0v0smfm001 at sneakemail.com Thu Mar 7 23:57:10 2002 From: l0819m0v0smfm001 at sneakemail.com (Joshua Macy) Date: Fri, 08 Mar 2002 04:57:10 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> Message-ID: <3C880AC2.6070708@sneakemail.com> Greg Ewing wrote: > I have another idea that doesn't suffer from that > problem. > > def string my_string: > This is a free-form string constant. Its value consists > of all the text at this indentation level, verbatim, > with the indentation stripped off. It can contain > ', ", ''', """, \ or any other characters. > > But then you have to indent everything in the text to that level, which isn't quite the same as cut-and-paste arbitrary text any more. Granted, it's not hard to do with a good editor, but neither is escaping a whatever triple quotes you might find in the text (even Notepad can do that). For that matter, the PEPs to make Python more unforgiving of what's contained in strings (only valid declared encodings or binary as octal escape sequences) seem to be advancing rapidly, so schemes for stuffing more arbitrary and unexamined junk into the source code seem to be heading in the wrong direction. I guess I don't really see the motivation for the proposed feature. If triple quoting isn't sufficient, I'd take that as a sign that the material should be a separate data file...it's not like Python makes it hard to read an external file into a string. Joshua From newgene at bigfoot.com Wed Mar 27 00:02:25 2002 From: newgene at bigfoot.com (newgene) Date: 26 Mar 2002 21:02:25 -0800 Subject: Looking for a python shell under linux like PythonWin Message-ID: Hi, group, The only python shell under linux I can find is IDLE, but it is not as good as PythonWin. A important feature "Attribute expansion"(a list of attributes for selection when pressing period after a module name) is not available. Is there a good python shell existing on linux now? Thanks. Newgene From greg at cosc.canterbury.ac.nz Wed Mar 20 22:32:38 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 21 Mar 2002 15:32:38 +1200 Subject: Attachments to the list/group - OK? (Was Re: Popular style document?) References: Message-ID: <3C995456.C0E85C39@cosc.canterbury.ac.nz> Dietmar Lang wrote: > > Well, there are things such as binaries or images groups where people > constantly exchange files. Can't you simply attach them, or do they post > them inline? Using an attachment for that makes fairly good sense in this day and age, given that MIME-aware mail and news readers are pretty widespread... provided that posting it to a newsgroup is really appropriate in the first place. Binaries groups came into existence before we had the Web. Now that we do, posting a link to a web site is usually preferable to posting anything large to a newsgroup. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From ifls at rz.tu-clausthal.de Tue Mar 19 03:50:13 2002 From: ifls at rz.tu-clausthal.de (Lutz Schroeer) Date: 19 Mar 2002 08:50:13 GMT Subject: Pure python alternative to mx.DateTime? Message-ID: One of my web hosts does not have a C compiler installed so I can't install mx.DateTime on that machine, because it need some C routines. Unfortunately I'm in need of some simple time and date calculations (ISO-time, how many days from now, weekdays, etc.). Is there any alternative to mx without inventing the wheel for the second time and programming it by myself? Lutz -- From stojek at part-gmbh.de Thu Mar 7 14:38:02 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Thu, 07 Mar 2002 19:38:02 GMT Subject: Determine size of wxSplitterWindow Message-ID: <3c87c189.40797156@news.easynews.net> Hi, I have cut down my problem. It seems to be impossible for me to determine the size of a wxSplitterWindow. The results of GetSizeTuple() are wrong. How comes? btw.: sashPostion=0 should split the Window in the middle, which it does not. Tanks for any help. Marcus -----snip-- from wxPython.wx import * #--------------------------------------------------------------------------- class ABA_CM(wxApp): def OnInit(self): title = "Test" frame = MainFrame(NULL, -1, title) frame.Show(true) self.SetTopWindow(frame) return true #--------------------------------------------------------------------------- class MainFrame(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self, parent, -1, title,size=wxDefaultSize, pos=wxDefaultPosition) splitter=wxSplitterWindow(self, -1) CMwin = wxWindow(splitter, -1, size=wxDefaultSize,pos=wxDefaultPosition) ABAwin = wxWindow(splitter, -1, size=wxDefaultSize,pos=wxDefaultPosition) splitter.SplitVertically(CMwin, ABAwin,sashPosition=0) CMwin.SetBackgroundColour(wxRED) ABAwin.SetBackgroundColour(wxBLUE) print CMwin.GetSizeTuple() print ABAwin.GetSizeTuple() #--------------------------------------------------------------------------- app = ABA_CM(0) app.MainLoop() -----snap-- From phr-n2002a at nightsong.com Sat Mar 16 21:34:17 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 16 Mar 2002 18:34:17 -0800 Subject: Enhanced information from common exceptions References: Message-ID: <7xsn6zx6qe.fsf@ruckus.brouhaha.com> Tim Peters writes: > A difficulty with this kind of thing is that producing exception info > doesn't come for free. Before 2.2, raising IndexError was the only way to > terminate a "for" loop via normal exhaustion, and the list indexing code has > no idea *why* it's being called. If it produced more info on an > out-of-range index, it would slow down every normal loop by the time it took > to construct a nice exception message doomed to be thrown away unlooked-at. > Note that the integers in your ideal message have to go through binary -> > decimal string conversion, and lots of dynamic string fiddling to paste all > the msg pieces together. The cycles add up fast. Well, raising the exception could put the index and list length into slots in the exception object, rather than formatting them. Exception objects could even have a few built-in slots for such purposes, so they wouldn't have to contain dictionaries. From emile at fenx.com Sat Mar 23 11:07:10 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 23 Mar 2002 08:07:10 -0800 Subject: simple question References: <2UVm8.30655$J54.1855090@news1.west.cox.net> Message-ID: Terry Reedy > ) or 4 digits: > ''.split(str(a)) > ? > hmm... list(str(a)) does better for me. -- Emile van Sebille emile at fenx.com --------- From paul at boddie.net Mon Mar 11 10:25:49 2002 From: paul at boddie.net (Paul Boddie) Date: 11 Mar 2002 07:25:49 -0800 Subject: Python daemon instead of CGI programs References: <88bc63c6.0203061444.30ad9c44@posting.google.com> Message-ID: <23891c90.0203110725.4e033c2f@posting.google.com> writeson at earthlink.net (Doug Farrell) wrote in message news:<88bc63c6.0203061444.30ad9c44 at posting.google.com>... > Hi all, > > I've got an idea that anyone is welcome to shoot holes in as it's only > in the 'thought' process now. I work for a company that develops > big content web sites using CGI's built with C++ as the primary > programming model. We also use Netscapes iPlanet as our web server. I've lived through this kind of nightmare myself - C++ is bad enough as a programming language for CGI-based applications (even with reasonably high-level libraries), but to add the iPlanet Web server to all that is particularly cruel. [Description of a mod_python or mod_snake equivalent] > We don't have to work out any of the complexities of > connecting mod_python.so to iPlanet. Well, there was once an implementation of an NSAPI module which surely worked with Netscape's (now iPlanet's) server products, and even that might be worth looking into. Personally, having been inconvenienced enough in the past by the "features" of Netscape's Web server, and not being entirely convinced that the product has moved on considerably over the past few years, I'd seriously suggest saving yourself some work and moving to Apache if at all possible. > What do you think of this idea? Am I completely off base and missing > some other obvious solution? Here are some options: * The NSAPI module, if you can find it and it still works. (And you're desperate to stick with iPlanet server - that licence was probably expensive, unless it came free with Solaris...) * Apache with mod_python or mod_snake, or even mod_webkit (and Webware) or SkunkWeb. * iPlanet, Apache or something else, with a CGI adapter (or something more exotic - see the previous option) and one of the Python Web frameworks. The last option is a bit more radical, since you would need to adopt a different programming model. However, Webware's servlets and even Zope's products are nicer to write than CGI programs. Paul From mwh at python.net Thu Mar 21 07:27:19 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Mar 2002 12:27:19 GMT Subject: Python-2.2.1c1 Build Problems on Linux and AIX. References: Message-ID: ralph at inputplus.demon.co.uk (Ralph Corderoy) writes: > > More detail needed. > > And you'll get it. This was just a two line overview :-) Get on with it then! Cheers, M. -- Monte Carlo sampling is no way to understand code. -- Gordon McMillan, comp.lang.python From bhahn at spam-spam.g0-away.com Mon Mar 4 17:10:08 2002 From: bhahn at spam-spam.g0-away.com (Brendan Hahn) Date: Mon, 04 Mar 2002 14:10:08 -0800 Subject: Adding static typing to Python References: <0DFA7478F1E5D311B90900508B1208CF565714@ausmail02.mis.gtech.com> Message-ID: Courageous wrote: >One of the things I like about C sharp is their use of attributes, >where you can define getters and setters on an attribute, but >otherwise the attribute is simply used as if it were a public one. Eiffel does this. It was one of the first things to make me say "Cool!" when I started looking into it. bhahn at transoft.mmangle.net <-- unmangle address to reply From MaximilianScherr at T-Online.de Wed Mar 20 15:31:46 2002 From: MaximilianScherr at T-Online.de (maximilianscherr) Date: Wed, 20 Mar 2002 20:31:46 -0000 Subject: eval() Message-ID: what does eval exactly do? could it do somehting like opening a text file with this: hello = 1 if hello = 1: print 'yeah' eval(readline()[:-1]) ... ? like external scripts? From Moo at houston.rr.com Thu Mar 7 00:24:42 2002 From: Moo at houston.rr.com (Avi Homes) Date: Thu, 07 Mar 2002 05:24:42 GMT Subject: Dictionaries in Lists References: Message-ID: "j vickroy" wrote in message news:a661gr$d2s$1 at mwrns.noaa.gov... > Nothing wrong with the idea. > > Did you specify: > > > Info = {'IName':"Voodoo2",'IDescription':"blahblah"} > > or what you posted (which had some syntax errors)? > > "Avi Homes" wrote in message > news:ayvh8.55100$6j2.3265866 at typhoon.austin.rr.com... > > I was attempting to make a list of dictionaries, which to me feels like > the > > C equivlant of an array of structs, kind of. anyway, after making a > > dictionary and putting some values into it, and trying to append it to a > > list, python is not liking this. Am I approaching the idea the wrong way? > i > > would like to keep the data organized as dictionaries.. the code looked > > something like > > > > Info{'IName':"Voodoo2",'IDescription':"blahblah} > > Listing=[] > > Listing.append(Info) I was shooting it off of the top of my head, the code is on the student network which I do not have access to from home. Anyway, there was an assignment sign between the Info and {} for the dictionary. I'll have to look at the code again, but alas, I'm leaving town today (thursday) and ill be gone for two weeks. so, I may just end up rewriting the code, because I know that the idea will work, I can indeed put a list of dictionaries, so I'll just rewrite it while im on the plane. thanks guys, and next time ill have the code with me From phd at phd.pp.ru Tue Mar 19 08:24:24 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 19 Mar 2002 16:24:24 +0300 Subject: socket.gethostbyname() AttributeError In-Reply-To: ; from ralph@penguin.com on Tue, Mar 19, 2002 at 01:12:58PM +0000 References: Message-ID: <20020319162424.L3447@phd.pp.ru> On Tue, Mar 19, 2002 at 01:12:58PM +0000, Ralph wrote: > I assumed that for scoket.gethostbyname(host), I was to pass a host of the > type "theodore.chipmunks.com" and that I would get back an IP address as a > doted quad. Obviously I am wrong about the form of the arguement I am to > pass to the function, because I am getting an AttributeError message. > > Can anyone offer some insight? Python 2.2 (#1, Dec 24 2001, 17:25:15) [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> socket.gethostbyname("www.python.org") '194.109.137.226' Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From usenet at thinkspot.net Thu Mar 14 00:42:23 2002 From: usenet at thinkspot.net (Sheila King) Date: Wed, 13 Mar 2002 21:42:23 -0800 Subject: Performance problem with filtering References: Message-ID: On Thu, 14 Mar 2002 15:51:22 +1100, "Delaney, Timothy" wrote in comp.lang.python in article : > > From: Sheila King [mailto:usenet at thinkspot.net] > > How does something with list comprehensions compare? Like: > > > > b = [entry for entry in b if entry not in a] > > > > Is this as slow as the original method suggested? Or is it closer to > > dictionary performance? > > Essentially, that is identical to the original method. Simply expand it out > ... (need to use a temporary name though). > > temp_b = [] > > for entry in b: > if entry not in a: > temp_b.append(entry) > > b = temp_b > del temp_b I understand how it works logically. I simply thought there might've been some tricky C implementation of list comprehensions that improved performance. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dgallion1 at yahoo.com Fri Mar 15 10:30:33 2002 From: dgallion1 at yahoo.com (Darrell) Date: 15 Mar 2002 07:30:33 -0800 Subject: how to check how many bytes are available to read() ? References: <2b57f654.0203142026.68ec3fc7@posting.google.com> Message-ID: Examples of using pipes and the work around for blocking reads. Use os.read(fileHandle) http://ezwiki.com/2.54/python/popenTest.py http://sourceforge.net/tracker/?func=detail&atid=105470&aid=527783&group_id=5470 --Darrell grante at visi.com (Grant Edwards) wrote in message news: > > If f is a pipe, then you can use select -- at least under Unix. > I don't know about Windows. From tdelaney at avaya.com Wed Mar 27 20:13:28 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 28 Mar 2002 12:13:28 +1100 Subject: Why does this work? Message-ID: > From: Don Garrett [mailto:garrett at bgb-consulting.com] > > "Delaney, Timothy" wrote: > > > > __slots__ > > Um... this does help protect them from outside > interferance, but doesn't in > any way require them to have been initialized in __init__, or > even protect you > from a misspelled name, does it? Just trying to make sure > that nothing goes on > with __names besides the name mangling into __class__name. http://www.amk.ca/python/2.2/index.html#SECTION000340000000000000000 __slots__ does indeed protect against misspelled names (but does not require initialisation in __init__ - that's up to you). For a private attribute, I think you would need to do the name mangling for __slots__ manually i.e. __slots__ = ['_ClassName__attr'] although I'm happy to be corrected if this is not indeed the case :) Tim Delaney From eppstein at ics.uci.edu Thu Mar 21 02:51:32 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 20 Mar 2002 23:51:32 -0800 Subject: Word frequencies -- Python or Perl for performance? References: <3C998FDE.5080204@geneva-link.ch> Message-ID: In article <3C998FDE.5080204 at geneva-link.ch>, Boris^2 wrote: > > I'm trying to figure out what the Internet is thinking today. > > What the internet is thinking, what the market is thinking... > sounds to me like attempts to pass epidemics for thought processes. I don't know, sometimes it seems like Google is close to omniscient. Of course, it can't pass the Turing test, but its answers to natural-language questions are usually a lot more intelligent than the answers of programs designed to pass Turing tests. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From herrn at gmx.net Thu Mar 7 18:50:52 2002 From: herrn at gmx.net (Marco Herrn) Date: Fri, 8 Mar 2002 00:50:52 +0100 Subject: how to give an object as argument for a method In-Reply-To: References: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> Message-ID: <20020307235052.GB4209@lurkabove.darkstar> On Thu, Mar 07, 2002 at 03:46:59PM +0000, Grant Edwards wrote: > In article , Marco Herrn wrote: > > > Is there a reason why this is just a convention? > > Because it seems to work well enough that way. > > > It seems (because it is such a _strong_ convention) that this > > should be a real feature of the language. I mean that there > > could be a reserved word "self" which is there all the time, so > > that one doesn't hast to do this himself. > > It would make the language and the parser more complex. > Extra cost must be justified by some corresponding gain. It > would also make it less obvious what "self" is if the first > parameter to a method was hidden from the user. > > If a function expects a parameter, then it should show up in > the function definition. Methods are just functions whose > first parameter is expected to be an object reference. Hmm, ok. All you say seems right to me. But what is a bit strange is, that I explicitly have to implement 'self', but don't give it as argument. If a have a method with the defininion 'f(self)' I call this method only with 'f()'. So the declaration doesn't look the same like the call. So you think it will stay this way, that one has to implement it for himself. That's ok. I can live with that. But I don't see any disadvantage, when changing the language so that a 'self' statement is always available. Bye 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 daniel.dittmar at sap.com Wed Mar 13 12:26:40 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 13 Mar 2002 18:26:40 +0100 Subject: Why I think range is a wart. References: Message-ID: > It happens to me too, mostly when I'm using a sliding window > type algorithm, that is, I need to look at two adjacent members > of the list. You can't do this easily by iterating through the list; > unrolling the first entry and the last entry are a pain. > > Is there a way of handling this nicely? Somehow I doubt it. class ListWindow: def __init__ (self, list): self.list = list + [None] # assuming None is a suitable out of bounds value def __getitem__ (self, index): return self.list [index:index + 2] for currentItem, nextItem in ListWindow (mylist): Daniel From skip at pobox.com Fri Mar 8 15:20:10 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 8 Mar 2002 14:20:10 -0600 Subject: Is current integer for-loop syntax a wart? In-Reply-To: References: Message-ID: <15497.7418.152505.116790@beluga.mojam.com> >>>>> "Jeremy" == Jeremy Cromwell writes: Jeremy> [is] the current integer for-loop syntax Jeremy> for i in range(10): Jeremy> a wart? -Wart Actually, I'd call it a mini-wart, sort of halfway between -Wart and -Wart?. Explanation: It seems a bit cumbersome that you have to call a function to use such a fundamental control structure. From an optimization point of view, a purely syntactic indexing construct would allow better inference about data types. You can't know ahead of time that range() always returns ints. (I've never seen anyone override it, but it *is* possible.) Tools like PyChecker can get away with assuming it's an int. Psyco assumes builtin functions never change, so it can dramtically improve for loop execution by dealing just with C ints. That means, strictly speaking, that it's not semantically identical to CPython, however. I believe over time it will be able to relax its assumptions about range's befahvior and do the semantically right thing. (I think Python2C also had an option that allowed the programmer to state this explicitly.) So, in my mind a syntactic replacement for range() would be nice, but not of earth-shattering importance. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From ykingma at accessforall.nl Sun Mar 31 06:16:47 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Sun, 31 Mar 2002 12:16:47 +0100 Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: <3CA62CD8.6ABD44D0@accessforall.nl> Message-ID: <3CA6F012.E2631003@accessforall.nl> Martin, you wrote: > > Ype Kingma writes: > > > Python is sufficiently high level not to care about the bits. > > Python never had a C float type, only a C double type, for precisily > > this reason. > > Python does, however, have a long int type, side-by-side with the int > type - because it cares about bits. Atleast it used to, there is a PEP > for merging the two integer types. There is also a PEP merging all > numeric types into a single one, or a hierarchy of types. I was referring to the bits in flag registers which allow all kinds of beatiful assembly language optimizations. I think we mostly agree here. I'd like to know whether this PEP merging all numeric types would also merge the bool type into its evt. hierarchy. > > Notice that the relationship of bool and int has two aspects: one is > whether you can combine them in numeric operations, > e.g. 28+isleap(year). There is absolutely no way to remove this > property from the language - too much code would break if that would > raise an exception. There are two ways to do this: - marking such code with: from __past__ import nonbool (as I remarked earlier this is rather radical) - defining __add__ and __radd__ in the int and float classes to also accept a bool sounds quite pythonic and acceptable to me. > The other question is whether bool should inherit from int. Notice > that this is unrelated: you could have the arithmetic operations even > without inheritance. The inheritance from int is mostly an > implementation convenience: too much code in the interpreter itself > would need to change to make bool inherit from object only. Agreed. > > Somehow this reminds me of subclassing Square from Rectangle: > > it just doesn't feel right, even though it might work. > > I can't see the relationship: A Sqare is-a Rectangle, so following > classic OO principles, the inheritance is clearly right. Depending on > how you define the Rectangle interface, this inheritance relationship > would even satisfy LSP. An Square that is a Rectangle has inherits two degrees of freedom, (height and width) which have to constrained to a single one in the implementation. Implementing such constraints is a bit awkward and can be avoided by implementing Square as a OneDegreeOfFreedomThing and a Rectangle as a TwoDegreeOfFreedomThing. These ...DegreeOfFreedomThing's are intended as abstract to be consistent with the design rule to not inherit from a class that has instantions. When bool is-a int, one would have to (awkwardly) implement at least one such constraint, namely that bool values can only be 1 or 0. > > With a non int bool, True and False would be real singletons: > > > > bool(1) is True > > bool(0) is False > > They are singletons even under the PEP: You have to work really hard > to make two instances of True (bool(1) is (not bool(0)) is bool(1) is > True); and if it was a type not inheriting from int, you could *still* > make extra instances if you wanted to hard enough. > > > True is not 1 > > This is True in the PEP. > > > True != 1 > > This is False, and it should be, since making it True would break > backwards compatibility. Ok. But just like the bool + int things above this could be implemented by implementing __cmp__ and __rcmp__ for the bool class and/or the numeric class. > > > Subclassing bool from int would also force 1 and 0 to be become > > real singletons. > > Can you elaborate? This is not at all the case. > > > The only reason this would work is that current python > > implementations happen to implement 1 and 0 in this way. > > Not at all: > > >>> (1>0) is 1 > 0 You're right. > > But you could make the language definition simpler by explicitly > > defining the cast to bool in contexts where a boolean is expected, > > see above. This would allow the current casts (eg. list to bool as > > non empty) to be described at the standard types instead of in the > > language definition. > > It is already that way, the method determining truth is __nonzero__; > for historic reasons, a number of fallbacks are taken if __nonzero__ > isn't implemented. I guess it's time for me to reread the fine manual and to read the bool thread on python-dev about whether the __add__ and __cmp__. Thanks for the corrections, Regards, Ype From stevena at neosynapse.net Thu Mar 7 21:28:19 2002 From: stevena at neosynapse.net (Steven D. Arnold) Date: Thu, 7 Mar 2002 21:28:19 -0500 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: References: Message-ID: <553719390.20020307212819@neosynapse.net> Hi Fernando, On Wednesday, March 06, 2002, at 5:05:03 AM, Fernando P?rez wrote: FP> Very nice, and thanks for the contribution. I've long been a fan FP> of this idea. But could you please clarify if your module is in FP> anyway different to the 'old' interpolation module that's been the FP> reference implementation to PEP 215? You can find it at FP> http://web.lfw.org/python/ towards the middle of the page. Also FP> see pep215 at http://python.sourceforge.net/peps/pep-0215.html I apologize for not responding last time; I did see your previous post but I'm usually very busy and I only have time to read python-list and respond to posts occasionally (though I always enjoy it when I do). FYI, if you do really desire a response from me on any subject, it's best to send an email to me directly or send me an instant message. I'd say the biggest difference is that istring is a type of string (descended from the str class). This gives it a lot of out-of-the-box features and compatibility that itpl doesn't have. On the other hand, the parsing in itpl is more elegant. When I get some time, I'll see what I can learn from his code. :-) In brief response to some other points raised in this thread: 1. What's wrong with the %(foo)s approach? Nothing, if you have a dictionary ready to go with the key/value pairs you need. istring fully supports the use of such constructs when you find it appropriate to use them. I'd say if you have a string that needs a lot of keys from a particular dictionary and you have just such a dictionary, you may want to use the %(foo)s format -- although personally I still find it less pleasing to the eye and less immediately readable than the $ notation. I suppose there's no accounting for taste. :-) 2. Some have asked why one would not use vars() and the mapping format all the time, since vars returns a dictionary of the local namespace? The problem with vars() is that (at least as far as I know) it doesn't support dictionaries, lists, object attributes and function calls. Furthermore, if you use a mapping, it has to support all substitutions in the string -- you can't intermingle with other variables. With istring, you can use $ notation for some variables and use vars() or another mapping for other substitutions. 3. DB API substitution -- it's true, you're better off using the DB API substitution rather than sending a literal string. I'd like to update istring to support this -- that is, you still see the same kind of string from the user perspective, but the actual query is submitted to the DB API behind the scenes in the correct way. I feel sure this is possible, it just hasn't been done yet. IMO, this is by far the most serious reason not to use istring, and it only applies to SQL. So, I hope to remove it as an objection soon. 4. Standard library -- If anyone wishes to take the steps to include it in the standard library, including any PEPs that may be needed in addition to 215, you have my blessing and I'll provide support. The current license is LGPL-like, with the intent of ensuring changes are open-source without infecting projects that use it. I will make istring available under the Python license if that is the only obstacle keeping it from inclusion in the standard library. In the meantime, it's practically like, say, an r or u string, except with parentheses: >>> from neo.istring import istring as i >>> l = [1,2,3] >>> i('first value is $l.0') 'first value is 1' Bottom line, I hope you like it and benefit from it. If you don't like it, then I wish you the best too, using whatever tools you do like. It's not a religion to me, just Python code. :-) Cheers! -------------------------------------------------------------- Steven D. Arnold Neosynapse stevena at neosynapse.net Managing Partner AIM: abraxan MSN: neosynapse at hotmail.com From duncan at NOSPAMrcp.co.uk Wed Mar 6 09:33:07 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 6 Mar 2002 14:33:07 +0000 (UTC) Subject: [ANN] istring 1.0.1 released; announce list created References: <3C86047F.1080601@stroeder.com> Message-ID: Artur Skura wrote in news:slrna8c26g.eug.arturs at aph.waw.pdi.net: > Ask yourself which query is clearer: > > (1) db.query("""SELECT foo, bar > FROM %s > WHERE rsrc_id = %s > AND name = '%s'" % (table, rsrc_id, name)) > > Or: > > (2) qry = istring("""SELECT foo, bar > FROM $table > WHERE rsrc_id = $rsrc_id > AND name = $.name""") > db.query(qry) > I vote for (3): db.query("""SELECT foo, bar FROM %(table)s WHERE rsrc_id = %(rsrc_id)s AND name = '%(name)s'" % vars()) You have the names for interpolation, AND control over the formatting. Someone should dust down the time machine and implement it. Oops, they did. Although, I sure hope there aren't any funny characters embedded in any of those variables that might turn the query into a DELETE... -- 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 justin at iago.org Mon Mar 11 11:03:47 2002 From: justin at iago.org (Justin Sheehy) Date: Mon, 11 Mar 2002 11:03:47 -0500 Subject: ' in ' works, why doesnt ' in '? In-Reply-To: <4abd9ce7.0203101059.444f1ec1@posting.google.com> (morton@dennisinter.com's message of "10 Mar 2002 10:59:51 -0800") References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> <4abd9ce7.0203101059.444f1ec1@posting.google.com> Message-ID: morton at dennisinter.com (damien morton) writes: > Strings are like sequences in that their individual elements > (characters ONLY) can be accessed as a sequence, but there are > important differences in the kinds of things people want to do with > strings. Strings are not like sequences, strings are sequences. > I think the verb IN means something slightly different for strings > than it does for sequences and dicts. Again, since strings are sequences, the operator "in" does not mean something different for strings than it does for sequences. It cannot, since that sentence is not meaningful. You may think that about a verb, but the issue at hand is an operator. As readable as Python is, it does not (and should not) strive to read just like English or any other language except perhaps Dutch. -Justin From philh at comuno.freeserve.co.uk Thu Mar 7 11:29:48 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 7 Mar 2002 16:29:48 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 15:35:06 -0800, David Eppstein wrote: >In article , > Steve Lamb wrote: > >> I fail to see how it is is greader readability or understanding when the >> current method is both. > >I diagree that the current method has both, or either. I don't know >about you, but I find "for x in range(n-1,-1,-1)" to be a difficult to >read and difficult to understand way of obfuscating a simple loop over >the numbers 0 to n-1 in reverse order. I think "for n > x >= 0" would >be much simpler. I think for x = n-1 to 0 step -1: would be about as obvious as it gets -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From gargravarr at whoever.com Wed Mar 20 15:34:31 2002 From: gargravarr at whoever.com (gargravarr at whoever.com) Date: Wed, 20 Mar 2002 20:34:31 GMT Subject: Unicode problem Message-ID: <3c98f206.24909027@news.tiscali.no> I have a problem with Unicode strings, the error I get is: UnicodeError: ASCII encoding error: ordinal not in range(128) It is caused by body.write('

    %s

    \n' % i.firstChild.data) Where body is a StringIO object, and i is a xml.dom.minidom object. The characters it reacts to is the 3 Norwegian 'extra' ones: ?, ?, ? (if you can see them) Using Python2.2 on Win32 Help appreciated Thansk in advance! Tom From nick at nick8325.freeserve.co.uk Tue Mar 19 12:54:51 2002 From: nick at nick8325.freeserve.co.uk (Nick) Date: Tue, 19 Mar 2002 17:54:51 -0000 Subject: Newbie: word count and Win32 References: Message-ID: "Joe Christl" wrote in message news:e9cd3ea2.0203190421.904cdfb at posting.google.com... > newbie here (don't you just cringe when you read that? :), > > I downloaded the python EXE from > http://www.python.org/ftp/python/2.2/, found a script on the > mail.python.org Tutor page: > http://mail.python.org/pipermail/tutor/2001-February/003403.html > > but I can't seem to get it to run. I would like it to run from the > C:\ command prompt, like so: > > c:\count.py foo.txt (or) > c:\count.pyc foo.txt > > and have it output the lines, words, and characters. I have tried to > even get it working from the >>> prompt, to no avail. > > Am I doing something wrong here? > > Thanks for your ideas, > Joe What happens if you type python c:\count.py foo.txt? From duncan at NOSPAMrcp.co.uk Tue Mar 26 07:56:58 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 26 Mar 2002 12:56:58 +0000 (UTC) Subject: implementing a constant singleton References: Message-ID: "robin and jim" wrote in news:p4_n8.1650$Ya2.72647 at newsread1.prod.itd.earthlink.net: > Is this the way to implement a constant singleton class using Python 2.2 > "new-style" classes? If you really feel a need for singletons, then I suppose this is a way to do them. Personally, I prefer to avoid singletons if possible. > class Message(str): > > def __new__(this_class, specification): > print 'Message.__new__ applied by %s' % str(this_class) self = str.__new__(this_class, specification) > self.subject = specification[0] > self.body = specification[1:] Running __new__ and __init__ together gets round your issue with __init__ being called every time. > class Constant_Singleton_Message(Message): > > def __new__(this_class): > it = this_class.__dict__.get('__it__') Don't use __it__ as it is reserved for Python. -- 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 rjones at ekit-inc.com Sun Mar 31 01:15:37 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sun, 31 Mar 2002 17:15:37 +1100 Subject: Subclass sadness (was Re: [Python-Dev] PEP 285: Adding a bool type) In-Reply-To: References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> Message-ID: <200203310615.GAA25295@crown.off.ekorp.com> On Sun, 31 Mar 2002 15:46, Andrew Koenig wrote: > The other way around -- inheriting rectangle from square -- would > seem to make more sense because a rectangle has all the information > that a square does, and then some. But that doesn't really work either, > because then you can no longer assume that every kind of square is > really a square. After all, it might be a rectangle. Hrm, just following this thought here, possibly for no good reason at all (hey, it's Sunday, and daylight savings just ended so I've got a whole _hour_ extra to waste today :)... hell, I can't even remember what the point of the circle/ellipse comment was ;) Surely sqaure and rectangle (and parallelogram) subclass a more fundamental four-sided-shape (er, I can't believe it, but I've forgotten the name for them ;)? They impose their own constraints on the four-sided-shape, given it has side lengths and angles between the sides. Right, back to doing other slask-Sunday stuff now ;) Richard From pj at sgi.com Thu Mar 7 19:34:43 2002 From: pj at sgi.com (Paul Jackson) Date: 8 Mar 2002 00:34:43 GMT Subject: [OT] range() for unix shell References: <2adab837.0203071409.76588265@posting.google.com> Message-ID: The following patch fixes a couple of typos in the above range() command: --- range.py.orig Thu Mar 7 16:33:01 2002 +++ range.py Thu Mar 7 16:31:57 2002 @@ -13,7 +13,7 @@ In first case, low == 0 is implied If no step size is given, 1 is assumed """ - exit + sys.exit(1) low = 0 step = 1 @@ -27,6 +27,6 @@ high = int(sys.argv[2]) step = int(sys.argv[3]) else: - usage + usage() print string.join(map(str, range(low, high, step))) -- -- I won't rest till it's the best ... Programmer, Linux Scalability Paul Jackson 1.650.933.1373 From jimd at vega.starshine.org Wed Mar 27 13:41:29 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 27 Mar 2002 18:41:29 GMT Subject: Python Web Programming Book? References: Message-ID: In article , Alexandre Fayolle wrote: > Simon Brunning wrote: >> Steve Holden's "Python Web Programming" sounds *exactly* right for >> you - it covers web programming (both client & server side) *and* >> database programming in some depth. > +1 ! Excellent book. > Alexandre Fayolle I'm guessing that you're preparing to teach classes in Python Web Programming. Based on that assumption: Yes. I would skip Lutz and stick with Steve Holden (who has brief but well written introductory chapters before focusing on web programming. Steve's book also has some coverage of Zope, though you might add _The_Zope_Book_ from No Starch Press. Echoing another response to this message I'd recommend that students also get Beazeley's Essential Reference. From jon+usenet at unequivocal.co.uk Wed Mar 27 06:34:38 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Wed, 27 Mar 2002 11:34:38 -0000 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> Message-ID: In article , A.M. Kuchling wrote: > Quixote turns the idea of templating on its head and embeds HTML in > Python code. Section 4 of > http://www.amk.ca/python/writing/mx-architecture/ talks about why this > turns out to be a really good idea. ... and 'jonpy' avoids the issue entirely by neither embedding Python in HTML or HTML in Python. Its templating system embeds *no code of any sort* in the HTML and this turns out to be completely super ;-). See http://jonpy.sourceforge.net/wt-examples.html#templatecode for examples. This is especially useful when you have different people generating the HTML and the code (as it almost always the case). The designer is much less likely to mangle the 'significant' parts of the HTML files, and even if they do, it's a matter of seconds to fix. Additionally, when the customer says "actually, we don't like the style of the site, we want it changed" and you get sent a whole bunch of new code-less HTML files, with a PHP-style code-in-HTML you pretty much have to reimplement the entire site from scratch, whereas with this system you just add back in the section markers and the code (which was in separate files anyway) does not usually need to be changed at all. Cheers Jon From i.linkweiler at gmx.de Tue Mar 26 19:04:56 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Wed, 27 Mar 2002 01:04:56 +0100 Subject: Python vs. C/C++/Java: quantitative data ? References: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> Message-ID: <3CA10CA8.DFF48898@gmx.de> I?m writing a diploma paper on rapid prototyping and python at education. I am interested in your experiences with python, too, including the time you needed to learn python. - Do YOU think, it is more easy to learn python than perl, java or C++ or ..... ? - What do you think about the syntax of Python? Is it easy to use, or do you have any problems with it? - Is here anybody who learned Python as first language? - Where do you see disadvantages of Python? Ingo From eric.brunel at pragmadev.com Mon Mar 11 05:20:07 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 11 Mar 2002 10:20:07 +0000 Subject: Python on Windows soon forbidden by Micro$oft? Message-ID: Hi all, Found the following link on comp.lang.tcl. A bit long, but worth reading... http://groups.google.com/groups?hl=en&selm=3B40A4A7.6E39BD%40brad-aisa.com&rnum=1 Regards, - eric - From loewis at informatik.hu-berlin.de Fri Mar 1 08:53:31 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 01 Mar 2002 14:53:31 +0100 Subject: Trouble importing / using a custom text codec References: <9ac02e81.0202280152.5bb1bf25@posting.google.com> <9ac02e81.0203010508.4ebccd75@posting.google.com> Message-ID: jhorneman at pobox.com (Jurie Horneman) writes: > What is a .pth file? See http://www.python.org/doc/current/lib/module-site.html Regards, Martin From rstephens at vectron.com Fri Mar 1 09:14:48 2002 From: rstephens at vectron.com (Ron Stephens) Date: 1 Mar 2002 06:14:48 -0800 Subject: Black Adder and PyQt Message-ID: I am thinking of buying a "home" license of Black Adder, to use for making GUI's for Python programs to be used on Linux+KDE and also perhaps for the new Sharp Zaurus. Does anyone have any experience with Black Adder that they can share? One of my main reasons for wanting Black Adder is to use the GUI builder, so I am particualrly interested in opinions about that aspect of Black Adder, but I am also interested in other aspects as well. One question I have concerns licensing. If I buy the "home" version, could I still share my programs as GPL'ed open source, or would that require me to buy the "professional" license, which is much more expensive? In other words, my programs would never be used in any commercial way but I might want to post them as open source, free software. I know Black Adder is still in beta, but is it stable enoough to use already? I suppose I should ask how it compares to PythonWare amd WingIDE, but I kind of favor the PyQt toolkit becuase it will hopefully work well on the Sharp Zaurus as well as the KDE desktop. From fredrik at pythonware.com Mon Mar 11 12:59:25 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Mar 2002 17:59:25 GMT Subject: lambda question References: Message-ID: <1g6j8.24364$n4.4758442@newsc.telia.net> lambda questionAlves, Carlos Alberto wrote: > first code: > f='x**3+2*x' > list=[0,1,2,0] > map(lambda x:eval(f),list) > > second code: > > def exe1(f,list): > return map(lambda x:eval(f),list) > > Can someone explain to me why the first code works while > second doesn't. because you're running under Python 2.1 or earlier, and haven't read up on Python's LGB scoping rules? if so, the following should do the trick: def exe1(f,list): return map(lambda x,list=list:eval(f),list) From brian at sweetapp.com Wed Mar 6 21:21:14 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 6 Mar 2002 18:21:14 -0800 Subject: getting number of arguments of builtin/C func In-Reply-To: Message-ID: <007701c1c57e$c168b320$445d4540@Dell2> Chris Liechti wrote: > i know these two: > >>>numArgs = func.func_code.co_argcount > >>>func.func_code.co_varnames[:numArgs] > > >>>apply(inspect.formatargspec, inspect.getargspec(f)) > > both only work for python functions, but i would like to know the > number of arguments a function takes regardles if its a type, builtin > or python func. There is no general way to determine the number of arguments that a C-implemented function requires. > any ideas appart from calling with zero args and parsing the > exception string (scanning: "TypeError: f() takes exactly 2 arguments > (0 given)") ... That would you do if you encountered an exception like this: "TypeError: open() takes at least 1 argument (0 given)"? And what if calling the function without arguments does something bad? Cheers, Brian From huaiyu at gauss.almadan.ibm.com Mon Mar 4 17:02:14 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 4 Mar 2002 22:02:14 +0000 (UTC) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: On Mon, 04 Mar 2002 03:41:07 -0500, Tim Peters wrote: >On boxes with this problem, I'm also curious what > >import math >print math.pow(1e-200, 2.0) > >does under 2.1. Python 2.2 (#1, Feb 28 2002, 16:44:48) [GCC 2.95.2 19991024 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> print math.pow(1e-200, 2.0) 0.0 >>> 1e-200**2.0 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') >>> 1e-200**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') Python 2.1 (#1, Oct 2 2001, 15:35:43) [GCC 2.95.2 19991024 (release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import math >>> print math.pow(1e-200, 2.0) 0.0 >>> 1e-200**2.0 0.0 >>> 1e-200**2 0.0 Huaiyu From nospam at bigfoot.com Tue Mar 5 16:29:58 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 5 Mar 2002 22:29:58 +0100 Subject: Updating Python...Newbie alert! References: Message-ID: Or you can replace "make install" by "make altinstall" if you want to keep Python 1.5.2 as default python (perhaps you got compiled extensions like database or GUI adaptors). Then you need to run your new python distro with "python2.2" command. "Chris Liechti" a ?crit dans le message news: Xns91C8E16569949cliechtigmxnet at 62.2.16.82... > "Mr.Lee" wrote in news:n3ah8.112697 > $Hu6.28510292 at typhoon.neo.rr.com: > > Hi all, > > Being quite new to Linux, I am having a bit of a problem > > when it comes to updating my installed version of Python(1.5.2) to > > the version that I have now(2.2). > > My problem is that I compiled Python in the directory that > > I downloaded and now I don't know where to put all of the files > > that were generated! It works, I ran the tests and it all came out > > fine, but I just don't know where to put the files for maximum > > efficiency. > > usualy one does "./configure;make;make install" and the "make > install" places the files where they belong (in subdirectories of > /usr/local/ usualy) > > chris > > -- > Chris > From greg at cosc.canterbury.ac.nz Thu Mar 7 21:08:12 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 08 Mar 2002 15:08:12 +1300 Subject: how to give an object as argument for a method References: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> Message-ID: <3C881D0C.8CBD1CB@cosc.canterbury.ac.nz> Marco Herrn wrote: > > If a have a method with the defininion 'f(self)' I call this method only > with 'f()'. So the declaration doesn't look the same like the call. There are times where you *do* explicitly pass in self, mainly when calling inherited methods, e.g. class C(D): def __init__(self): ... D.__init__(self) # Initialise my base class ... So if "self" were implicit, then *this* would be a case where the call didn't match the definition. You can't win! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From cmbardon at engmail.uwaterloo.ca Thu Mar 21 02:21:31 2002 From: cmbardon at engmail.uwaterloo.ca (Chris Bardon) Date: 20 Mar 2002 23:21:31 -0800 Subject: Problem with Python Extensions Message-ID: <5c2b81.0203202321.50bf8908@posting.google.com> If anyone could help me with this problem it would be greatly appreciated: I'm trying to write a simple Python extension for use in Truespace 4.3. At this point, I'm just trying to assess what can be done with it, so I'd like to be able to start with an example that just returns a value. The problem is, my extension crashes truespace whenever I try to import it. I've created the dll using MS Visual C++ 6 and Python 1.5-I've also included the source for the dll below (like I said-starting simple). When I try to import this into truspace's python interface (import CommExt), the script causes an invalid page exception in MFC42.DLL. I'm linking this against python15.lib, as obtained from python.org. If anyone has had a similar problem, or can see from my source what my problem might be, your help would be greatly appreciated. Thanks, Chris Bardon //CommExt.cpp //Another stab at making a truespace extension #include "Python.h" PyObject* comm(PyObject *self, PyObject *args); static PyMethodDef commMethods[] = { {"comm", comm, 1}, {NULL, NULL} /* Sentinel */ }; static PyObject *CommExtError; extern "C"__declspec(dllexport) void initCommExt() { Py_InitModule("CommExt", commMethods); //this is the line that crashes TS! } PyObject* comm(PyObject *self, PyObject *args) { int result=42; return Py_BuildValue("i", result); } From shalehperry at attbi.com Fri Mar 1 15:06:54 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 01 Mar 2002 12:06:54 -0800 (PST) Subject: __abs(self)__? In-Reply-To: Message-ID: On 01-Mar-2002 Mike Carifio wrote: > I'm reading about special method names. __abs__(self), which maps to the > abs() method seems unneccessary(?). > So: > > class ExampleNumber: > def __init__(self, initializer): > self.value = initializer > def __abs__(self): > return abs(self.value) > >>>> x = ExampleNumber(-1) >>>> x.abs() > 1 > > seems no different from: > > class ExampleNumber: > def __init__(self, initializer): > self.value = initializer > def abs(self): # name isn't special? > return abs(self.value) > > abs is a builtin function, so why do I need a special name for a function? > I'm missing something... > the __foo__ method names are special because you do not call them directly (usually) rather they are triggered when a request is made. __abs__() causes the object to return a value that represents the absolute value of the object's data, whatever that means. abs(obj) translates into obj.__abs__(). This is just like 'print obj' calling obj.__str__() or 'obj[i]' calling obj.__getitem__(i). From tim.one at comcast.net Sun Mar 10 16:17:01 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 10 Mar 2002 16:17:01 -0500 Subject: How to disable assert statements inside a module? In-Reply-To: Message-ID: [Pearu Peterson] > Is there a way to disable all assert statements inside a module, > and without calling python with -O switch? [Martin v. Loewis] > You can set __debug__ to 0 on the module level; this will disable > assert statements inside this module. Note that assignment to __debug__ was deprecated in 2.1: SyntaxWarning: can not assign to __debug__ and removed in 2.2: SyntaxError: can not assign to __debug__ -O is the only way left. Guido often writes code under the control of an explicit "debug" vrbl instead. A more flexible way to control asserts would be (IMO) prime PEP material (as a heavy assert user myself, I sympathize with Pearu's dilemma -- "all or nothing everywhere" is too crude for large projects with many subsystems). From wealthychef at mac.com Fri Mar 15 13:23:42 2002 From: wealthychef at mac.com (Richard Cook) Date: Fri, 15 Mar 2002 10:23:42 -0800 Subject: readline() blocks after select() says there's data?? In-Reply-To: <15506.10262.578727.665781@12-248-41-177.client.attbi.com> References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: That's a good point. My actual problem turns out that I had the first two parameters to select.select() reversed, though. :-| At 10:57 AM -0600 3/15/02, Skip Montanaro wrote: > Rich> I don't really need select to block. I just want it to be > Rich> accurate. If it returns a file object in the list of things which > Rich> are available, why should then readline() block on it? > >Remember that select() is lower level than readline(). As someone else >pointed out, select() may return because there is data available, but it >makes no promises about what that data is. Calling readline() may then hang >waiting for other conditions (presence of a newline in the input, for >example). > >-- >Skip Montanaro (skip at pobox.com - http://www.mojam.com/) -- From john at ecsc.co.uk Wed Mar 27 04:16:11 2002 From: john at ecsc.co.uk (John Leach) Date: Wed, 27 Mar 2002 09:16:11 +0000 (UTC) Subject: os.fchown, avoiding a race condition Message-ID: Hi, I haven't managed to find any reference in python (any version) to the unix system call fchown (SVr4, SVID, POSIX, X/OPEN). There is chown, but not fchown. I'd like to create a file as a different user but would like to avoid a race condition by chowning via the file descriptor, but it seems I cannot. Does anyone know why this seems to be missing? Any plans for it to appear? Any other way I can do this? Thanks in advance. -John. -- http://people.ecsc.co.uk/~john GPG: B89C D450 5B2C 74D8 58FB A360 9B06 B5C2 26F0 3047 From skip at pobox.com Tue Mar 19 09:15:04 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 19 Mar 2002 08:15:04 -0600 Subject: Pure python alternative to mx.DateTime? In-Reply-To: References: Message-ID: <15511.18408.245358.647371@12-248-41-177.client.attbi.com> Lutz> Unfortunately I'm in need of some simple time and date Lutz> calculations (ISO-time, how many days from now, weekdays, etc.). Lutz> Is there any alternative to mx without inventing the wheel for the Lutz> second time and programming it by myself? There's Jeff Bauer's NormalDate module: http://starship.python.net/crew/jbauer/normaldate/index.html -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From nospam at bigfoot.com Fri Mar 15 16:05:04 2002 From: nospam at bigfoot.com (Gillou) Date: Fri, 15 Mar 2002 22:05:04 +0100 Subject: Process to process synchronization (unix) Message-ID: Hi, I have a Zope application and another running process (in python too). I need to transmit data and signal (hey ! data available, do your job !) in an asynchronous way from the Zope app (in an external method) to the python running process (that runs for another user). The other process waits for the signal, takes given data, does the jobs and waits further signal (...) I'm 99.9% newbie in process to process communication. What packages are helpful for this ? Any examples ? Thanks in advance. --Gillou From bokr at oz.net Thu Mar 7 17:48:08 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Mar 2002 22:48:08 GMT Subject: regular expression for nested matching braces References: Message-ID: On Thu, 07 Mar 2002 12:13:24 -0500, Tim Peters wrote: >[Piet van Oostrum] >> ... >> In fact python's regular expressions are a little bit stronger than >> the theoretical ones because of the allowed \n constructs, but still >> can't count. > >If you're into this kind of thing, doing a google search on > > "regular expression" "NP complete" > >turns up several linear-time reductions transforming NP-complete problems >into matching-with-backreferences problems. IOW, adding backreferences to >theoretical regexps turns the regexp matching problem from polynomial time >into "almost certainly" exponential time. In that sense, backreferences add >enormous power. But counting is *really* hard . > With some limitations (use triple quotes for less limitation on input), how about: >>> s = "A line of text with {multiple and {nested} braces} to {confuse} re!" >>> sl = eval('["'+'"], "'.join('", ["'.join(s.split('{')).split('}'))+'"]') >>> sl ['A line of text with ', ['multiple and ', ['nested'], ' braces'], ' to ', ['confuse'], ' re!'] then walk the tree as desired. Regards, Bengt Richter From ben at wintersun.org Mon Mar 25 17:43:36 2002 From: ben at wintersun.org (Ben Caradoc-Davies) Date: Mon, 25 Mar 2002 22:43:36 GMT Subject: Indentation problem References: Message-ID: On Mon, 25 Mar 2002 14:16:49 +0100, Gilles Diribarne wrote: > 1/ Because it's almost impossible to paste python code with ident = n > spaces to another code with indent = m spaces "Four was the number of their indenting, and the number of their indenting was four." -- The Book of Armaments (and the Python Style Guide). Use automated tools to migrate all your code to four-space indenting. All coders should conform to http://www.python.org/doc/essays/styleguide.html I was once a two-space indenter, but now I'm Saved. > This kind of examples occurs more and more and you can indent the code > by hand when it's 10 lines of codes, but not 1000 code lines. > It prevents the re-use of code pieces. Ack! That's not reuse. That's insanity! Write once and reuse with import. The Great Satan of software development is code duplication, because all your bugs are duplicated, as is the work for any redesign. You are doing something wrong. Abstraction is your only tool to control complexity (other than avoiding complexity in the first place). > 2/ Programmers wants independence: some wants to manage building blocks > with spaces, other with tabs, some wants length = 4 with tabs. > I would like to use my own programming style! But, my code risks to be > not supported by others. Your job "risks to be not supported by" your employer. Programmers who want independence must expect to support their own code, alone. Frankly, one of the biggest problems preventing code reuse is the mess some programmers make: other programmers would rather rewrite the code than try to understand or debug the exisiting code. A consistent style and complete, correct, in-code documentation (literate programming) helps to encourage reuse. There's plenty of damage to be done at the higher structural level design/API without stooping to micro-level style inconsistency. > 3/ A large number of programming language use this. C, PERL, Ruby, ... > Why not Python? Because of crimes committed against legibility by those other languages. -- Ben Caradoc-Davies http://wintersun.org/ From s.schwarzer at ndh.net Sun Mar 31 13:14:07 2002 From: s.schwarzer at ndh.net (Stefan Schwarzer) Date: Sun, 31 Mar 2002 19:14:07 +0100 Subject: PEP 285: Adding a bool type References: Message-ID: <3CA751EF.10F25F2D@ndh.net> > I offer the following PEP for review by the community. If it receives > a favorable response, it will be implemented in Python 2.3. > [...] > Review > > Dear reviewers: > > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. I'm -1 on this PEP. To summarize: The problem I have with this proposal is that it does a half-hearted job (and can only do so because of backward compatibility issues). I think it's a bad deal to get > >>> a > b > True > >>> but on the other hand have to keep in mind subtle interactions between bools and ints. For example, I consider it very unintutive that "True == 1" should by true but "True == 2" should be false. I understand well that this is for backward compatibility, i. e. not breaking code that uses "boolean" results to calculate something together with numbers. There are, as pointed out, too much cases where bool/int interactions lead to surprises because the behaviour of the bool type does not live up to its abstract concept that it should have. This is confusing; in effect one would have to think _more_ whether the code does what is should. If one deals with ints _explicitly_, calculation outcomes are much easier to see. Regarding special uses such as RPC and databases it would suffice to add a "boolean" module to the standard library. This would offer a standard way to handle a boolean type for these special purposes, wouldn't it? So, in my opinion the disadvantages strongly outweigh the benefits of the PEP. Additionally, the PEP brings some more design ambiguity which I dislike. Should my function/method return 0, None, - or False, in a specific case? Having to make this decision reminds me at the choice of defining an attribute as "protected" vs. "private", or using "virtual" or not, in C++. Sometimes, I would like to postpone decisions until later. This thinking is in line with the earlier post in which someone said that "it's not unusual for an integer meaning true or false to become a 'level' variable". _If_ the PEP is accepted (which I do not hope), I would prefer ... > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) str(True) should be "1" (because of the arguments of Marc-Andre Lemburg; some applications actually might make use of this representation). > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). "True" and "False" > Most other details of the proposal are pretty much forced by the > backwards compatibility requirement; e.g. True == 1 and > True+1 == 2 must hold, else reams of existing code would break. > > Minor additional issues: > > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. Not to me, despite its convenience. As the name suggests, isleap should return a bool. But then, it shouldn't be added to an int. A solution to resolve this would be to change the name of isleap. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. operator.truth(x) should return a bool. Stefan From peter at engcorp.com Thu Mar 14 23:54:47 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 14 Mar 2002 23:54:47 -0500 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: <3C917E97.E615E316@engcorp.com> Jonathan Gardner wrote: > > I have a free software program (http://sf.net/projects/bttotalcontrol/) and > I am having great difficulty writing an installation script for windows. > > I don't want to use distutils because I am not writing a module - but an > entire distribution with images, data files, and executable programs. I > would like to put icons on the desktop and stuff in the start menu as well. > > I am at a major disadvantage because I don't have access to a windows > machine, and so I can't test anything directly. However, I do have a few > people who actively test for the project at home. > > Anyone have any suggestions on where I should go? Anyone can help me out > here? Why not find and use one of the several free installer programs, rather than trying to write something from scratch yourself? For example, try looking at google with "free windows installers" and follow the first link you find. -Peter From SBrunning at trisystems.co.uk Tue Mar 26 08:42:20 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 26 Mar 2002 13:42:20 -0000 Subject: beginner Message-ID: <31575A892FF6D1118F5800600846864DCBCEAB@intrepid> > From: Ken?z Attila [SMTP:attila-kenez at vnet.hu] > I am a beginner using Python and I have two problems. > > I would like two write an installer program in Python, that works on any > computer with Wondow OS, so that is not nesseccary to have Python > interpreter on it. Is there a simple (or a difficult) way to do it? I use a combination of py2exe (), which builds an exe file from a Python script, and Inno setup (), which builds a setup for your new exe. There are alternatives to both of these, but they work for me. > The other question is about pyd files. I did not found any mention about > it > in the documentation. I want to access a database under SAP DB from > Python, > and for that I need to use the sapdb.pyd file. I tried to move it to a > directory in PATH and PYTHONPATH but the interpreter dropped an error at > the > import statement. How I have to use these kind of files? A plain old import should work if the pyd is in your PYTHONPATH. It would be useful to see the error message, but my first guess is that you have the wrong version of the pyd file - under windows, they are specific to a Python release. If you have Python 2.2, and the pyd was compiled for 2.1, it wouldn't work. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Tue Mar 26 07:56:37 2002 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Tue, 26 Mar 2002 13:56:37 +0100 Subject: forgetting state References: <98b6685d.0203231539.1459d00d@posting.google.com> Message-ID: Dale Strickland-Clark schrieb in Nachricht ... >If you're debugging a program and execution stops at some point, for >any reason, you don't want to have to completely leave your >development environment and restart it just so you can run from the >beginning again. > Exactly. But I always thought this sort of problem only crops up when I import module A into script B and then change module A and rerun script B. But now I had a script importing nothing at all. It stopped with an exception, I corrected the fault - and got the same exception, citing the old code which wasn't in the script any more! Looks as if the corrected script wasn't read at all - but even on Windows Python isn't a human too lazy to read a letter to the end (or so I thought). IDE was Pythonwin. Koczian --- Dr. Sibylle Koczian Universitaetsbibliothek , Abt. Naturwiss. D-86135 Augsburg Tel.: (0821) 598-2400, Fax : (0821) 598-2410 e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From kare at speech.kth.se Wed Mar 20 06:47:13 2002 From: kare at speech.kth.se (Kare Sjolander) Date: Wed, 20 Mar 2002 12:47:13 +0100 Subject: Q: Sound production with python? References: Message-ID: <3C9876C1.F08DF2C6@speech.kth.se> Using Snack (http://www.speech.kth.se/snack) you would use the following commands to generate a note sequence. from Tkinter import * from tkSnack import * root = Tkinter.Tk() initializeSnack(root) s = Sound() filt = Filter('generator', 440, 30000, 0.0, 'sine', 8000) def beep(freq): filt.configure(freq) s.play(filter=filt,blocking=1) beep(261.6) beep(293.7) beep(329.7) beep(349.3) This should get you started Kare "A.Newby" wrote: > Being a beginner fiddle player, as well as a beginner python programmer, I > want to write a little prog that trains the sense of pitch. > > How envisage it working is thus... > > It plays a simple 4 note melody, then repeats the melody with one of the > notes (selected randomly) slightly off pitch ... say by 20% or 10% or 5%. > The user then has to detect which note was off. > > What modules and commands should I use to generate this sounds? What's the > best way to go about it? > > -- > cdewin at dingoblue.net.au From peter at engcorp.com Fri Mar 29 17:10:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 17:10:04 -0500 Subject: [XP] Code Complete: Things were Scary Back Then References: <3CA4E5F5.70B5A7E5@engcorp.com> Message-ID: <3CA4E63C.300E9DC7@engcorp.com> Oops.. sorry, I didn't notice David had warped us away from comp.software.extreme-programming... From fperez528 at yahoo.com Mon Mar 18 16:29:34 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 18 Mar 2002 21:29:34 +0000 Subject: ANN: IPython 0.2.8 Message-ID: Announcing an update to IPython, an enhanced interactive Python shell. WHERE: http://www-hep.colorado.edu/~fperez/ipython NEW since last public release (ChangeLog included with full details): - Full Emacs integration. Now IPython can be used both in Emacs shell/term buffers and also as your Python interpreter (with C-c !). Instructions on the necessary code for your .emacs file provided. - Interface to the Gnuplot plotting system. This can be used as a template for interfacing with any other program which one can communicate with (via pipes, sockets, whatever). - Many improvements to the embedding facilities. It's now possible to have nested copies of IPython running (such as debugging code with embedded IPython inside IPython itself). Global and local locks for the embedded instances provided to control them better. - User controllable prompt system. Particularly useful for using IPython as an embedded interpreter for other code. - Improved macro system for automatically re-executing many lines of previous input. - Small updates for better behavior under Python 2.2 (only 2.1 required) - Improved manual, now @magic system is fully documented. - Simplified Windows installation. - Better control for running other programs inside IPython via @run. - New -upgrade command line option for old users to update their .ipython/ directory automatically. - Improvements to auto-completion code. Also made readline an option (not using it disables completion, of course). - New paging system (for viewing long strings and files) is now OS independent. - Many small bugfixes. WHAT is IPython? (this is just for context. See the webpage for full details). IPython tries to: 1. Provide an interactive interpreter superior to Python's default. IPython has many features for object introspection, shell access, and its own special command system for adding functionality when working interactively. 2. Serve as an embeddable, ready to use interpreter for your own programs. IPython can be started with a single call from inside another program, providing access to the current namespace. This can be very useful both for debugging purposes and for situations where a blend of batch-processing and interactive exploration are needed. 3. Offer a flexible framework which can be used as the base environment for other systems with Python as the underlying language. Specifically scientific environments like Mathematica, IDL and Matlab inspired its design, but similar ideas can be useful in many fields. Portability: Linux (and other unices, including Mac OSX), Windows XP. Should run fine on all WinNT, and probably also on Win9x (I can't test that). Python version: requires 2.1 or newer. License: LGPL (a few files from third parties carry MIT licenses). Cheers, Fernando Perez. From sam_collett at lycos.co.uk Fri Mar 8 06:51:06 2002 From: sam_collett at lycos.co.uk (Sam Collett) Date: 8 Mar 2002 03:51:06 -0800 Subject: Python Classes References: <2030665d.0203070226.46b39af4@posting.google.com> Message-ID: <2030665d.0203080351.1682b6fc@posting.google.com> I have modified the code as follows (may wrap): class clFile: def __init__(self,path_to_file): self.f = path_to_file self.exists = os.path.exists(self.f) if self.exists == 0: return None def getFileName(self,blnExt=None): """ blnExt = show file extension (put in value other than 0 or None to show the extension) """ if blnExt: result = os.path.basename(self.f) else: result = os.path.splitext(os.path.basename(self.f))[0] return result def getFileExt(self): result = os.path.splitext(self.f)[1] return result def getDir(self): result = os.path.dirname(self.f) return result def getSize(self): size = int(os.path.getsize(self.f)) if size < 3072: #<3kb return "%db" % size elif size < 2097152: #<2mb return "%.2fkb" % (size/1024.) else: #>2mb return "%.2fmb" % (size/1048576.) def modified(self): import time return time.strftime('%d/%m/%Y; %I:%M%p',time.gmtime(os.path.getmtime(self.f))) What I want to do is if the file does not exist to return nothing or an error. I thought the following code would work, but it didn't. How could I get it to work? self.exists = os.path.exists(self.f) if self.exists == 0: return None Martin Franklin wrote in message news:... > Sam Collett wrote: > > > I am quite new to Python and have no experience with classes. I have > > tried a file class, but I am not sure how to get it to work: > > > > class clFile(file): > > > > def getFileName(blnExt=None): > > """ > > file = path to file > > blnExt = show file extension (put in value other than 0 or > > None to show the extension) > > """ > > import os > > if blnExt: > > result = os.path.basename(file) > > else: > > result = os.path.splitext(os.path.basename(file))[0] > > del os > > return result > > > > def getFileExt(): > > import os.path > > result = os.path.splitext(file)[1] > > del os > > return result > > > > def getDir(): > > import os > > result = os.path.dirname(file) > > del os > > return result > > > > I wondered if there was a way to do something like the following: > > > > myfile = clFile("c:\\somedir\\dir with spaces\\foo.txt") > > myfile.getDir would return c:\somedir\dir with spaces\ > > myfile.getFileExt would return .txt > > myfile.getFileName would return foo.txt or foo > > Ok try this to get you working: > import os # do this at the top.... > > class clFile: > def __init__(self, file): > # constructor called when you create an instance (object) of this > class > self.file=file > # self.file instance variable bound to file object > #(in this case the file name passed to the class constructor) > > def getFileName(self, blnExt=None): > # return filename with or without the extension.. > if blnExt: > result = os.path.basename(self.file) > else: > result = os.path.splitext(os.path.basename(self.file))[0] > return result > > def getFileExt(self): > # return file extension > return os.path.splitext(self.file)[1] > > > def getDir(self): > # return the file basname (directory/folder) > return os.path.dirname(self.file) > > > > # now for testing..... > if __name__=='__main__': > clf=clFile('/home/bpse/crapola.bot') # create an instance of clFile > > # call it's methods.... > > print clf.getFileExt() > print clf.getFileName(blnExt=1) > print clf.getFileName() > print clf.getDir() > > > > > You should really work your way through the tutorial (at least the classes > bit) on:- > http://www.python.org/doc/current/tut/tut.html From mertz at gnosis.cx Sun Mar 17 15:08:08 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Sun, 17 Mar 2002 15:08:08 -0500 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: | danb_83 at yahoo.com (Dan Bishop) wrote: |> Even for complex numbers, for which "less than or greater than" is |> meaningless? Just van Rossum wrote previously: |It doesn't have that meaning for me anymore, it simple means "not equal" |to me. It is an abstract symbol. I really don't believe we can discuss |this on any other level than "I prefer x because I'm used to it"... In the end, Just is right. People get used to different things. Nonetheless, I think of the natural language semantics of the symbols--or maybe better "insinuations"--prefers '<>' to '!='. The (good) one suggests "is greater than or less than (but not equal to)". I know that not everything is technically in an order relation, but it still "makes sense" at a first approximation. The (bad) one looks like some odd sort of augmented assignment. "Hmmm... assign, what? The negation of the right side to the left side?! The LHS negated with the RHS?!" But then, I wrote virtually the same thing a few months ago, in almost the same thread. And I probably will again in six months. And despite my feeling on the "principle of least surprise", I don't have any real trouble reading code that uses '!='. -- _/_/_/ 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 tejarex at yahoo.com Fri Mar 8 09:45:35 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 08 Mar 2002 14:45:35 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> Message-ID: "Bengt Richter" wrote in message news:a69lml$b2v$0 at 216.39.172.122... > On Fri, 08 Mar 2002 15:54:29 +1300, Greg Ewing wrote: > >Even something like q'delim' doesn't allow you to > >easily use completely arbitrary text, because you > >still have to pick *some* string that doesn't occur > >in the text. Although you don't have to modify the > >text, you do have to inspect it in order to choose > >a suitable delimiter. > Unless you choose one with vanishingly small probability > of being included, like a generated guid. This was Guido's intention when he choose triple quotes and I think he did excellently well. I don't believe I had even seen """ and quite possibly not ''' ever before learning Python. I do know that I found """ to be quite jarring, as if I have never seen it before. > A smart editor could do this for you. A smart editor could also scan for triple quotes in pasted text and select one that was not found as the enclosing quotes and do the octal quoting fixup if both were. Terry J. Reedy From wlashell at outsourcefinancial.com Mon Mar 4 11:57:06 2002 From: wlashell at outsourcefinancial.com (Will LaShell) Date: 04 Mar 2002 09:57:06 -0700 Subject: Black Adder and PyQt In-Reply-To: <3C82F708.70303@mishre.com> References: <3C80B1E3.575761B7@river-bank.demon.co.uk> <3C82F708.70303@mishre.com> Message-ID: <1015261027.7978.5.camel@lyric.ofsloans.com> > > Anyone out there have recommendations on a good IDE with form designer, > that's not Beta? Nothing too fancy...I've tried wxDesigner, but > couldn't figure out that spacer stuff for the life of me. I don't know if you have considered this, but a really excellent tool for gui building is glade. You save the gui into a .glade file and use pylibglade to load it into your program. It allows a really interesting seperation between your processing code and the gui code. Obviously you still need a good editor, and they aren't integrated, but you were asking for options, and this is a pretty decent one. We use this system here at work. > > Wayne > > -- > Wayne Pierce > web: http://www.mishre.com > email: wayne at mishre.com > > "What you need to know." From martin at v.loewis.de Fri Mar 29 13:13:53 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 29 Mar 2002 19:13:53 +0100 Subject: Executing a specific function. In-Reply-To: <3CA4A04A.F37DD1D9@amtec.com> References: <3CA4A04A.F37DD1D9@amtec.com> Message-ID: Michael Saunders writes: > I had seen this API but it requires a "callable". Isn't a callable a > PyObject pointer to a callable function? Correct. It could be anything callable, though: a class, a type, an instance with an __call__ method, any other object with a tp_call slot. > How do I build the "callable". All I have is a Python file, > "myfile.py" and the name of a function to call "myPthonFunction". Always think of how to write things in Python, then translate to C. Everything you can do in Python can be (more or less) literally translated. In the specific case, I'd guess you'll do import myfile result = myfile.myPythonFunction() Translating this to C, you'll do: module = PyImport_Import("myfile"); result = PyObject_CallMethod(module, "myPythonFunction", ""); Don't forget to check for exceptions! If you would not have PyObject_CallMethod, you would do function = PyObject_GetAttrString(module, "myPythonFunction"); result = PyObject_CallFunction(function, ""); In C, you can do things that you can't, directly, do from Python. E.g. if you can't guarantee that myfile is on sys.path, there is no need to add it to sys.path - just use one of the functions that create modules from source code. HTH, Martin From paul at boddie.net Wed Mar 13 06:31:03 2002 From: paul at boddie.net (Paul Boddie) Date: 13 Mar 2002 03:31:03 -0800 Subject: Converting relative URLs to absolute References: Message-ID: <23891c90.0203130331.6f030f5b@posting.google.com> Fernando P?rez wrote in message news:... > James A Roush wrote: > > > Does anyone have any code that, given that absolute URL of a web page, can > > convert all the relative URLs on that page to their absolute equivalent? > > Assuming absolute is a string and relative_list a list of strings, the > followinng comes to mind: > > [absolute+'/'+relative for relative in relative_list] > > Maybe you wanted something fancier, don't know. I suppose it would be nicer or more appropriate to deal with "back references" as well as being able to detect "base" elements. For example, given the following "base"... http://www.python.org/invented/framework/demo/ ...and the following URLs... moreinfo.html docs.html ../apps.html ../../stuff.html /index.html http://www.zope.org ...one would want to remove certain parts of the "base" before concatenating the relative URLs to it. Thus, we would produce these absolute URLs: http://www.python.org/invented/framework/demo/moreinfo.html http://www.python.org/invented/framework/demo/docs.html http://www.python.org/invented/framework/apps.html http://www.python.org/invented/stuff.html http://www.python.org/index.html http://www.zope.org I'm not so sure that urllib supports such operations, at least not in any version of it that I have (from Python 2.0 or 2.1). Instead, there's some fairly low-level split operations which aren't especially useful in this case. In addition, you might need to use some parser to get hold of any "base" elements in the HTML. I've written some page-mining tools which help with these kinds of activities, and I suppose I should get round to releasing them at some point. Let me know if you're interested! Paul From mhammond at skippinet.com.au Tue Mar 19 01:33:08 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 19 Mar 2002 06:33:08 GMT Subject: Serial Ports References: <3c96c220$1_1@news.iprimus.com.au> Message-ID: <3C96DBB0.1070402@skippinet.com.au> Jamie Carl wrote: > Hi all, > > I'm still fairly new to Python so forgive me. I'm hoping someone can > point in the right direction regarding how I would go about accessing a > serial com port from Python. I'd like to do it mainly under Linux, but > hopefully it will work under windows aswell. > > Is it possible? Can someone point me to some documentation or code samples? > http://www.google.com/search?q=python+serial+port Mark. From robin at jessikat.fsnet.co.uk Mon Mar 4 07:35:04 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 4 Mar 2002 12:35:04 +0000 Subject: Gentle reminder for Python UK Conference, April 4 & 5. References: <1015238517.16564.0.nnrp-01.c1c3e191@news.demon.co.uk> Message-ID: <1CjMnIA4n2g8EwPZ@jessikat.demon.co.uk> In article <1015238517.16564.0.nnrp-01.c1c3e191 at news.demon.co.uk>, Paul Brian writes ..... >If that does not convince you, try advice from Mrs Doyle (Father Ted and the >Inland Revenue) : > >"Ah, go on, go on, go on, go on, go on, go on, go on, go on" > ..... this must be ironic as apparently the number of tax non replies has increased by some significant fraction and this is the most despised ad campaign of 2001. -Anarchic-ly yrs- Robin Becker From m.andrzejewski at dmz.com.pl Mon Mar 4 06:28:17 2002 From: m.andrzejewski at dmz.com.pl (marcin andrzejewski) Date: Mon, 4 Mar 2002 12:28:17 +0100 Subject: problem with locale Message-ID: everything works fine in IDLE, but when running as script, i 've got following error: import locale locale.setlocale(locale.LC_ALL, '') a= locale.format ('%.2f',-100000.236,1) Traceback (most recent call last): File "locale.py", line 1, in ? import locale File "locale.py", line 2, in ? locale.setlocale(locale.LC_ALL, '') AttributeError: 'module' object has no attribute 'setlocale' >Exit code: 1 what's wrong ? -- marcin andrzejewski m.andrzejewski at dmz.com.pl keson at post.pl From kdahlhaus at yahoo.com Thu Mar 28 11:57:26 2002 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 28 Mar 2002 08:57:26 -0800 Subject: The Python Way References: Message-ID: <283adf56.0203280857.3cc75e37@posting.google.com> Tim Peters wrote in message > class XandY: > """A class to wrap x and y values. > followed by 50 lines of unit tests to verify proper operation of the trivial > methods. This kind of numbing excess is self-inflicted (for a meaning of > "self" broad enough to encompass one's employer ). Hey, that looks like java. But-it's-encapsulated. From sjmachin at lexicon.net Wed Mar 27 07:23:18 2002 From: sjmachin at lexicon.net (John Machin) Date: 27 Mar 2002 04:23:18 -0800 Subject: re.split and lookaheads References: Message-ID: Morus Walter wrote in message news:... > Hi, > > I'm trying to split a string into two parts using zero width record > boundaries. > This should be possible by using a regular expression which consists of a > lookahead only. Unfortunately python does not split my string. [snip] > If I use the same RE for searching, it matches as exepted: This is the case with *any* zero-width pattern (as at version 2.2) -- see examples below. You should raise a documentation enhancement request. >>> re.split(r"\b", "abc def ghi") ['abc def ghi'] >>> re.split(r"", "abc def ghi") ['abc def ghi'] >>> re.split(r"x*", "abc def ghi") ['abc def ghi'] >>> re.sub(r"\b", "z", "abc def ghi") 'zabcz zdefz zghiz' >>> re.sub(r"", "z", "abc def ghi") 'zazbzcz zdzezfz zgzhziz' >>> re.sub(r"x*", "z", "abc def ghi") 'zazbzcz zdzezfz zgzhziz' >>> From cliechti at gmx.net Tue Mar 19 20:41:54 2002 From: cliechti at gmx.net (Chris Liechti) Date: 20 Mar 2002 02:41:54 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) wrote in news:slrna9fkli.9ti.mlh at vier.idi.ntnu.no: > I know there are several solutions available for building > standalone binary executables from Python programs (Freeze, py2exe, > McMillan Installer, etc.) -- I just wondered if it would be > possible to add functionality like this to distutils? E.g. adding > some command (xdist, for executable, as opposed to the existing > bdist?)... as i understand py2exe it does exactly that. it adds a new target "py2exe" so that disutils have a new target name. i.e "python setup.py py2exe" generates the exe+dlls in the dist dir -- Chris From usenet at thinkspot.net Fri Mar 1 08:04:44 2002 From: usenet at thinkspot.net (Sheila King) Date: Fri, 01 Mar 2002 05:04:44 -0800 Subject: newbie lists and code examples for OOP. References: Message-ID: On Fri, 01 Mar 2002 09:34:03 -0000, "skoria" wrote in comp.lang.python in article : > > I'm trying to write a class where one function calls a method in the > same class. Right now I'm doing this with trial and error, and I don't > really understand where I need to put parentheses, use (self), etc. I > can't find any "functional" examples of object oriented programming on > any online tutorials, or any simple programs already written that can > be used as a good tool to figure out how to call functions within > classes in python, when to use self.* what internal functions (like > __init__) can be used for. Lots of theory on this, but no functional > examples. For one thing: A beginner's forum would be the Tutor mailing list: http://mail.python.org/mailman/listinfo/tutor A good reference I would recommend for the type of stuff you are asking about: Core Python Programming by Wesley Chun. When to use self: Do you want the method to be called in the following way: object.method() where the method is always called by an instance of the object? Or would you like to be able to call it like this: method() without having to necessarily have an object to use that method? if the former, use "self". If the latter, don't use "self". Hope this answers some of your questions. Join the Tutor list and ask some more. You will get some good answers. -- Sheila King http://www.thinkspot.net/sheila/ "When introducing your puppy to an adult cat, restrain the puppy, not the cat." -- Gwen Bailey, _The Perfect Puppy: How to Raise a Well-behaved Dog_ From amoustafa at pobox.com Tue Mar 19 02:24:15 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Mon, 18 Mar 2002 23:24:15 -0800 Subject: Java and Python References: Message-ID: <3C96E79F.4010802@pobox.com> Delaney, Timothy wrote: >>From: Ahmed Moustafa [mailto:amoustafa at pobox.com] >> >>1. Where can I find an unbiased comparison between Java and Python? >> > > Nowhere. The best place to look though is > > http://www.python.org/doc/Comparisons.html > > which has comparisons with various languages. I knew about those articles and I felt they were biased to Python. > > >>2. Will Python dominate? >> > > Of course! Actually, no language will ever dominate, and Java and Python are > not mutually exclusive (in fact, there is an implementation of Python which > runs on top of the Java VM and has full access to all java classes, etc ... > http://www.jython.org/. > > >>3. Who does support Python? >> > > What type of support are you talking about? If you want commercial support, > I think ActiveState gives it. If you are talking about who maintains and > enhances Python, that's the Python development team in general (but with a > lot of community involvement. I understand Microsystems supports Java. Who does play the same role for Python? > > If you are asking these questions to decide if you should learn Python, > don't bother - the answer is an unqualified "yes". Python is very easy to > learn, and will make it much easier to learn other languages. If you are > asking to decide if you should learn either Java or Python, the answer is > "no" - learn both. Then learn a few more languages. But Python is a great > language to start with. I know Java, actually, I am a Sun certified Java programmer. > > Tim Delaney > > Thanks a lot for your reply. -- Ahmed Moustafa From akuchlin at ute.mems-exchange.org Thu Mar 21 16:46:13 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 21 Mar 2002 21:46:13 GMT Subject: "Zope-certified Python Engineers" [was: Java and Python] References: Message-ID: In article , John J. Lee wrote: > [OT: A question I've asked many times and got no answer to is 'why has > nobody done self-consistent ranking for academic papers'? I fear the Have you seen CiteSeer, at http://citeseer.nj.nec.com/cs ? It crawls the Web for papers, and then assembles a graph of citations. --amk (www.amk.ca) You know, Doctor, you're quite the most infuriating man I've ever met. -- Jo, in "The Time Monster" From brian at sweetapp.com Thu Mar 28 12:37:07 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 28 Mar 2002 09:37:07 -0800 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! In-Reply-To: <3ca28aba$1@news.microsoft.com> Message-ID: <001d01c1d67f$2eb81090$445d4540@Dell2> Shiv wrote: > Huh! This is news to me. When did this happen? Hmm ... by the looks of it > and the way ActiveState seems to be neglecting things looks like there has > been some falling out between them ... But then I shouldn't be doing such > idle speculation here ... I don't think that there was a falling out. Here is what David Ascher said: http://mail.python.org/pipermail/python-dev/2001-December/019058.html I was laid-off from ActiveState at the same time as Mark (and a dozen other people) and it seemed pretty clear that the company was losing tones of money and had to get rid of some people in order to survive. There was one ActivePython developer and he was laid-off. I would imagine that Trent Mick, who was/is the Komodo project manager, is the only person working on ActivePython and I'm sure that he has lots of other responsibilities. I bet that after ActivePython 2.2 comes out, future releases will become available in a more timely fashion. Cheers, Brian From usenet at thinkspot.net Tue Mar 12 18:27:36 2002 From: usenet at thinkspot.net (Sheila King) Date: Tue, 12 Mar 2002 15:27:36 -0800 Subject: frustrated stupid newbie question References: Message-ID: [posted and mailed] On Tue, 12 Mar 2002 16:59:13 -0600, "Scott Kurland" wrote in comp.lang.python in article : > Why isn't this $%^*#$% program working? > #Searching for perfect numbers > > howhigh= input ("How high should I check?") > for number in range (1,howhigh): > factorsum = 0 > halfnumber=number/2 > for checking in range (1,halfnumber): > if number/checking == int (number/checking): > factorsum = factorsum + checking > if number == factorsum: > print number > What do you mean it isn't working? It ran without crashing when I tried it. Here is the output from a sample run: >>> How high should I check?50 10 >>> Are you expecting some other type of output? What are you expecting? > Flame away, I can't feel dumber than this. Oh, now what newsgroup mistreated you so, that you would expect such a thing? We don't do that here in comp.lang.python! -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From kp87 at lycos.com Fri Mar 8 06:08:51 2002 From: kp87 at lycos.com (kevin parks) Date: 8 Mar 2002 03:08:51 -0800 Subject: [OT] range() for unix shell References: <2adab837.0203071409.76588265@posting.google.com> <2adab837.0203071734.1a3bee80@posting.google.com> Message-ID: <5e8bd451.0203080308.6665d155@posting.google.com> Paul (see you on Csound from time to time!) see the useless python page: http://www.lowerstandard.com/python/uselesspython2.html From mac at magusdesigns.com Wed Mar 6 18:19:32 2002 From: mac at magusdesigns.com (99miles) Date: 6 Mar 2002 15:19:32 -0800 Subject: create zip archive Message-ID: hi- i am creating a zip file from a directory. it is working great, but the files in the subdirectories get put into the top level directory in the zip file. I want the directory structure to remain intact when i extract the zip file. How can I do this? Any ideas? thanks a lot- Mac I am using this code, currently: for name in glob.glob("mypath/*"): if os.path.isfile(name): file.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED) From James_Althoff at i2.com Fri Mar 1 16:47:00 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 13:47:00 -0800 Subject: Status of PEP's? Message-ID: [Jim] > For example, one problem I had when playing with an experimental > implementation of the "middle argument" variant mentioned above is that the > specific relational operators are tied to the values of the bounds. If you > want to iterate from the smaller value (up) to the larger value you write: > > for 1 <= var < 5: > > whereas if you want to iterate from the larger value (down) to the smaller > value you have to turn things around and write: > > for 5 > var >= 1: > > which all looks very nice when you are dealing with literal constants. But > suppose you have variables for the bounds, "start" and "end"? Let's say I > have a function > > def doSomethingFromTo(start,end): > > The function has to test to see which of "start" and "end" is the smaller > value in order to know whether to execute a for-loop with "<" or a for-loop > with ">" (and the code specified in each separate for-loop has to be > written redundantly). I found this to be awkward. [Greg Ewing] > But if you really want, you can > always sort out the argument order before entering > the loop, e.g. > > if start > end: > start, end = end, start > for start <= i < end: > ... > > No redundant for-loop code required. But I don't get the specified behavior, either. [David Eppstein] > What's wrong with > for min(start,end) < var < max(start,end) > ? It gives different results than specified. Let's take an example. Suppose start == 10 and end == 5 This means I want to iterate on 10,9,8,7,6,5 (ignore open vs closed -- not relevant here) in *that* order. In Greg's case we swap start and end and do for 5 <= i <= 10 and iterate 5,6,7,8,9,10 -- the right numbers but the wrong order. In David's case we pick 5 as the min and 10 as the max do for 5 <= var <= 10 and iterate 5,6,7,8,9,10 -- same deal. In other words, if I want to iterate up (smaller up to larger) I need to write the for-loop as for smaller <= i <= larger: # can *only* iterate up but if I want to iterate down (larger down to smaller) I need to write the for-loop with the reverse relational operators for larger >= i >= smaller: # can *only* iterate down So if you want/need "from/to" functionality for an "interval" using the suggested for+relational idiom, you need to have two for-loops at hand, test the bounds, *and* pick the corresponding, correct for-loop (whose relational operators are in the correct direction). Note that the existing range and xrange functions (when used in a for-loop), although requiring a test on the bounds in order to determine the correct order of the args, do *not* require the use of two for-loops in this context. for i in range(n,m,step): # can iterate up or down depending on n,m,step I would like to be able to create a "directional, interval-like" object that iterates 10,9,8,7,6,5 (for example) as well as one that iterates 5,6,7,8,9,10 -- and do that with *one* construct, not two (in a for-loops, list-comp.s, or anywhere else). Using the much beloved (by few beside me ) "overload the divide operators" approach (just to illustrate the point, no need to flame the syntax again ), you can do this by saying interval_5to10 = 5 // span // 10 interval_10to5 = 10 // span // 5 so that one for-loop does the trick for i in start // span // end: # can iterate up *or* down, just like range can The fact that the suggested for+relational idiom *does* require two loops seems like a step backwards (again, in *this* context) to me. Or a limitation, at least. Just to clarify. Jim From jScPhArMistl at att.net Tue Mar 19 15:51:22 2002 From: jScPhArMistl at att.net (Joe Christl) Date: Tue, 19 Mar 2002 20:51:22 GMT Subject: Newbie: word count and Win32 References: Message-ID: On 19 Mar 2002 20:26:34 GMT, bokr at oz.net (Bengt Richter) wrote: > >From a quick look that[1] script, it looks like it expects to read >from stdin only. I.e., it says > > # iterate over each line on stdin > for line in sys.stdin.readlines() : > ... I emailed the author of the post (Derrick Hudson) and that was what he told me too. > >To feed the script's stdin you'll have to redirect or pipe data to it. >To pipe stuff on windows to a python script you have to run the interpreter >(python) explicitly one way or another, so I would try: > > python count.py < foo.txt > >or you could pipe the output of the windows type command, like: > > type foo.txt | python count.py The < redirect didn't seem to work from a Win32 standpoint. I tried the: python count.py < foo.txt ...and... python count.py foo.txt ... with failed results. I forgot about the pipe | > >To make the script work like what you expected, it needs to look >at the command line arguments (sys.argv) for a file name and open that, >and use the resulting file object in place of stdin. > He gave a a diff output for it to accept a filename. I am going to try that first and report back, >BTW, IMO you get a nicer ouput if you change the last line of the script to > print '%6d: %s' % (words[word], word) I don't really care too much about the amount of times a word shows up. I'll try it his way and yours. :) >As an exercise, you could modify it to accept an option on the command line >to output in order of frequency instead of alphbetically, and also accept >a file name. Then look into the glob module and see if you can make it >do multiple files from a wild card spec. Have fun. As busy as my time is, it may be next year when I finish all that :P >You may want to look at various scripts that were put on your disk when >you installed, e.g. in wahtever corresponds to D:\Python22\Tools\Scripts\* >on your system. Look at some small stuff first. > >Regards, >Bengt Richter > Thanks, Joe Christl From justin at iago.org Thu Mar 7 11:12:13 2002 From: justin at iago.org (Justin Sheehy) Date: Thu, 07 Mar 2002 11:12:13 -0500 Subject: Order of constructor/destructor invocation References: Message-ID: "Reginald B. Charney" writes: > Brett is exactly right. I am using an approach that is valid and elegant in > C++. Since elegance is largely a matter of opinion, I'll simply disagree on that point. Destructors and related methods generally ought to be used for object cleanup related to their reclamation, not for doing additional new processing. Abusing them in this fashion feels deeply inelegant to me, especially since there are so many straightforwward ways to solve the problem without resorting to such means. Elegance aside, your approach is invalid regardless of the programming language. You cannot create a correct HTML-writing program in the style you demonstrated, given the structure of HTML. Your linear style simply will not work for anything beyond trivial examples, since HTML is fundamentally hierarchical. As another poster mentioned, your method breaks down very quickly. Your style would not work for this fairly simple document because the structure is unclear: ----------------------------- h = HTML() b = BODY() l = LIST() le = LISTELEMENT() p = PARAGRAPH() ----------------------------- This will not work because you must specify both the start and end of a tag in this sort of language. It cannot be usefully inferred from any linear structure. This has little to do with Python, and will break just as badly in any language. A few examples of alternate strawman methods that might work: ----------------------------- h = HTML() b = BODY() l = LIST() le = LISTELEMENT() p = PARAGRAPH() h.start() b.start() l.start() le.start() le.end() l.end() p.start() p.end() b.end() h.end() ----------------------------- HTMLstart() BODYstart() LISTstart() LISTELEMENTstart() LISTELEMENTend() LISTend() PARAGRAPHstart() PARAGRAPHend() BODYend() HTMLend() ----------------------------- HTML(BODY(LIST(LISTELEMENT()), PARAGRAPH())) ----------------------------- The first two of these are not quite as concise as yours, but unlike yours all three are able to express the needed structure to correctly generate HTML. > While Justin is correct - there are a number of packages out there to > generate HTML, I was writing an article and trying to use Python for the > simple examples in the article. (The article was not about Python, per se). > I had to remove all references to Python when I found that the order of > destruction was non-deterministic. This doesn't follow. There are plenty of simple ways to do what you describe that work without trying to misuse the methods designed to aid with garbage collection. > It is interesting that destruction/garbage collection (something > usually done after everything has been completed) has so profound > effect on the design of programs and thus, implementation of > algorithms. It wouldn't have nearly as much effect if you took heed of your own parenthetical note and realized that all of an object's interesting work should be done before the destructor, as opposed to inside the destructor. I apologize if my tone here is a bit confrontational, but that is largely due to the fact that you immediately began blaming Python for not doing what you want in spite of an incorrect design. -Justin From cfelling at iae.nl Wed Mar 6 16:51:53 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 6 Mar 2002 22:51:53 +0100 Subject: PEP 284, Integer for-loops References: Message-ID: David Eppstein wrote: ... I haven't studied your proposal closely yet, so I'm probably way off here, but... > Issues > The following issues were raised in discussion of this and related > proposals on the Python list. ... > - Should types other than int, long, and float be allowed as > bounds? Another choice would be to convert all bounds to > integers by int(), and allow as bounds anything that can be so > converted instead of just floats. However, this would change > the semantics: 0.3 <= x is not the same as int(0.3) <= x, and it > would be confusing for a loop with 0.3 as lower bound to start > at zero. Also, in general int(f) can be very far from f. ...I definitely would expect this to work for all types that know about comparison and have let's say a successor or predecessor method. Integers should grow such methods too. Let's call the successor method next and confuse the hell out of everyone:) The loop variable will be of the same type as the left-bound. For `low <=' it gets as value the value of low, for `low <' the initialisation value is low.successor. So different steps are easy, like: class Step2(int): def successor(self): return Step2(self + 2) for low < x < 20: -- groetjes, carel From peter at engcorp.com Thu Mar 28 22:20:42 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 28 Mar 2002 22:20:42 -0500 Subject: vwait in Python? References: <1017315455.8141.1.camel@lewis> Message-ID: <3CA3DD8A.49C7C339@engcorp.com> Steve Holden wrote: > > "Ken Guest" wrote: in message > > So is there no way, short of a 2 line while statement, to have code > > hang around until the value of some variable has been changed? > > > > I have tried using variations of the simple while statement, but they > > only result in the application hanging (going into an infinite loop > > no doubt). > > > Now you've explained the REAL problem, of course it's easier to see how to > solve it. [...] > Something else you haven't explained is whether the code which changes the > variable's value is aware that there is another component waiting for it to > change (in other words, are you working with code you can modify, or must > you just wait for the value to change). This being Python, I wonder if it isn't possible, with code "you can't modify", to change the code anyway, by inserting an appropriate __setattr__() to monitor the change. If nothing else, this thought is giving me some cool ideas related to mock objects and such in doing test-driven development... hmm. :-) -Peter From cfelling at iae.nl Sun Mar 3 21:20:03 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 4 Mar 2002 03:20:03 +0100 Subject: Status of PEP's? References: <1cef615e.0203021254.6bf3658@posting.google.com> <3C82C77E.6B9FA688@cosc.canterbury.ac.nz> Message-ID: Greg Ewing wrote: > "Hernan M. Foffani" wrote: >> >> indici(x) will replace the odd xrange(len(x)) idiom and address the problem >> of open intervals where the length of the set is not known in advance. > I like this a lot! > But... where the **** did the word "indici" come from? some misplaced latin inflexion? > Could we please call it either "indexes" or "indices"? Let's go for indices then, as indexes is to similar to indexed, and I would like to reserve that word for the case you want the index as wel as the indexed item like in: for i, x in indexed("spam"): print "letter %s is a `%d'" % (i, x) -- groetjes, carel From jeff at ccvcorp.com Fri Mar 1 19:48:53 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 01 Mar 2002 16:48:53 -0800 Subject: Status of PEP's? References: Message-ID: <3C802175.A527BFA0@ccvcorp.com> David Eppstein wrote: > In article , > James_Althoff at i2.com wrote: > > > Another issue that I have is that the syntax does not work outside of a > > for-loop header. I want to be able to create integer intervals anywhere in > > my code, not just in the header of a for-loop. > > [x for 3 <= x < 10] Personally, I still don't see this as being an advantage over xrange(3,10). > or, for a slightly more complicated example: yesterday I wanted to iterate > over powers of two: > > [1L << x for 0 <= x < 1000] [1L << x for x in xrange(1000)] While this would benefit from generator comprehension instead of list comprehension, other than that, I don't (personally) see an advantage to the interval-syntax proposal. I suppose it's just a matter of taste, but I'd rather see fewer "nifty syntax tricks" added to Python, and I don't see this as adding enough functionality over xrange() to be worthwhile. Jeff Shannon Technician/Programmer Credit International From christophe.delord at free.fr Sat Mar 9 02:31:00 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Sat, 09 Mar 2002 08:31:00 +0100 Subject: short-circuit behavior anomaly? References: Message-ID: <3C89BA34.8070501@free.fr> Hi, There is a bug in 'fn'. pr always returns None. When x==1, pr('one') is executed (and prints 'one') and returns None so the condition (x==1 and pr('one')) is false. Finally the last condition will also be evaluated (ps('other')). you can define pr like this : def pr(s): print s return 1 or define the last condition like this : or (x not in (1,2) and pr('other')) Christophe. logosity wrote: > Hi, > > I was working through this tutorial: > http://gnosis.cx/publish/programming/charming_python_13.txt > > Which shows the statements in the following functions (imp and fn) as > equivalent: > > def pr(s): print s > > def imp(): > if x == 1: pr('one') > elif x == 2: pr('two') > else: pr('other') > > def fn(): > (x == 1 and pr('one')) \ > or (x == 2 and pr('two')) \ > or (pr('other')) > > Here is a sample program: > x = 1 > imp() > x = 2 > imp() > x = 3 > imp() > print > x = 1 > fn() > x = 2 > fn() > x = 3 > fn() > > When run, this produces the following output: > one > two > other > > one > other > two > other > other > > IOW, the third clause gets evaluated regardless of the outcome of the > first two clauses. > > However, substituting the following in fn() will produce the same > result as imp(): > print (x == 1 and ("one")) or (x == 2 and ('two')) or ('other') > > Implying something to do with the function calls -- if I replace the > pr('one') call in the line again will cause 'other' to be printed > after 'one') > > I am wondering, is this a mistake in the tutorial, a change in > behavior between versions (I am using 2.1 and the tutorial seems to > be written against 2.0), a bug in Python, or something else? > > I have looked through the FAQ, browsed the bug list at SF, read the > relevant sections of the language reference and searched (as best I > could) the mailing list archive here (and at google), but I can't > find out what the deal is. > > Anyone have any thoughts? > > Thanks, > Bill > > > -- Christophe Delord http://christophe.delord.free.fr/ From skip at pobox.com Wed Mar 6 17:42:54 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 16:42:54 -0600 Subject: The language vs. the environment In-Reply-To: References: Message-ID: <15494.39790.135887.255289@beluga.mojam.com> Sean> On 06-Mar-2002 Steve Lamb wrote: >> On Wed, 06 Mar 2002 13:21:35 -0800 (PST), Sean 'Shaleh' Perry >> wrote: >>> help release more python modules so perl mongers will quite wagging >>> CPAN in front of our faces. >> >> Quality over Quantity. :) Sean> not to disagree, however there are FAR more interesting perl Sean> modules out there than python ones. Correct, which is why a better solution than CPAN or VoP might include some sort of module rating system. However, this discussion probably belongs on the catalog-sig. (my first bullet. hint, hint... ;-) Skip From gimbo at ftech.net Thu Mar 7 08:55:02 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Thu, 7 Mar 2002 13:55:02 +0000 Subject: overloading a function Message-ID: <20020307135502.GA489@andy.tynant.ftech.net> On Fri, Mar 08, 2002 at 12:36:46AM +1100, Dave Harrison wrote: > If I have a function, but I want to be able to call it two different > ways - the ways being differentiated by the paramaters I pass the > function) how do I do this ?? The pythonic way is to use default parameter values as follows: def Foo(num, dflt=None): if dflt is None: # do whatever is appropriate else: # do whatever is appropriate Then you can use either of the following: Foo(5) Foo(5, 'hello') This is actually an FAQ: http://www.python.org/doc/FAQ.html#4.75 HTH, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From dale at riverhall.NOTHANKS.co.uk Sat Mar 30 08:35:49 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 30 Mar 2002 13:35:49 +0000 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <60FB8BB7F0EFC7409B75EEEC13E20192158DC1@admin56.narex.com> Message-ID: <0efbauk1gi6s06hi8pmo8cimsaci4l9b1q@4ax.com> Steven Majewski wrote: > >table = {} > >table[key] = func, (args,...) >... > >def doit( k ): > return table[k][0]( *table[k][1] ) > > >You could also use entries that are lists of (func,args) pairs, >and there are ways of constructing nested tables. > > There are many ways of achieving the same result as a nice clear case/switch/whatever construct, but they all end up being an exercise in deduction for the reader. You can't beat a properly designed construct for the purpose. Then, at least, everyone knows what you're trying to achieve. -- Dale Strickland-Clark Riverhall Systems Ltd From stefan.heimann at web.de Wed Mar 6 18:26:03 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 6 Mar 2002 23:26:03 GMT Subject: Getting stdout and stderr from popen References: Message-ID: Donn Cave wrote:: > Quoth Jonathan Gardner : >| Stefan Heimann scribbled with his keyboard: >|> I want to launch an external process and have stdout and stderr >|> redirected to one output stream, >| >| You are on Unix, right? >| >|> something like >|> >|> f = os.popen('cvs status 2>&1') >|> >|> does the right thing, but does not work on all platforms. > > Apparently he is not on UNIX? That's the right answer, as long > as popen() runs the UNIX shell. I am on unix but I want it to work on windows, too. > >|> If I write >|> >|> pin, pout, perr = os.popen3('cvs status') >|> >|> I get the output of stderr and stdout but not in the right order. >| >| What do you mean in the right order? Do you mean that it is returning in, >| err, out or that err and out are spitting out stuff simultaneously? the latter one. > > Probably not simultaneous, because the C I/O library probably has > thread interlocks that prevent it, but if you want a single time > ordered stream, you'd need time stamps to reassemble it out of > two. For example, suppose you record the output of "make", which > will be both output and error streams. If you read them separately, > you won't be able to tell which compiler errors belong to which > make commands. That's what I need! Is it really so complicated? I think it should be common that someone needs to read stdout and stderr ordered by time. > >| Okay, let's talk about what is really happening deep underneath the hood. >| >| These popen functions are a shorthand for a very common thing in the world >| of Unix. It goes something like this: >| >| 1) make three pipes (in, out, err) >| 2) fork. > > I beg your pardon, but that's really not common at all. Most UNIX > pipes are created using the shell, which makes a pipe for output only. > If you want a separate pipe for error, you're in for some gymnastics - > (cvs status 2>&3 | sed s/^/out:/) 3>&1 1>&2 | sed s/^/err:/ > And there's no Bourne shell formula at all to get all three on pipes. > More recent shells have features that could be exploited for that, > but it gets hairy. > > This is not just nitpicking, because there are real good reasons why > it isn't all that common. It's surprisingly difficult to get two > processes to cooperate reliably over multiple pipes. That's my second > point here - even if separate output and error streams are OK in terms > of the data, they're distinctly more difficult to deal with if you > don't make some simplifying assumptions about how the other process > is going to behave. > > The shell syntax to route both streams into the pipe is really the > right way to go, if it works. If it doesn't work, we'd have to know > why not, before suggesting any answer. (If it doesn't work on Windows, > then someone else is going to have to answer it - and the subject line > probably should have included "Windows" in the first place.) Hm, I haven't tested it on Windows, but I *know* that the shell syntax won't work. I didn't think that it is so complicated ;-) Bye Stefan From philh at comuno.freeserve.co.uk Wed Mar 27 12:41:58 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Wed, 27 Mar 2002 17:41:58 +0000 Subject: Random... References: <%slo8.20800$cB5.20607@atlpnn01.usenetserver.com> Message-ID: On Wed, 27 Mar 2002 10:22:10 -0500, Steve Holden wrote: > >While you correctly interpret netiquette, might it not have been more >considerate to this list if you had *mailed* the OP rather than giving >her/him a public dressing down which many others also had to read >unnecessarily? Or is it OK to waste *my* time by chastising the OP publicly? One advantage of posting to the newsgroup is that everyone else also gets the messages that top posting is bad. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From quinn at regurgitate.ugcs.caltech.edu Fri Mar 1 22:26:13 2002 From: quinn at regurgitate.ugcs.caltech.edu (Quinn Dunkan) Date: 2 Mar 2002 03:26:13 GMT Subject: Useful, robust shell utilities References: Message-ID: On Fri, 01 Mar 2002 21:13:15 +0900, Jonathan Gardner wrote: >I tried to use the shutil module... and to tell you the truth, it stinks. >Is there an effort to make a robust, useful shutil module that has the >equivalent of the unix shell utilities? > >I think it would be nice to make things like 'grep' even... > >Here is my wish list. Each of these should implement a significant portion >of what the GNU utils do. They should be robust, and give reasonable >results, and reasonable exceptions. > >touch, chmod, chown, chgrp, touch >df, du >cp, dd, install, mv, rm, shred I have a single function that implements more than a sigificant portion: os.system() Seriously, why reinvent all those wheels? If you're looking for portability to systems without them, I'm sure you can find implementations. Maybe not on the Mac though--I don't know how shellish stuff works there. If the answer is "it doesn't" then maybe a python solution is necessary. But all most of the chgrp etc. stuff isn't going to work there anyway. >If there isn't an effort to make this, or if no one has done anything like >this yet, I am willing to volunteer some time to do it. It would be really >nice if they ended up being compatible with Windows and Macintosh - give >them some powerful tools they didn't even know existed! The cygwin people already did this. If you want to do some hacking that's great, but your time may be better spent elsewhere :) From cbbrowne at acm.org Thu Mar 21 00:18:38 2002 From: cbbrowne at acm.org (Christopher Browne) Date: Thu, 21 Mar 2002 00:18:38 -0500 Subject: Java and Python References: <3C996234.9090506@verizon.net> Message-ID: The world rejoiced as Rich Salz wrote: > Cameron Laird wrote: >> I'm still looking for a way to get this point across: the >> answer to many questions is, "There's no such thing." No >> one plays the role for Python that Sun plays for Java. > > Hmm.. Both provide a reference implementation, both provide a > community process for suggesting improvements (but still retain the > right to do what they think best)... what's missing? Guido has slightly shallower pockets than Sun, and the community is worried about his being struck by massive passenger-carrying vehicles. -- (concatenate 'string "cbbrowne" "@canada.com") http://www3.sympatico.ca/cbbrowne/python.html Do Roman paramedics refer to IV's as "4's"? From jgardn at alumni.washington.edu Sat Mar 16 01:31:55 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Sat, 16 Mar 2002 15:31:55 +0900 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> Message-ID: Cliff Wells scribbled with his keyboard: > On 15 Mar 2002 05:35:15 GMT > Gerhard H?ring wrote: > >> The best solution to this problem is to give in and get a damn Windows >> box. Even a virtual one with VMWare or Bochs will do. AFAIK Bochs can >> run at least Windows 95 and it even runs on non-x86 hardware. > > I use VMware 2.0 at work and 3.0 at home and found it to be excellent. > I've had some stability problems with 3.0 (although this may be the result > of other factors - later Linux kernel versions, Athlon CPU, keyboard/chair > interface, etc). At work, VMware 2.0 has never crashed on me and > performance is excellent on a PIII 800 running Win2k, and it's far > preferable to having a dual-boot system. > VMWare is not free software, right? Trouble with non-free software is that they tend to go out of business eventually (like our dear friends from the Blender community) and take their software with them. Jonathan From carifio.nospam at nospam.usys.com Fri Mar 29 11:26:15 2002 From: carifio.nospam at nospam.usys.com (Mike Carifio) Date: Fri, 29 Mar 2002 16:26:15 GMT Subject: test_struct.py fails when building Python 2.2 on RedHat 6.2/alpha Message-ID: I've recently built Python 2.2 on a RedHat 6.2/alpha box. When I run the regression test suite ('make test'), test_struct.py fails with a floating point exception and stops the regression test suite. Some questions: 1) Is this a know error or have I discovered something new? I tried to find out if this error was seen before by going to the python bugs database (http://sourceforge.net/tracker/?atid=105470&group_id=5470&func=browse) and searching the newsgroup in Google. Are there other sources? I didn't find a good way to search the sourceforge bug tracker for specific keywords (like 'test_struct' or 'alpha'). 2) Once I take test_struct.py out of the test list, the suite runs to completion, but I still have 24 tests that have failed. Are all tests the same? For example, if test_bsddb fails, is my installation bogus or should I just shy away from db files on RH6.2/alpha? Is there a document or file somewhere that tells me how to interpret these results? 3) And related to (2), is test_struct.py a "mandatory" test? I guess the question I'm asking is: if some of the tests fail, is the build to be distrusted? If there's a judgment call to make here, how do I inform my judgement? Please advise at your convenience. Thanks. From peter at engcorp.com Sat Mar 2 18:22:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Mar 2002 18:22:37 -0500 Subject: Windows GUI - which way? References: <3C7EC855.5844B19F@engcorp.com> Message-ID: <3C815EBD.7DC6C694@engcorp.com> Spencer Ernest Doidge wrote: > > I want to maintain and use a library of Python scripts. I want to invoke > any script from this library by using a GUI app. The script itself would > have no GUI features. It would be sending and receiving serial port > messages. (This is like the script I am already running.) > > Some frequently-used scripts would be invoked directly from a Tools menu, > others would be named in a File/Open dialog. I want to begin execution of > the script by using either a menu, a dialog, or a toolbar icon. When the > execution begins, I want to be able to abort the script at any time by > either a dialog button, a menu item, or a toolbar icon. Sounds a lot like some kind of automated testing system. Can you describe the nature of the application, to help us envision appropriate approaches? > If I write the GUI app all in Python, is it a simple matter to, say, load > and run the script in its own thread, and have it be responsive to a > signal from the main thread telling it to abort? Sure. Scripts can be loaded at any time with 'import', and it's trivial to derive a Thread class which sports a spiffy "stop()" method that sets a flag which is polled in the main loop as a way of telling the thread to clean up and exit. > For nice-to-haves, it would be nice to display some sort of output, even a > progress control (thermometer, or whatever one calls it), or some text in > an output window, the way it's done in Visual C++ when you build a > project. The background thread can communicate with the GUI thread by using the various mechanisms for such a thing that are provided by Python (e.g. 'Queue') and by the GUI framework you pick (for example, the wxWindows/wxPython 'PostEvent()' method). > Do you know of straightforward ways to accomplish the must-haves? > > What about the nice-to-haves? Just start building and ask away in this forum as you encounter difficulties. :-) From NO_SPAM_jmpurser2 at attbi.com Sat Mar 16 15:04:08 2002 From: NO_SPAM_jmpurser2 at attbi.com (John Purser) Date: Sat, 16 Mar 2002 20:04:08 GMT Subject: Sample Python programs to look at? References: <327f0ccd.0203161144.14299a4c@posting.google.com> Message-ID: Chris just posted this as a useful link in another similar thread: http://www.lowerstandard.com/python/ As someone new to Python it was just what I was looking for. John "jennyw" wrote in message news:327f0ccd.0203161144.14299a4c at posting.google.com... > Hi there! I was just wondering if someone could suggest sample Python > programs to look at. Something complicated enough for me to get a > feel for what programming something non-trivial would be like, but not > so complex that it's overwhelming. In particular, I'm interested in > database access (e.g. MySQL) and IMAP access, so if there's a smallish > app. w/ source out there that someone could point me to, that'd be > great! > > Thanks! > > Jen From shriek at gmx.co.uk Fri Mar 1 22:09:36 2002 From: shriek at gmx.co.uk (Stephen) Date: 1 Mar 2002 19:09:36 -0800 Subject: Want to monitor process.. References: <87550ef1.0202272315.15779bbd@posting.google.com> <97ae44ee.0202280901.3153bdfc@posting.google.com> <3C7EC9C6.D11FB17@engcorp.com> <97ae44ee.0203010102.14ebf2bb@posting.google.com> <3C7F66AB.D51BEA03@engcorp.com> Message-ID: <97ae44ee.0203011909.620b829b@posting.google.com> Peter Hansen wrote in message > > > Yikes! "Crash"? Do you really mean they crash the Python interpreter, > > > or do you mean they exit with an exception? > > > > Sorry, I guess I mean "exit with an exception" though to be honest, I > > still don't know because I haven't been able to run the programs > > interactively during a 'crash'. > > I'm not sure what the interactive thing would add, since the > interpreter will already print exception tracebacks to the console > whenever your program exits exceptionally. If you aren't seeing > a traceback, maybe you aren't really exiting with an exception. Sorry, I should have explained that the reason I don't see the output is that I run the programs in the background since I log into the servers from remote and don't want the programs exiting when I log out. > > > If the latter, just wrap the highest level code with a try/finally > > > or try/except and put code in to ensure the child processes are > > > properly terminated. Simple, clean, safe. > > > > Will do. I didn't want to put try/except/finally at the highest level > > of code yet since we're actually in Beta and I want to know when my > > server encounters a problem. > > No problem, just put a "raise" statement as the final statement in > the exception handling block (when using try/except only) and you'll > still propagate the exception up and right out of the interpreter > so it prints a traceback to the console. Good idea, this is something that I think I should employ for all code in future. When developing applications, I usually have exceptions raised at the lowest level of code (eg. the module/class level) but then as I start building the higher levels of code, the lower levels get lost ('swallowed') as opposed to propagated up. Damn, wish that had occured to me earlier. > In the try/finally case, > however, you'll still get the traceback if an exception *did* > occur, because the interception is only a temporary one. After the > finally code executes, exception processing continues on. > > I think you might focus on the lack of a traceback. You should > always see one if you aren't explicitly swallowing the exception. > (Note, a few standard modules such as the SocketServer and such > will internally swallow exceptions in the server threads by default.) I've been logged in and watching the console for several hours and I am getting a traceback when errors occur ~ the difficulty I had before was imposed by running to the background, which I've just seen in the link below (http://cr.yp.to/daemontools/faq/create.html#why) is apparently not good software design. ................................. > From: Greg Green (gregory.p.green at boeing.com) > Subject: Re: Want to monitor process.. > Newsgroups: comp.lang.python > View this article only > Date: 2002-03-01 12:35:56 PST > > > If you are using a unix OS, I would suggest using daemontools > from Bernstein. It has a set of tools for supervising a process. > I use it all of the time for these sorts of problems. Excellent! This looks like just the ticket. I've actually employed it in the past with Bernstein's Qmail but never truly understood the importance of it. Now that I've read the minimalist documentation, I think this is going to become an important addition to my toolbox. Thank you, gentlemen, thank you. Stephen. From gbreed at cix.compulink.co.uk Fri Mar 8 06:14:55 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Fri, 8 Mar 2002 11:14:55 +0000 (UTC) Subject: 'The Goat and the Car' puzzle solved in Python -- was: [GERMAN] "ziegenpro References: Message-ID: Oh, this is the zeigenproblem thread? I was ignoring it because it purported to be in German. > Le 07/03/02 ? 19:28, stefan antoni ?crivit: > > sorry that i won't be able to explain this in english, i don't know > > the > > name of this problem in english, and the website which is about this > > problem is also in german. It's called the Monty Hall Problem. > > i am still going to school, and we talked about this problem in a math > > lesson. since i haven't got a basic-interpreter, i'd like to translate > > this code into python, but i don't understand the code. Here's my monty.py from a while back. It gives the result you got 66642 cars and 33358 goats you were right 66% of the time so the stratagem works! """Python script to test the Monty Hall Problem""" import whrandom nCars = 0 nGoats = 0 for each in xrange(100000): # decide where the car is carPosition = whrandom.randint(1,3) # choose a door myFirstChoice = whrandom.randint(1,3) # Monty chooses a door # not your door or the one with the car behind for door in (1,2,3): if door not in (carPosition, myFirstChoice): montyChoice = door # change your mind for door in (1,2,3): if door not in (montyChoice, myFirstChoice): myFinalChoice = door # see what you won! if myFinalChoice == carPosition: nCars = nCars + 1 else: nGoats = nGoats + 1 print "you got %i cars and %i goats" % (nCars, nGoats) print "you were right %i%% of the time" % (nCars*100/(nCars+nGoats)) From greg at cosc.canterbury.ac.nz Wed Mar 6 21:31:11 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Mar 2002 15:31:11 +1300 Subject: Pep 276 - if 6 were 9 References: Message-ID: <3C86D0EF.4FD46F1B@cosc.canterbury.ac.nz> Emile van Sebille wrote: > > for each of range(6): > for each of mylist: > for each of 6: for seven of 9, tertiary adjunct of unimatrix(1): ... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From surajsub at netscape.net Fri Mar 15 20:24:33 2002 From: surajsub at netscape.net (Surajsub) Date: 15 Mar 2002 17:24:33 -0800 Subject: Help Required Message-ID: Hi, I am a newbie to Python and am pretty fascinated by it power and speed.I am however puzzled in trying to write this script. The script builds a list of userids to be fed to ldap and it is supposed to be uid1,uid2,uid3....and so on.( Notice there is no space) However when i am trying to create the uid list it gives uid1, uid2, uid3,...and so on. how do i get rid of this leading space if u would call it.. string.lstrip does not work either. what am i doing wrong? TIA Suraj From mlh at vier.idi.ntnu.no Mon Mar 4 12:05:44 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 4 Mar 2002 17:05:44 +0000 (UTC) Subject: ANN: experimental patch to allow importing from file-like objects References: <3c7fcbe6.7419921@news.t-online.de> <3c81245c.47694421@news.t-online.de> <3C817D5C.24C26C3F@earthlink.net> Message-ID: In article <3C817D5C.24C26C3F at earthlink.net>, Hans Nowak wrote: >Gerson Kurz wrote: > [...] >I don't know much about 2.2 yet, but I think the >preferred method is subclassing file, then opening a >file through the subclass's constructor (rather than >through open()). For example: open *is* file. (Just take a closer look.) So you should subclass file (i.e. open) -- and of course you'd then use the constructor of that class, not the constructor of your superclass (which would be file or open, which are one and the same). -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From amoustafa at pobox.com Wed Mar 20 01:41:13 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Wed, 20 Mar 2002 06:41:13 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> Message-ID: <3C982EDA.2050408@pobox.com> Peter, Thanks a lot for your answers. I really appreciate them. Peter Hansen wrote: > Ahmed Moustafa wrote: > >>Peter Hansen wrote: >> >>>Ahmed Moustafa wrote: >>> >>>>1. Where can I find an unbiased comparison between Java and Python? >>>>2. Will Python dominate? >>>>3. Who does support Python? >>>> > [...] > >>>I think if you told us what your purpose is in asking the questions, >>>the answers would be more useful and direct. _Why_ do you want >>>to know? >>> >>I'm interested in knowing which skills will(are) being looked for. >> > > Thanks for the clarification. In that case, these would be my answers > to you: > > 2. Python will not dominate, any more than any other language will. > Python is certainly in a growth period, but it seems unlikely it > will attain the mass acceptance of Pascal, C, C++, and Java in their > day. (Not to imply that Java's day has passed... that much is > evident from the number of bookstore shelves devoted to it!) > But who cares? If you go where the mass unwashed go, you'll get > the same sorts of mundane and rote jobs as the mass unwashed do. > > 1. As others have said, there is no such thing as an unbiased > comparison of almost anything, let alone programming languages, > let alone two with such, uh, "dedicated" users as Java and Python. > Nevertheless, even if we could find such a thing, the response > would really depend entirely on the application area. How about web development? Also, how is Python doing in the embedded applications? > Java is better suited for some applications, and Python for > others. Without defining the type of work you want to do, > any comparison is meaningless. (E.g. "Python programs tend > to be much more readable" doesn't matter if your job involves > writing Java on a Java team doing EJB stuff, unless you > can get the whole team to use Jython instead.) > > 3. The best support for either Java or Python is probably in > their respective newsgroups. Python's is widely known as being > one of the most polite and helpful. The language has been > around a little longer as well, and as it's not largely a > commercial venture this might suggest that the "support" > question is a bit of a red herring. Do you regularly contact > the Microsoft for help with VB, or Sun for help with Java? > (Or did you mean who is "backing" the language, ensuring > its continued viability. The answer to that is twofold: > look at the 11+ year age of Python as historical proof > it's not a flash in the pan, and note it's _open source_ > so it cannot, by definition, lose viability while people > support and use it. You can always get the source.) > > Here's my best answer to you: I happen to hire programmers > to work on my team in a wireless telecom company. Although > we happen to have chosen to use Python in addition to C and > a few minor languages like Javascript and Assembly, where > necessary, the language we use is hardly the most important > thing. > > Communication skills are, first and foremost, the thing I > look for in hiring. This includes the softer social skills > like how to work in a team and put aside one's programming > ego. Next are adaptability, as in how easily someone can > pick up new skills and apply them effectively. Design > skills are useful. Debugging skills are very valuable, > though rather unfortunately rare. Probably some others > that don't come to mind in today's economy (we're not > hiring now :-). > > Way, way down the list of things I look for in a resume > is the programming languages a candidate has. Not entirely > unimportant, but useful only taken as a whole. I don't care > whether somebody knows Python, and have found and hired > only one such programmer yet (and not because he knew Python). > The others had a variety of backgrounds including Java, > C++, Delphi, VB, C, BASIC, assembly of various kinds, > and so forth. Those with only a single language, or > maybe two, probably didn't get hired. Those with a dozen > were more able to demonstrate their flexibility to me. > > When they were hired, they went to work learning Python. > About a week later, most of them were already contributing > in a productive way. A month later any of them could > code Python as well as they could code in any of their > previous languages. For the most part, I would have > expected the same of them even if we used Java (though > perhaps with a somewhat longer learning curve). > > The point is, I would never hire you or anyone _because_ > you knew Python, or Java. I would hire you because > I thought you were capable of learning it and using it > effectively. I actually tend to shy away from people > with great lists of "certifications" in languages because > it suggests to me they have difficulty learning and > think it's a very impressive thing that they managed > to learn enough to write an exam which tests knowledge > of syntax but little about programming skill. I agree a certificate does not mean a great programmer, and I think the employers know that, but it still tells that one is serious about the profession. I have been programming with Java for +4 years now. I got certified 2 months ago. I feel my resume is stronger now. > > My suggestion then is to "get over" the comparison thing, > and make sure you know both, and throw in others as you > come across them and have opportunity to learn. This will > make you a better programmer, because of the learning and > generalization your brain will do, not because of the > specific skills you have. > > Not all companies hire in this way, of course, but all > the best ones do. :-) > > -Peter > > P.S.: If you are considering Python as a massive growth > area where ex-Java programmers can go to get lucrative > jobs, you're bound to be disappointed. As in programming, > there is no silver bullet. > -- Ahmed Moustafa From maxm at mxm.dk Fri Mar 15 13:50:42 2002 From: maxm at mxm.dk (Max M) Date: Fri, 15 Mar 2002 18:50:42 +0000 Subject: Converting relative URLs to absolute References: <23891c90.0203130331.6f030f5b@posting.google.com> <23891c90.0203150820.6362868@posting.google.com> <1BA0B611A94DFC68.31BB361E767CE89A.765E82A2856C9826@lp.airnews.net> Message-ID: <3C924282.6020407@mxm.dk> Cameron Laird wrote: > From what I've seen, cURL, or more properly libcurl > , has cornered the market > in being an efficiently coded library which properly > interprets the most recent URL standards. Is Python > best served by support of pycurl? Isn't Curl more like urllib? This thread was about a function that could manipulate, and especially add, (relative)urls regards Max M From bosahv at netscapenospam.net Thu Mar 14 02:56:13 2002 From: bosahv at netscapenospam.net (Bo Vandenberg) Date: Thu, 14 Mar 2002 07:56:13 GMT Subject: Python Version Strategy? Message-ID: I'm confused by what is going on with the python versions from various sources. Python.org has a final 2.2 (I use that) but Activestate has a python 2.1 as its recommended python and only a 2.2 beta last I looked. Redhat, and most (all?) of the linux distros seem to be slow to fully upgrade and I feel like this is raining in my cornflakes. I'm not even beginning to think of when the next version of python (3?) comes out. Anyone think they have inside information on all this? What's a forward thinking newbie, with no old code to support to do??? From brueckd at tbye.com Tue Mar 5 10:42:43 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 5 Mar 2002 07:42:43 -0800 (PST) Subject: Python song? (Re: Python isn't necessarily slow) In-Reply-To: <3C8451E1.B2CD032@cosc.canterbury.ac.nz> Message-ID: On Tue, 5 Mar 2002, Greg Ewing wrote: > Siegfried Gonzi wrote: > > > > Python isn't necessarily slow: > > That sounds like a great title for a Python > song: "It Ain't Necessarily Slow!" Hmm... 'necessarily' is a bit cumbersome. The "ain't" makes me think of country songs from the U.S., so how about "Just cuz I slither, it don't mean I'm slow"? On a side note, I noticed *another* musical-sounding thread started up - "I've got the Unicode blues". -Dave From grante at visi.com Sun Mar 10 00:52:35 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 05:52:35 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> Message-ID: In article <3C8AEE09.5B2431FD at engcorp.com>, Peter Hansen wrote: >> That's kind of sad, but I figured as much. The only real >> stand-alone Win32 app I've seen in a long while is puTTY. Are >> statically linked apps just not possible under Win32, or just >> not practical? > > Just as possible and practical as under Linux, really. But under Linux, there's generally the option to distribute source, thus allowing the user to generate a binary that is linked with the "right" libraries. > Which is to say not highly desirable in many cases, at least > for serious (read, largish) applications. For smaller utility > type programs, definitely possible but, unfortunately, less of > an option in your case trying to do it with Python tools. But > you really don't want to statically link an 800K interpreter > and a 2MB windowing framework into your little utility, do > you? :) Hmm, I don't really see the difference in practice between statically linking and installing a bunch of "private" DLLs that are only used by my app. In one case they're all in one file, in the other case they're in a bunch of files that have to be linked at run-time. In both cases none of the stuff is being shared with anybody else, so it's not like putting things in DLLs is saving any system resources -- though it perhaps make the packaging simpler. >> > Use py2exe and you'll get a directory with the Python DLL, the >> > wxPython DLL, your EXE, and a few other DLLs as needed (e.g. >> > the native regular expression stuff if you use it). >> >> I don't know diddly about DLLs, so pardon the ignorant >> question: Can my DLLs be put in a private directory where my >> EXE can find them? I'd rather not put anything in any public >> system directories. > > Yes, definitely. Not entirely advisable if you're delivering > more than one program in the same manner, Right now I don't exect to. If I did, couldn't I make all of "my" apps look in the same place for "my" DLLs? I really hate the idea of my app putting things in "system" directories. That's just plain evil. [Though that does appear to be SOP under Windows.] > since you'd be duplicating piles of files, but you can do it. If I am duplicating files, then that means that some other app is using the same DLLs. One of us is going to have to either overwrite what's already there or use what's already there. My limited experience is that neither option works very well. AFAICT, there doesn't appear to be a practical way to have multiple versions of DLLs installed, so if you've got two apps that require different versions of DLLs, then one of the apps is screwed. > And I suppose there's the fact you'd be avoiding much of the > grief caused by dynamically linked apps and "DLL version hell" > by doing that, if you can spare the hard drive space (and most > users probably can these days). Windows users... worried about drive space... ROTFL! -- Grant Edwards grante Yow! Let's all show human at CONCERN for REVERAND MOON's visi.com legal difficulties!! From phr-n2002a at nightsong.com Tue Mar 26 15:24:51 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 26 Mar 2002 12:24:51 -0800 Subject: Optimizations (was Re: reduce vs. for loop) References: Message-ID: <7xeli7m60c.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > Try this: > > def fact3(n): > mul = operator.mul > return reduce(mul, range(1L, n+1) ) I don't think this is permitted, but if it were, apply(mul, range(1L, n+1)) would probably be faster than reduce. From mhammond at skippinet.com.au Mon Mar 25 17:13:11 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 25 Mar 2002 22:13:11 GMT Subject: win32Extensions,win32com References: <3C9EFE65.7000300@decillion.net> Message-ID: <3C9FA112.1080408@skippinet.com.au> Gerrit van Dyk wrote: > Hi all, > > Is there a newsgroup or mailing list for the win32com extensions from > Mark Hammond or should I post related questions on this list? > > Regards > Gerrit van Dyk > This list is fine. There is a win32 specific list at http://mail.python.org/mailman/listinfo/python-win32 if you prefer. Mark. From tdickenson at devmail.geminidataloggers.co.uk Wed Mar 13 06:36:54 2002 From: tdickenson at devmail.geminidataloggers.co.uk (Toby Dickenson) Date: Wed, 13 Mar 2002 11:36:54 +0000 Subject: zlib vulnerabilities and python References: Message-ID: Erno Kuusela wrote: >In article , Robin Becker > writes: > >| Does the recent zlib double free vulnerability >| http://news.com.com/2100-1001-857008.html > >| impact zlib.pyd? > >i can't think of a reason why it wouldn't. if it's dynamically linked >to zlib, you can just update the zlib library though. Not on Windows, if I remember correctly (and I dont have a windows machine handy to check) Toby Dickenson tdickenson at geminidataloggers.com From maxm at mxm.dk Wed Mar 13 19:33:52 2002 From: maxm at mxm.dk (Max M) Date: Thu, 14 Mar 2002 00:33:52 +0000 Subject: dictonary References: <3C8F27DC.F69B1F54@stud.cs.uit.no> <3C8F3800.3070002@mxm.dk> <3C8FEA78.C6250F62@3captus.com> Message-ID: <3C8FEFF0.2000607@mxm.dk> Bernard Yue wrote: > >Max M wrote: > >>A bit more readable perhaps? >> >>keys = dict.keys() >>vals = dict.vals() >>sql = "insert into table(%s) values (%s)" % ( >> ','.join(keys), >> ','.join(list(len(keys)*'?')) >>) >>cursor.execute(sql, vals) >> > >Will this method cause problem when inserting numbers (strings are >quoted, but not for numbers)? I remember it will (not 100% sure, it's >been a while). Thats what I've done (with MySQLdb): > If it follows the Python DB standard, quoting should not be nessecary when doing it like above. The execute method should automatically do the correct quoting whenever nessecary. To quote the spec: ------------------------------ " The module will use the __getitem__ method of the parameters object to map either positions (integers) or names (strings) to parameter values. This allows for both sequences and mappings to be used as input. The term "bound" refers to the process of binding an input value to a database execution buffer. In practical terms, this means that the input value is directly used as a value in the operation. The client should not be required to "escape" the value so that it can be used -- the value should be equal to the actual database value. " ------------------------------ So the above code generates a query like: sql = "insert into table(firstname, lastname, country) values (?,?,?)" The questionmarks are placeholders for the values in the parameter tuple passed to execute. cursor.execute(sql, ("Max's", 'M', 'Denmark')) You could also chose other ways to format your querystrings. regards Max M ------------------------------ paramstyle: String constant stating the type of parameter marker formatting expected by the interface. Possible values are [2]: 'qmark' = Question mark style, e.g. '...WHERE name=?' 'numeric' = Numeric, positional style, e.g. '...WHERE name=:1' 'named' = Named style, e.g. '...WHERE name=:name' 'format' = ANSI C printf format codes, e.g. '...WHERE name=%s' 'pyformat' = Python extended format codes, e.g. '...WHERE name=%(name)s' ------------------------------ From 987A8857 at eudoramail.com Wed Mar 27 08:38:04 2002 From: 987A8857 at eudoramail.com (987A8857 at eudoramail.com) Date: Wed, 27 Mar 2002 08:38:04 -0500 Subject: Here is how you will recieve you Vacation at no cost, Message-ID: <7j7wka7e240i1k.24m0iu7yrt2b@mx2.efax.com> An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Mar 2 20:58:02 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 2 Mar 2002 17:58:02 -0800 Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: "David Eppstein" > Here's another way of looking at the same question. > An iterable object has a next() function, that's what it means to be > iterable. If numbers are iterable, we can call number.next(), right? > So what should 5.next() be? Surely anyone familiar with the Peano axioms > would say 6, not 0! Interesting, but even that depends on access mode. If I open a file to iterate over it, I certainly expect record 0 to be retrieved first. OTOH, if I want to add a record, then I want the next _unused_ index. As for what else iter(5) could mean, it's certainly more interesting to have it count up to five vs counting up from five! ;-) I-have-to-get-back-to-practicing-my-Peano-now-ly y'rs, -- Emile van Sebille emile at fenx.com --------- From rstephens at vectron.com Wed Mar 6 07:52:37 2002 From: rstephens at vectron.com (Ron Stephens) Date: 6 Mar 2002 04:52:37 -0800 Subject: Black Adder and PyQt References: <3c8087eb$0$18514$e4fe514c@dreader4.news.xs4all.nl> <3c848d1a$0$90054$e4fe514c@dreader1.news.xs4all.nl> Message-ID: I have just ordered both Black Adder, Personal edition plus one year of updates, as well as your new book, GUI Programming with Qt: Python edition. I want to thank all of you who responded to my initial enquiry: you have helped to make my decision (along with some helpful comments from the programming forum at www.arstechnica.com where a couple of people were very enthusiastic about Black Adder). I also mentioned your book there and posted the link you gave to Opendocs where I ordered it. I almost feel guilty for not supporting PythonWare also, but my reasons are: 1. I want to use my gui programs primarily on Linux (KDE) and also, eventually, the Sharp Zaurus which uses the Qt toolkit. 2. The new GUI programming book using PyQt will be very helpful to me, it includes chapters specifically on Black Adder. 3. I feel it is time for me to get off the fence and support Black Adder, which appears to be what I am looking for. This will not be a quick learn for me, but I am in it for the long term now. Thanks to all who offered opinions, and I look forward to reading the book as soon as I get home from Asia! ;-))) Ron Stephens gui programming neophyte From djc at object-craft.com.au Sat Mar 23 01:39:36 2002 From: djc at object-craft.com.au (Dave Cole) Date: 23 Mar 2002 17:39:36 +1100 Subject: Sybase module 0.34 released Message-ID: What is it: The Sybase module provides a Python interface to the Sybase relational database system. It supports all of the Python Database API, version 2.0 with extensions. This is mostly a bug fix release. 1) Cursor state machine fix from Phillip J. Eby. 2) Fix for MS compiler reported by Roberto M Esguerra. 3) Added CS_IFILE option to ct_config() for Erik A. Dahl. The module is available here: http://www.object-craft.com.au/projects/sybase/sybase-0.34.tar.gz The mailing list for discussing the module is here: https://www.object-craft.com.au/cgi-bin/mailman/listinfo/python-sybase The module home page is here: http://www.object-craft.com.au/projects/sybase/ - Dave -- http://www.object-craft.com.au From jon+usenet at unequivocal.co.uk Sat Mar 30 20:07:56 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Sun, 31 Mar 2002 01:07:56 -0000 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> <23891c90.0203290655.25bbcab9@posting.google.com> Message-ID: In article <23891c90.0203290655.25bbcab9 at posting.google.com>, Paul Boddie wrote: > It's actually quite reminiscent of the earliest versions of DTML, in > fact, where comments are used to mark the structure of the "model" as > opposed to the special tags which were introduced in DTML later on. Why were special tags added? I don't see any need for anything above the two concepts of 'replacements' and 'sections' that jonpy provides. I think the three interesting concepts in jonpy are: * absolute minimum of non-html code in html templates * correspondence between html sections and nested classes, e.g.: HTML:

    Top level.

    $$replacement$$

    Top level.

    Code: class main(wt.TemplateCode): class section(wt.TemplateCode): def replacement(self): return "Section." * dual file hierarchy for html and code, e.g.: DOCUMENT_ROOT/index.html DOCUMENT_ROOT/img.jpg DOCUMENT_ROOT/thing.html DOCUMENT_ROOT/subdir/index.html DOCUMENT_ROOT/wt/index.html.py DOCUMENT_ROOT/wt/thing.html.py DOCUMENT_ROOT/wt/subdir/index.html.py > Zope Page Templates takes the other "under the radar" approach, of > course, using special attributes which HTML editors usually don't want > to touch. Presumably bad things still happen if the designer deletes the tag itself that the magic attributes are attached to though. > In the Python community, there is obviously an intense interest in > templating, but I haven't seen more than a handful of validation > packages, and I can imagine that few of them actually integrate > satisfactorily with template packages. I'm not sure what you mean here. Can you give an example of what a "validation package" might do? Cheers Jon From skip at pobox.com Thu Mar 7 14:21:25 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 13:21:25 -0600 Subject: The language vs. the environment In-Reply-To: <23891c90.0203071057.57204175@posting.google.com> References: <23891c90.0203071057.57204175@posting.google.com> Message-ID: <15495.48565.198124.510813@beluga.mojam.com> >> * breathe some life into the catalog-sig: >> http://www.python.org/sigs/catalog-sig/ Paul> We've got the Vaults and siphon has been around and yet failed to Paul> maintain a high profile, as far as I've read on this list/group. Paul> Interestingly, the CPAN issue just keeps coming up. Myself, I Paul> wrote a script to query the Vaults, and I even have functionality Paul> for finding dependencies, although with the "screen-scraping" Paul> techniques in use, my code is possibly not that reliable. Paul> Nevertheless, I see a future for "grass roots", really simple code Paul> in this area, and surely writing that code would be *much* easier Paul> than writing a PEP about some banal language change. There was a lightning talk at IPC10 on Gideon, a prototype Python repository. Since it's implemented as a Zope product I think you sort of get an XML-RPC API for free, which would beat screen scraping hands down. You can check it out: http://www.zope.org/Members/k_vertigo/Products/Gideon A prototype server is at: http://66.123.57.58:8080 Thanks to Andrew Kuchling for the references. >> * find a Python bug without a proposed fix and write one (there are >> currently between 250 and 300 open bug reports): >> http://sourceforge.net/tracker/?group_id=5470&atid=105470 Paul> Although one might think that this requires a "Python internals Paul> skill level" of at least 7 out of 10, there are probably porting Paul> issues that could usefully be resolved by people with access to Paul> the right hardware. Correctamundo. I am in the midst of composing a note looking for new developers, to be posted shortly. Skip From sam_collett at lycos.co.uk Thu Mar 7 05:26:03 2002 From: sam_collett at lycos.co.uk (Sam Collett) Date: 7 Mar 2002 02:26:03 -0800 Subject: Python Classes Message-ID: <2030665d.0203070226.46b39af4@posting.google.com> I am quite new to Python and have no experience with classes. I have tried a file class, but I am not sure how to get it to work: class clFile(file): def getFileName(blnExt=None): """ file = path to file blnExt = show file extension (put in value other than 0 or None to show the extension) """ import os if blnExt: result = os.path.basename(file) else: result = os.path.splitext(os.path.basename(file))[0] del os return result def getFileExt(): import os.path result = os.path.splitext(file)[1] del os return result def getDir(): import os result = os.path.dirname(file) del os return result I wondered if there was a way to do something like the following: myfile = clFile("c:\\somedir\\dir with spaces\\foo.txt") myfile.getDir would return c:\somedir\dir with spaces\ myfile.getFileExt would return .txt myfile.getFileName would return foo.txt or foo From tim.one at comcast.net Mon Mar 11 18:16:12 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 11 Mar 2002 18:16:12 -0500 Subject: Using doctest and executing a process In-Reply-To: Message-ID: [Tim] > You may have better luck with, e.g. > > >>> os.open('/bin/ls').read() Make that >>> os.popen('/bin/ls').read() or-insert-other-letters-at-random-until-it-actually-works-ly y'rs - tim From robin at jessikat.fsnet.co.uk Thu Mar 21 19:58:27 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 22 Mar 2002 00:58:27 +0000 Subject: mutlifile inheritance problem References: <9896e047.0203211303.741f695a@posting.google.com> <3C9A680A.F00216D2@hotmail.com> Message-ID: is this connected to motley-fool? -Heavens to Murgatroyd-ly yrs- Robin Becker From mlh at vier.idi.ntnu.no Wed Mar 20 22:55:14 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 21 Mar 2002 03:55:14 +0000 (UTC) Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: In article , Martin v. Loewis wrote: >mlh at vier.idi.ntnu.no (Magnus Lie Hetland) writes: > >> I know there are several solutions available for building standalone >> binary executables from Python programs (Freeze, py2exe, McMillan >> Installer, etc.) -- I just wondered if it would be possible to add >> functionality like this to distutils? > >That is certainly possible; freeze would be the obvious choice for >such a mechanism (IMO). Hm. I just tried freeze (with a simple 'print "Hello, world"') script and it failed miserably, after first having frozen almost all the modules in the standard library. In my experience (not very extensive in this area), both py2exe and the McMillan installer have performed much better... But that may be my fault, of course. > Alas, distutils is unmaintained, Really? A pity. > so don't wait > for anybody else to implement it for you. I guess not. There is always the hope that if one gripes about something someone else will be inspired to do something about it ;) Oh, well. Maybe when I get lots of extra time... >Regards, >Martin -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From shalehperry at attbi.com Fri Mar 22 14:47:26 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 22 Mar 2002 11:47:26 -0800 (PST) Subject: Namespace Qualification Question In-Reply-To: <3C9B7C2A.20708@cpsc.ucalgary.ca__no_spam__> Message-ID: On 22-Mar-2002 Craig McLean wrote: > I've been messing around with python namespaces and I've run into > something that I haven't been able to answer. > > Is there a module assosciated with the file you started the interpreter > with, and if there is what is it's name? For instance > > > python qux.py > > I would have thought that there would be a qux module, and that it's > name would be stored in the __name__ builtin. > > If I was using the interpreter interactively would that change things? > When run as a script its __name__ is '__main__'. This is how all of those python modules allow themselves to contain test code. def my_func(arg): pass if __name__ == '__main__': my_func() if you import the above code (say it is in my.py) in an interpreter session or in a script the __name__ will be 'my'. If you run it as python my.py its name is '__main__'. From dragon at china.org Sun Mar 10 23:43:47 2002 From: dragon at china.org (Qiang.JL) Date: Mon, 11 Mar 2002 04:43:47 GMT Subject: should i learn it first ? References: Message-ID: <7CWi8.104549$aFN.34864@news1.bloor.is> yeah. i have been following my post. thanks for everyone's input. It helps! seems a lot people recommend C over C++, i would keep this in mind and get a go at it. i think i get a list of language to learn and go deeper now : Java, C, Perl, Python, Lisp actually i found an article on http://www.tuxedo.org/~esr/faqs/hacker-howto.html#BASIC_SKILLS it recommend the same set as above i mentioned. but i got learning C not C++ this part clear now :) Q. "Qiang.JL" wrote in message news:NAmi8.54548$xG.5157 at news2.bloor.is... > Hi,all > > apologize if this is off-topic :) > > I am a student who have learned perl,java and other like data structure > stuff. Now i want to take some further step to learn one or two languages to > improve my language view. There are two languages are on the list: python > and C++ > I have heard a lot ppl talk about C/C++,saying it's the must language to > learn for a programmer.and i indeed feel so. but C/C++ is hard and may need > to take longer time to learn and get the concept.also, Python seems a good > language and easier to learn. > I think some of you may come cross this, so let me ask you these questions > > do i need to learn C/C++ to be a good programmer? > > which one is better to start with ? ( I'm not a program beginner so python > being a beginner programmer maybe not be applied here) > > How many language do you think one should _master_? I think one or two is > enough.learning others are letting you to learn the language concept and > structure etc certainly helpful. > > > > > > From gerhard at bigfoot.de Thu Mar 21 08:29:16 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 21 Mar 2002 13:29:16 GMT Subject: How to install pychecker? References: Message-ID: Dale Strickland-Clark wrote in comp.lang.python: > I thought I'd try this out. > > In the absence of any instructions (that I can find) I tried unzipping > it to a directory and running setup.py. > > I got this: > > C:\Program Files\pychecker-0.8.10>setup.py > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: no commands supplied > > What am I supposed to do? "python setup.py install", as with every Python package that uses distutils. Or read the comment at the top of the setup.py file ;-) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From mwh at python.net Mon Mar 25 07:08:49 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 25 Mar 2002 12:08:49 GMT Subject: 2.2.1c1 platform experiences References: Message-ID: Michael Hudson writes: > I've attempted to summarise the reports of people using 2.2.1c1 on > various platforms here: > > http://starship.python.net/crew/mwh/221c1-reports.txt I've updated this quite a bit since posting here. You may want to check again. > Can people fill in gaps, confirm/deny rumours, dig into the mentioned > problems? > > It might be best to email me rather than posting to the group, but > I'll see it either way. Cheers, M. -- QNX... the OS that walks like a duck, quacks like a duck, but is, in fact, a platypus. ... the adventures of porting duck software to the platypus were avoidable this time. -- Chris Klein, alt.sysadmin.recovery From l0819m0v0smfm001 at sneakemail.com Tue Mar 12 23:39:08 2002 From: l0819m0v0smfm001 at sneakemail.com (Joshua Macy) Date: Wed, 13 Mar 2002 04:39:08 GMT Subject: frustrated stupid newbie question References: <8B012C611E@kserver.org> Message-ID: <3C8E9E41.3040300@sneakemail.com> Scott Kurland wrote: >>>>>Why isn't this $%^*#$% program working? >>>>> >>>>>#Searching for perfect numbers >>>>> >>>>>howhigh= input ("How high should I check?") >>>>>for number in range (1,howhigh): >>>>> factorsum = 0 >>>>> halfnumber=number/2 >>>>> for checking in range (1,halfnumber): >>>>> if number/checking == int (number/checking): >>>>> factorsum = factorsum + checking >>>>> if number == factorsum: >>>>> print number >>>>> >>>>> >>>Well, I was expecting failure, which we got. What I hoped for was the >>> > two > >>>perfect numbers between 1 and 50, 6 and 28. As others pointed out, you're being bitten both by integer division and range not extending as high as you thought. Change the 2 to 2.0 to force floating point in the division, add 1 to each of the end ranges, and use the modulo operator to do the comparison and it works: howhigh= input ("How high should I check?") for number in range (1,howhigh + 1): factorsum = 0 halfnumber=number / 2.0 for checking in range (1, halfnumber + 1): if number % checking == 0: factorsum = factorsum + checking if number == factorsum: print number How high should I check?50 6 28 On recent releases of Python (2.1+, I believe) you can also add the line: from __future__ import division to your program, which will make division behave the way you were expecting. From Tom_Good1 at excite.com Thu Mar 21 14:30:53 2002 From: Tom_Good1 at excite.com (Tom Good) Date: 21 Mar 2002 11:30:53 -0800 Subject: Pmw.ComboBox label_text param causes error Message-ID: The Pmw ComboBox sample code at: http://pmw.sourceforge.net/doc/ComboBox.html shows label_text as one of the possible keyword arguments to the constructor. However, when I use it I get the error shown below. I'd appreciate assistance in figuring out the problem. PythonWin 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - see 'Help/About PythonWin' for further copyright information. >>> from Tkinter import * >>> import Pmw >>> Pmw.version() '0.8.5' >>> combo = Pmw.ComboBox(None, label_text="foo") Traceback (most recent call last): File "", line 1, in ? File "C:\Python21\lib\Pmw\Pmw_0_8_5\lib\PmwComboBox.py", line 139, in __init__ self.initialiseoptions(ComboBox) File "C:\Python21\lib\Pmw\Pmw_0_8_5\lib\PmwBase.py", line 557, in initialiseoptions raise KeyError, text + string.join(unusedOptions, ', ') + \ KeyError: Unknown option "label_text" for ComboBox >>> From sdm7g at Virginia.EDU Fri Mar 29 19:09:27 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Fri, 29 Mar 2002 19:09:27 -0500 (EST) Subject: Breaking String into Values In-Reply-To: Message-ID: On Fri, 29 Mar 2002, robert garretson wright wrote: > I am working on reading in a data file format which is set up as a series > of lines that look like this: > > 3500035000010104A Foo 45 > > I want to break up into a variables as follows: > a = 35000, b = 35000, c = 10104, d = 'A', e = 'Foo', f = 45 > > My current code (auto-generated from a data dictionary) looks > something like this: > > temp = line[0:5] > a = int(temp) > temp = line[5:10] > b = int(temp) > temp = line[10:15] > c = int(temp) > temp = line[15:16] > d = temp > temp = line[16:20] > temp = temp.rstrip() > e = temp > temp = line[20:23] > f = int(temp) > > with a bit more error checking around the int() calls. > > Is there a better way to do this? The files have around 1000-8000 lines each > so I would like it to be fast. Is there a package around that someone has > coded up as a C-extension to do this? > "better" ? I don't know if it's better, but you can do it more concisely with something like this: >>> a,b,c,d,e,f = [ f(s[i:j]) for i,j,f in ((0,5,int), (5,10,int),(10,15,int),(15,16,str),(16,20,str),(20,23,int))] ( in 2.2 -- earlier versions can do the same in a loop or a map() ) ... probably a bit slower, but more readable I think. Depending on what you're going to do with them, sometimes it makes sense to load them as attributes of a class. I that case you can add the variable names to the list and do a setattr(): class Thing: pass athing = Thing() for name,i,j,f in (('a',0,5,int),('b',5,10,int),('c',10,15,int), ('d',15,16,str),('e',16,20,str),('f',20,23,int)): setattr(athing,name,f(s[i:j]) Sometimes, with data file conversion problems, I will make an intermediate class to represent the abstract object, with methods to load from or dump to the particular representation format. Again -- it's more overhead to do it that way, but I've usually found it worth it in the long run. -- Steve Majewski From emile at fenx.com Tue Mar 5 17:50:21 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 5 Mar 2002 14:50:21 -0800 Subject: Python song? (Re: Python isn't necessarily slow) References: <86n0xmg2q4.fsf@skitty.catseye.net> Message-ID: "Cliff Wells" > Tim Legant wrote: > > Oh, are you from across the pond? It was either Bronski Beat or the > > Communards who did an interesting cover of Ain't Necessarily So in the > > early '80s - I think both groups were Brits.... It's in more of a > > Broadway musical style than country, though. > > It was Bronski Beat (from "Age of Consent"). I don't recall who did the > original. > I'm going bet it's from Porgy & Bess by Gershwin. -- Emile van Sebille emile at fenx.com --------- From claird at starbase.neosoft.com Thu Mar 21 17:37:17 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 21 Mar 2002 16:37:17 -0600 Subject: Evaluation of intellectual products (was: "Zope-certified Python Engineers" [was: Java and Python]) References: Message-ID: <2C63E731EDC3F035.AA755C2524A64090.903E916ECF6E2F43@lp.airnews.net> In article , . . . >[OT: A question I've asked many times and got no answer to is 'why has >nobody done self-consistent ranking for academic papers'? I fear the >answer is simply that most of the data is owned by a small number of >companies who, as a result, have no real incentive to advance the state of >the art. Still, maybe somebody out there is trying to do it...] > > >John > I don't know whether you're not familiar with ISI , or you *do* know them, but intend something different by "self-con- sistent ranking for academic papers". -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From ggerrietts at yahoo.com Mon Mar 4 20:01:19 2002 From: ggerrietts at yahoo.com (Geoff Gerrietts) Date: Mon, 4 Mar 2002 17:01:19 -0800 Subject: chopping a string In-Reply-To: References: Message-ID: <20020305010119.GK1792@isis.gerrietts.net> Quoting David Bear (iddwb at moroni.pp.asu.edu): > there's gotta be an easier way. I have a string > " something somethingelse " > > note the leading a trailing whitespace. I'd like to grab the first > word and strip whitespace. I came up with > > string.join(string.split(string.strip(str))[:1]) > > but I'm thinking, there must be a better way? better means (faster) (smaller).. That's probably what I would use, though if you're in a python that supports string methods, you could do: str.strip().split()[0] or "".join(str.strip().split()[:1]) The latter registers as about 1.33 times faster than (takes 3/4 as long as) the version above; the former is 2 times faster (runs in 1/2 the time). You could maybe do with something with re: string.join(re.split("\s+",str)[:2]) But that won't work if you don't have leading whitespace, and it's slower, if a bit more concise. My timings show 2500 iterations of this at .14 seconds, while the method-based version clocks .06 and your original at .08. Thanks, --G. -- Geoff Gerrietts -rw-rw-rw-: permissions of the beast From duncan at NOSPAMrcp.co.uk Fri Mar 15 09:25:19 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 15 Mar 2002 14:25:19 +0000 (UTC) Subject: does Python support some kind of "casting" References: Message-ID: Tino Lange wrote in news:a6shn9$9l6$1 at crusher.de.colt.net: >> Yes, that will make a copy. But copying a list is a pretty efficient >> operation, so no, it isn't really horribly inefficient. Have you >> tried it and identified this as a bottleneck? How long are your lists >> anyway? > > 3600 Elements each. > > No I didn't check if it's a bottleneck. But I immediately didn't feel > good when writing "return list(newlist)" > (the list contains a list of strings itself - so it's much stuff to > copy) When Python copies your list, it doesn't copy the strings, just adds a new reference to each string. So roughly speaking your list copy involves copying 3600 pointers and incrementing 3600 reference counts. My PC (900MHz pentium) can create (and destroy) 10,000 copies of a list of 3600 strings in about 1 second. It takes about 5 seconds if I save all the intermediate values giving me a list of 10,000 lists. -- 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 James_Althoff at i2.com Mon Mar 11 15:04:34 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 11 Mar 2002 12:04:34 -0800 Subject: PEP 284, Integer for-loops Message-ID: [Hernan M. Foffani] |James, is it too difficult to extend java inherited classes |to behave in a more pythonic tradition way? | |For instance, instead of collection.getCount() have the |chance to use collection.__len__()? | |I guess that is not possible to override a superclass, |right? That's a good suggestion and we like doing that kind of thing when possible. And you *can* define Jython subclasses that inherit from and override Java superclasses -- that being one of the things that makes Jython so usable in a Java environment. Two dimensional collections (e.g., tables) are trickier than one dimensional sequences, however. In such cases __len__ is not well-defined. Jim Althoff Senior Vice President i2 Technologies, Inc. From chris.gonnerman at newcenturycomputers.net Sat Mar 30 01:16:53 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sat, 30 Mar 2002 00:16:53 -0600 Subject: PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> Message-ID: <010101c1d7b2$92c1a7c0$0101010a@local> ----- Original Message ----- From: "Guido van Rossum" > I offer the following PEP for review by the community. If it receives > a favorable response, it will be implemented in Python 2.3. > > ... > > Dear reviewers: > > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. Looks cool to me. > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) "True" sounds best to me. Explicit is better and all that... > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). Proper case is Pythonic (based on existing usage of None, exception names, etc.) > ... > > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. bool. If you've got it, use it. >... > > Some external libraries (like databases and RPC packages) need to > be able to distinguish between Boolean and integral values, and > while it's usually possible to craft a solution, it would be > easier if the language offered a standard Boolean type. This is a VERY good reason IMHO. > The standard bool type can also serve as a way to force a value to > be interpreted as a Boolean, which can be used to normalize > Boolean values. Writing bool(x) is much clearer than "not not x" > and much more concise than > if x: > return 1 > else: > return 0 Yes! I LIKE it. > ... > > There's also the issue (which I've seen puzzling even experienced > Pythonistas who had been away from the language for a while) that if > you see: > > >>> cmp(a, b) > 1 > >>> cmp(a, a) > 0 > >>> > > you might be tempted to believe that cmp() also returned a truth > value. This one bit me in the early days. > ... > > I don't see this as a problem, and I don't want evolve the > language in this direction either; I don't believe that a stricter > interpretation of "Booleanness" makes the language any clearer. Ditto. "Language clarity" has been thrown around as a reason for all kinds of much more invasive enhancements. Python IS clear, and *very* few constructs borrowed from other languages are going to improve it now. Just two reserved words, True and False, in proper case, are not going to break much and just might add some of the clarity that everyone seems to want to add. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From RStephens at viteonline.com Fri Mar 1 13:20:05 2002 From: RStephens at viteonline.com (Ron Stephens) Date: Fri, 1 Mar 2002 13:20:05 -0500 Subject: Black Adder and piquet Message-ID: <2B69DFB47D76D3118B0100A0C9DED182010FB900@vi_nor_mail.vectron.com> Thank you. If you do find the documentation you worked on, I would be glad to have it and maybe I can add to it. Thanks Ron Stephens > -----Original Message----- > From: Wayne Pierce [SMTP:wayne at mishre.com] > Sent: Friday, March 01, 2002 1:06 PM > To: Ron Stephens > Cc: python-list at python.org > Subject: Re: Black Adder and PyQt > > > Ron Stephens wrote: > > I am thinking of buying a "home" license of Black Adder, to use for > > making GUI's for Python programs to be used on Linux+KDE and also > > perhaps for the new Sharp Zaurus. Does anyone have any experience with > > Black Adder that they can share? One of my main reasons for wanting > > Black Adder is to use the GUI builder, so I am particualrly interested > > in opinions about that aspect of Black Adder, but I am also interested > > in other aspects as well. > > I really like the GUI builder of BA, unfortunately I think it could use > more work. Granted it is __still__ in beta, but it's been in beta for > quite a while without an update. When I do GUI development I typically > do the first part in BA, then manually add in the GUI pieces that BA > doesn't support directly yet (like menus). > > The only thing I don't like about the GUI builder is that it doesn't > support a lot of widgets yet. The last I heard they were waiting for Qt3. > > > One question I have concerns licensing. If I buy the "home" version, > > could I still share my programs as GPL'ed open source, or would that > > require me to buy the "professional" license, which is much more > > expensive? In other words, my programs would never be used in any > > commercial way but I might want to post them as open source, free > > software. > > As I understand it, the only restriction on redistribution is if you are > distributing commercial apps. Then you need the business edition to > redistribute Qt and the other modules. It might be good to get the > scoop directly from them on this since I got the business edition and > haven't had to worry about it. > > > I know Black Adder is still in beta, but is it stable enoough to use > > already? I suppose I should ask how it compares to PythonWare amd > > WingIDE, but I kind of favor the PyQt toolkit becuase it will > > hopefully work well on the Sharp Zaurus as well as the KDE desktopI > haven't had too many problems with BA's stability; typically I use BA > for the GUI design and syntax highlighting then compile and test in a > shell. I've had some lockups when using the run from within BA in the > past, not all the time but I was never able to figure out what would > cause it so I just skipped it all together. > > The documentation could use some work, most of the PyQT docs are in C++ > and can take some fiddeling to get right. At one point I started to do > some documentation for BA to give to some coworkers, if I can find it > you are welcome to it (they decided to stick with Perl, so I never had > to finish it). > > They have a mailing list (somewhere) for BA discussions, I forgot what > the address is and had it sent to an address I no longer have access to. > :( If you do purchase BA, I would say skip the support and the option > to receive CDs. In the time that I have had the program there hasn't > been an update, the support is so-so and they haven't ever sent a CD. > > Even with all of that BA is usually the second program I open when I do > Python development (the shell is first). The feature I like most is the > ability to collapse code blocks. > > Wayne > -- > Wayne Pierce > web: http://www.mishre.com > email: wayne at mishre.com > > "What you need to know." From olc at ninti.com Sun Mar 31 07:08:12 2002 From: olc at ninti.com (Michael Hall) Date: Sun, 31 Mar 2002 21:38:12 +0930 (CST) Subject: long integers Message-ID: G'day: I'm using Python 1.5.2 and am having trouble with long integers when I pull data out of a MySQL database using MySQLdb. When I retrieve a numeric value from a field with an `int' data type, the value has an `L' stuck on the end. In one script, I worked around this by stripping the L off with: var = numeric_id # ("2L") var = var[:-1] print var >> 2 In this case, numeric_id was passed through a hidden field in an HTML form. But this doesn't work in another script for some reason, where the value is passed straight from a database query. I tried converting the data type from number to string, but that doesn't work either: var = result[0] # ("2L") var = 'var[:-1]' print var >> var[:-1] So now I'm confused. I don't yet know enough Python to know what to try now. Is there some easy way around this problem? Can this be fixed in MySQL by changing or modifying the data type, or should I upgrade to a later version of Python? Thanks Mick ----------------------------- Michael Hall mick at ninti.com ----------------------------- From phil at river-bank.demon.co.uk Fri Mar 22 13:21:20 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Fri, 22 Mar 2002 18:21:20 +0000 Subject: PyQt installation problems on windows References: <20020322164756.46454.qmail@web11302.mail.yahoo.com> Message-ID: <3C9B7620.6C239B08@river-bank.demon.co.uk> Amit Mongia wrote: > > Hi, > I have installed Python 2.2 , on my computer. I > created a gui using Qt Designer and used pyuic to make > a python file out of it. > Now i want to run that file using the python > interpreter. Whenever i try doing that it gives an > error: > > Traceback (most recent call last): > File "WrapperInterface.py", line 10, in ? > from qt import * > File "F:\PYTHON22\lib\qt.py", line 44, in ? > import libqtc > ImportError: DLL load failed: One of the library files > needed to run this applic > ation cannot be found. > > I even tried all the py and pyc file from PyQt/lib > folder to Python22/lib folder and the same with the > Dll files. but it still gives the same error. Can > anyone offer a solution for this on windows. What version of PyQt? What version of Qt? Is libqtcmodule.pyd in F:\python22\dlls? Is sip.dll (assuming you are not running a PyQt v3.1 pre-release version) installed in a directory that is on your path? Phil From martin at v.loewis.de Fri Mar 8 04:07:19 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 08 Mar 2002 10:07:19 +0100 Subject: undefined symbols when linking Python into a shared library References: <3C8540B5.E133D407@freenet.de> <3C88031B.8A0FB866@freenet.de> Message-ID: Michael Neuroth writes: > Thank you for the tip, now I can see, that the 'missing symbol' is > exported from the shared library: > > 000a7bac D _Py_NoneStruct > > Is there any difference for exported (data) symbols, when loading > a shared library with dlopen() instead of linking it 'statically' while > creating the program file? Certainly: If a symbol is missing in a program, the program cannot resolve that symbol from a library opened through dlopen: For that to work, the program would need to start executing. It cannot execute if it has missing symbols. > That is true of course. Is there any possibility to create a shared > libraray for Python: libpython.so instead of libpython.a? Not currently. On SF, there are a number of patches that provide this facility. To get PIC objects, setting CFLAGS may be sufficient. Regards, Martin From eppstein at ics.uci.edu Thu Mar 7 16:47:49 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 07 Mar 2002 13:47:49 -0800 Subject: PEP 284, Integer for-loops References: <3c87d103.26130283@news.laplaza.org> Message-ID: In article <3c87d103.26130283 at news.laplaza.org>, mats at laplaza.org (Mats Wichmann) wrote: > If you'e going on to teach Python, you'd tell 'em those can of course > be combined. I don't want to teach Python. I want to teach other stuff. Python is close to an ideal language for this purpose: easy to just start using without spending a lot of time teaching it, easy to express algorithms as actual debugged working code without all the overhead of C/C++/Java (the other logical choices of languages, that the students already know). But there are a few warts in the design, where instead of just using Python I have to stop and explain some unnatural unintuitive syntax. Multi-parameter range() is one of those warts. From jeff at ccvcorp.com Fri Mar 1 16:18:14 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 01 Mar 2002 13:18:14 -0800 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> Message-ID: <3C7FF015.D1A00D13@ccvcorp.com> Robert Amesz wrote: > On Win98 I've found I had to quote *and* escape the quote characters, > and - sometimes - backslashes too. I'm not sure if this is also the > case on Win2000, but it's worth a try. This would yield something like: > > '\\"c:\\\\program files\\\\dimbo\\\\bongo.exe\\\\" \\"c:\\\\program > files\\\\dumbo\\\\my file.dat\\"' > > Horrible, I know. This is why raw strings exist. >>> mystring1 = '\\"c:\\\\program files\\\\dimbo\\\\bongo.exe\\\\" \\"c:\\\\program files\\\\dumbo\\\\my file.dat\\"' >>> print mystring1 \"c:\\program files\\dimbo\\bongo.exe\\" \"c:\\program files\\dumbo\\my file.dat\" >>> mystring2 = r'\"c:\\program files\\dimbo\\bongo.exe\" \"c:\\program files\\dumbo\\my file.dat\"' >>> # note! ^ the 'r' here! >>> print mystring2 \"c:\\program files\\dimbo\\bongo.exe\" \"c:\\program files\\dumbo\\my file.dat\" >>> Note that you've got an extra backslash in your version -- you want a single escaped double quote after 'bongo.exe', not an escaped backslash followed by an unescaped double quote. Raw strings will save you much pain. Jeff Shannon Technician/Programmer Credit International From calves at coelce.com.br Mon Mar 11 13:07:03 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Mon, 11 Mar 2002 15:07:03 -0300 Subject: ENC: lambda question Message-ID: <29A97D00F387D411AC7900902770E148044AB531@lcoeexc01.coelce.net> See the error below: >>> def exe1(f,list): return map(lambda x:eval(f),list) SyntaxError: local name 'f' in 'exe1' shadows use of 'f' as global in nested scope 'lambda' (, line 1) >>> > -----Mensagem original----- > De: Bertrand Geston [mailto:bergeston at yahoo.fr] > Enviada em: segunda-feira, 11 de mar?o de 2002 14:46 > Para: python-list at python.org > Assunto: Re: lambda question > > > lambda questionBoth work on my computer: > > PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit > (Intel)] on win32. > Portions Copyright 1994-2001 Mark Hammond > (mhammond at skippinet.com.au) - see > 'Help/About PythonWin' for further copyright information. > >>> def exe1(f,list): > ... return map(lambda x:eval(f),list) > ... > >>> f='x**3+2*x' > >>> list=[0,1,2,0] > >>> map(lambda x:eval(f),list) > [0, 3, 12, 0] > >>> exe1(f,list) > [0, 3, 12, 0] > >>> > > If you give us the kind of error, problem hou have, you will > help us to help > you. > TIA ;-) > > "Alves, Carlos Alberto - Coelce" wrote > in message > news:mailman.1015866267.21439.python-list at python.org... > Hi all, > Look at the two codes below > first code: > f='x**3+2*x' > list=[0,1,2,0] > map(lambda x:eval(f),list) > second code: > def exe1(f,list): > return map(lambda x:eval(f),list) > Can someone explain to me why the first code works while > second doesn't. > Carlos Alberto > COELCE/DPRON-Departamento de Projetos e Obras Norte > Fone: 677- 2228 > e-mail: calves at coelce.com.br > \|||/ > (o o) > --ooo0-(_)-0ooo-- > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bergeston at yahoo.fr Mon Mar 11 08:00:19 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Mon, 11 Mar 2002 14:00:19 +0100 Subject: newbie needs help with tkinter References: <1Myi8.13667$%d1.409160@twister2.libero.it> Message-ID: Beeing newbie myself, I played with you code, here is the result: ----------------------------------------------------------- from Tkinter import * class Application(Frame): def __init__(self,master=None): Frame.__init__(self,master) menubar=self.addmenubar() master.config(menu=menubar) w=Label(self,fg="green",text="*") self.pack() w.grid() def addmenubar(self): menubar=Menu() filemenu=Menu(menubar) menubar.add_cascade(menu=filemenu,label="File") filemenu.add_command(label="Configura", command=self.configframe) filemenu.add_command(label="Lavora") return menubar def configframe(self): self.config(bg="yellow") w=Label(self,fg="blue",text="prova") w.grid() self.update_idletasks() print "hello!" #main root=Tk() applicazione=Application(root) root.mainloop() ----------------------------------------------------------- "Sacchi" wrote in message news:1Myi8.13667$%d1.409160 at twister2.libero.it... > I've just learned the main rules of python(I already knew both java and > C). Now I'm trying to get something out of Tkinter, but while running > this sample program (made by myself) I encountered a problem. I wanted > that by clicking on the "configura" command under the "File" menu the > frame would get yellow and that a label would appear on it. The > function works(the line "print "hello!"" gets executed) but the gui > window doesn't change. I even tried to use the widget redraw methods > but with no success... anyone can help me please? > > Thanks in advance > Marco > > --------- Program Code ---------------------- > > from Tkinter import * > > class Application(Frame): > > def __init__(self,master=None): > Frame.__init__(self,master) > menubar=self.addmenubar() > master.config(menu=menubar) > menubar.mainloop() > > def addmenubar(self): > menubar=Menu() > filemenu=Menu(menubar) > menubar.add_cascade(menu=filemenu,label="File") > #these lines got shifted by the newsreader program, but all belong to > #the addmenubar function > filemenu.add_command(label="Configura"command=self.configframe) > filemenu.add_command(label="Lavora") > return menubar > > def configframe(self): > self.set(bg="yellow") > w=Label(self,fg="blue",text="prova") > w.grid() > self.update_idletasks() > print "hello!" > > #main > > root=Tk() > applicazione=Application(root) > root.mainloop() > -- > ----------------------------------------------------- > remove "nospam" from email address to answer > ----------------------------------------------------- From mlh at vier.idi.ntnu.no Mon Mar 11 22:44:13 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Tue, 12 Mar 2002 03:44:13 +0000 (UTC) Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> <4abd9ce7.0203101059.444f1ec1@posting.google.com> Message-ID: In article <4abd9ce7.0203101059.444f1ec1 at posting.google.com>, damien morton wrote: [snip] >> No. That is NOT a good reason to change a language in an inconsistent way. > >The 'in' operator is now a verb that can be defined to mean pretty >much any function with two arguments. Well, yes, it could be made to print out both its arguments, for instance, but why would that be a good idea? It is (in the main language and standard libraries) as a container membership operator. Using it as something else is possible, but seems like a strange thing to do -- and to suggest such a change in parts of the language itself is even stranger. >It cant be a set membership operator because python doesnt have sets. Yet. There is a PEP on the way, and the membership operator will certainly function in the expected way there as well. > The issue at stake is that its meaning should be well understood. Yes. > Strings are like sequences in that their individual elements > (characters ONLY) can be accessed as a sequence, but there are > important differences in the kinds of things people want to do with > strings. What do you mean? In Python (and all programming languages I can think of at the moment) strings are sequences. I think "a sequence of characters" is a reasonable model of a string (since the word "string" means "(1) a series of things arranged in or as if in a line, (2) a sequence of like items"). It seems that you are suggesting that strings are to be modelled as "a set of substrings" or something. >From the persepective of an english speaker, the the string 'fox' is >IN the string 'the quick brown fox'. No it isn't. It's in the *phrase* 'the quick brown fox', which isn't a sequence of characters, but a sequence of *words*. What you're looking for is 'fox' in 'the quick brown fox'.split() Or, if you insist that 'ox' is IN the string 'fox' (with 'in' meaning 'is a part of'), wouldn't you also say that the sequence 3, 4, 5 can be found IN the sequence 1, 2, 3, 4, 5, 6? But would you say that this interpretation of the word 'in' should be used in Python? That would make things very ambiguous: >>> (3, 4, 5) in (1, 2, 3, 4, 5, 6) 1 >>> (3, 4, 5) in (1, 2, (3, 4, 5), 6) 1 > Under the covers, the IN operator is defined as the __contains__ > function. Method, actually. > Clearly, the string 'the quick brown fox' CONTAINS the string 'fox'. As a substring, yes. As an element, no. The string 'fox' cannot be said to be a member of the string 'the quick brown fox'. > I think the verb IN means something slightly different for strings > than it does for sequences and dicts. What about sets? A set certainly CONTAINS a subset -- do you think the membership operator should be used as a subset operator in the upcoming set type? In that case, what should be used as a membership operator? Or perhaps you think it should be used as both, making things ambiguous? > Check this out: > > ('fox' in 'the quick brown fox') > ('the quick brown fox'.find('fox') != -1) > > Which of these expressions is clearer, more intuitive and > convenient? Are you saying that making one sequence behaving unlike all others is clear and intuitive? It may be 'convenient', but that's a common and dangerous trap. Just to poke another hole in your suggestion -- what would the following code produce? for x in 'the quick brown fox': print x If you want the members of the string to be words, it should produce the quick brown fox If you want to include all substrings, it should produce t th the ... the quick brown fox h he he q he qu Etc. And how would you number the elements? If s is the string above, should s[0] be 'the' or ''? Or perhaps it should be 't', making the proposal thoroughly self-inconsistent? -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From mwh at python.net Tue Mar 12 04:45:25 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 12 Mar 2002 09:45:25 GMT Subject: python and haskell for fun References: Message-ID: Christopher Browne writes: > I'd love to see Vyper go further; it's a neat approach to the > "wouldn't it be neat to static type Python?" question. Well, I'm half of the vyper developers on sf. I think the only check-in I've made was to add a .cvsignore file. > The thing that seemed particularly neat was the way it added in > ML-style pattern matching. > > I have a feeling that what has happened isn't so much that people > started farting in the author's general direction ("your mother smells > like elderberries!"), but that it was a one man show, and that nobody > really took interest in it. I think what happened was that he got a job. I'm *interested* in it, but I don't even have time to keep up with the bug reports against Python . > In effect, it may be just like most of the SourceForge projects that > get started up by someone that thinks they have an idea, but who never > get around to any usable degree of completion. Vyper is usable, although I don't know whether it works with the latest releases of ocaml. It just doesn't offer any real advantages over CPython. It's also quite a bit slower. If people want to pick it up, the code's there, and I'm sure John could be persuaded to give you developer status... Cheers, M. -- CLiki pages can be edited by anybody at any time. Imagine the most fearsomely comprehensive legal disclaimer you have ever seen, and double it -- http://ww.telent.net/cliki/index From peter at engcorp.com Sun Mar 31 09:11:56 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 09:11:56 -0500 Subject: relational database? References: <5yEp8.5051$hi7.18667@news-server.bigpond.net.au> Message-ID: <3CA7192C.E1C8974A@engcorp.com> Trung Hoang wrote: > > "Martin v. Loewis" wrote in message > news:m3eli1m2dt.fsf at mira.informatik.hu-berlin.de... > > "Trung Hoang" writes: > > > > > What relational database is easy to setup and use with python? > > > > Gadfly. It is a pure-Python database, and requires little > > administrative interaction. It does not provide good performance, > > though... > where can i get this ? Try Google? From fperez528 at yahoo.com Fri Mar 15 10:09:44 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 15 Mar 2002 15:09:44 +0000 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: John Roth wrote: > > Putting something into the start menu is dead easy. Just put a > link to the appropriate file into "c:Windows/Start Menu/Programs" > Note the blank, and watch your capitalization. Windows is > flaky about capitalization. > This is only for win9x. Win2k/xp have per-user Start Menu dirs, and their location must be retrieved from the registry (Def. is C:\documents and settings\user-name\Start Menu, but it can vary). So to have this be reliable, there's no way around diving into the pleasures of the registry. f. From mwh at python.net Sat Mar 9 11:31:23 2002 From: mwh at python.net (Michael Hudson) Date: Sat, 9 Mar 2002 16:31:23 GMT Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> <3C88E7B4.A910D281@earthlink.net> <7xvgc6k6ja.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Michael Hudson writes: > > The combination of lazy evaluation and non-functional semantics are > > only good for creating confusion. > > > > functional non-functional > > strict ml python > > lazy haskell brrr > > What do xrange, xreadlines, etc. do, if not lazy evaluation? I was talking about lazy (or to be accurate, non-strict) evaluation as being a property of the language. In Haskell-talk a function is strict if it evaluates to bottom when applied to bottom (here "bottom" is the "result" of evaluating an invalid expression, say a non-terminating loop or 1/0). See here for more info: http://www.haskell.org/tutorial/functions.html#sect3.3 This concept doesn't really exist in Python because all functions -- including xrange, xreadlines & co -- are strict in all arguments. Cheers, M. -- There's an aura of unholy black magic about CLISP. It works, but I have no idea how it does it. I suspect there's a goat involved somewhere. -- Johann Hibschman, comp.lang.scheme From mhammond at skippinet.com.au Sat Mar 16 21:03:55 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 17 Mar 2002 02:03:55 GMT Subject: Help with a Python ASP C extension module ... References: <40ee0487.0203152316.70c12a49@posting.google.com> Message-ID: <3C93F993.3010109@skippinet.com.au> Eric Vasilik wrote: > I am writing a C extension to Python. The reason I am writing an > extension is that I believe that the implementation of > Response.BinaryWrite() in the Window's ASP extension (I am using > Active State's Python 2.1) is not releasing the global interpreter > lock. I am almost certain that it does. All COM calls release the GIL. Response is an IDispatch object. This means that the call is made via either PyIDispatch::Invoke, or PyIDispatch::InvokeTypes. These release the lock. > I am getting very poor performace using it and I believe that > my server is not taking advantage of writing out multiple streams > because of the global lock. I am not sure what makes you believe Reponse.Write is to blame. It is more likely that another Python thread is "busy" somewhere other than Response.Write or fileIO. > Instead of writing out a response with: > > Response.BinaryWrite( buffer( open( fileName, 'rb' ).read() ) ) > > I am now doing the following: > > PythonExt.binaryWriteFile( Response, fileName ) OK - but don't be surprised if you see pretty much the same thing. You are removing a little Python overhead, but not alot. > The difference between these two is that the first calls the default > implementation of Response.BinaryWrite and the second calls an > extension I have written which reads the file and writes it out to > response, all while the interpreter lock is released. The former Python version will do all the significant work (ie, the file open, read and response.write call) with the lock released too. Some of the IDispatch mechanics will be avoided though, as will the multiple lock transitions involved in the Python version. > My problem, is I cannot find any documentation on how to get a hold of > the IResponse object from the Python Response object. I need to get > it so that I may call BinaryWrite on without going back into the > Python interpreter. Going via IResponse should speed things up a tiny bit too. Basically, the "Response" object is a class instance, and the attribute "_oleobj_" is the PyIDispatch object. So you need something like: if (!PyArg_ParseTuple("Os", &pyResponse, &filename)) ... PyObject *pydisp = PyObject_GetAttrString(pyResponse, "_oleobj_"); if (!pydisp) ... // now get the object. if (!PyCom_InterfaceFromPyObject(pydisp, IID_IRESPONSE, (void **)&pResponse, FALSE /* None is not valid */ )) ... Py_DECREF(pydisp); ... use pResponse pResponse->Release(); Using PyCom_InterfaceFromPyObject() means you will need to include pythoncom.h, and link against pythoncomxx.lib - which means you will need to build pythoncom from sources - see http://starship.python.net/crew/mhammond/win32/BuildingExtensions.html Mark. From jar at mminternet.com Wed Mar 13 00:29:50 2002 From: jar at mminternet.com (James A Roush) Date: Tue, 12 Mar 2002 21:29:50 -0800 Subject: Converting relative URLs to absolute Message-ID: Does anyone have any code that, given that absolute URL of a web page, can convert all the relative URLs on that page to their absolute equivalent? -- ----------------------- James A Roush jar @ mminternet.com ----------------------- From klaatu at evertek.net Wed Mar 13 16:46:30 2002 From: klaatu at evertek.net (Mike Dean) Date: Wed, 13 Mar 2002 15:46:30 -0600 Subject: Python on Windows soon forbidden by Micro$oft? In-Reply-To: ; from rasmussn@lanl.gov on Wed, Mar 13, 2002 at 09:10:45AM -0700 References: Message-ID: <20020313154630.B12827@evertek.net> * rasmussn at lanl.gov [2002-13-03 09:10]: > After all, the GPL forbids linking GPL code with non GPL code, i.e. > MS libraries. At least I think so from reading the GPL FAQ > (http://www.gnu.org/licenses/gpl-faq.html). For example, in answer to > > I am writing free software that uses non-free libraries. What legal issues > come up if I use the GPL? > > [quote from the GNU GPL faq] > > Since VC++ is not normally distributed with the operating system, I would > assume > that MS VC++ libraries are not compatible with GPL code. But the core MS VC++ libraries are distributed with Windows 98 and higher, and are at least commonly available on virtually all Windows systems (Unless a system is very old and isolated, it probably has some version of msvcrt.dll on it, as well as mfc42.dll). As I see it (though I'm no lawyer, let alone copyright law expert), the restrictions become A., if the PythonLabs team upgrades to a newer version of Visual C++, they can no longer distrubute updated runtimes with Python, and B., people cannot use newer versions of Microsoft tools to develop multi-language products involving Python or any other open source software, and distribute runtimes with that (which basically outlaws creating VB-Python combination programs). And one cannot use open-source tools to build any part of an application that will have Microsoft runtimes distributed with it. But that's just my $.02 - correct me if I'm wrong on anything please! -Mike > > Now I should rush to point out that I don't know this to be the reason > for Microsoft's license, I'm just wondering. Anyone more familiar with > the law in this area care to comment? > > Craig > > > > -- > http://mail.python.org/mailman/listinfo/python-list From tim.one at comcast.net Mon Mar 11 14:31:08 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 11 Mar 2002 14:31:08 -0500 Subject: round() function strange behaviour In-Reply-To: Message-ID: [brobbins333 at shaw.ca] > I understand and agree with what you are saying. However,it is > possible in some languages (VB, for example) to return a numerical > result from a function with only two (or any other number) of decimal > places. The VB Currency type is a 64-bit signed integer under the covers, implicitly scaled by 10,000. That's similar to a FixedPoint(4) if you use my FixedPoint.py class, although a FixedPoint(4) has no restriction on the magnitude, while a VB Currency value is restricted to the range -922,337,203,685,477.5808 <= Currency <= 922,337,203,685,477.5807 You should re-read the responses you've gotten, because they're exactly on target. The details are everything here. From jason at jorendorff.com Mon Mar 11 01:37:57 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 11 Mar 2002 00:37:57 -0600 Subject: Getting stdout and stderr from popen In-Reply-To: Message-ID: Stefan Heimann wrote: > f = os.popen('cvs status 2>&1') > does the right thing, but does not work on all platforms. I'm sure it doesn't work on *all* platforms, but it works for me on Windows 2000. I'm sure someone here knows the details on this; I don't. Give it a try. ## Jason Orendorff http://www.jorendorff.com/ From gleki at gol.ge Tue Mar 5 17:26:11 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Tue, 05 Mar 2002 14:26:11 -0800 Subject: Can Python do this? References: Message-ID: <3C854603.8F567948@gol.ge> Hi! Can you tell me little bit more why is this a bad idea to use exec/eval? Where can I find more information? Thank you in advance. Greetings, Giorgi Gerhard H?ring wrote: > Le 04/03/02 ? 12:51, Robert Oschler ?crivit: > > Hello, Python newbie here. > > > > Let's say I'd like to build a method name into a string variable (e.g. > > "FuncCall" + "1" to attempt to call "FuncCall1"). Can I then call that > > method by somehow having the interpreter evaluate the string variable into a > > call to the desired method? (I know this is usually done in a language like > > Prolog or Lisp but I'm hoping Python can do it too.) > > This can easily be done with the built-ins eval and exec. But in 99 % of > all cases, it's a really bad idea to use them. Perhaps you can tell us > what you're trying to accomplish anyway? There's usually a better way > than (ab)using eval/exec. > > Gerhard > -- > This sig powered by Python! > Au?entemperatur in M?nchen: 5.7 ?C Wind: 2.1 m/s From sumner-nntp5 at forceovermass.com Mon Mar 11 13:12:04 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Mon, 11 Mar 2002 18:12:04 GMT Subject: should i learn it first ? References: Message-ID: In article , Bengt Richter wrote: > On Sun, 10 Mar 2002 17:13:17 GMT, "G. Sumner Hayes" wrote: > >>In article , Bengt Richter wrote: >>Ugh, I can see learning Python first but definitely learn C before >>C++. In that order, you won't have to unlearn patterns of design >>you absorb solving problems with C++. >> >>Seriously, the point of using a low-level language like C or C++ >>is to get next to the hardware, and it should be learned from that >>level first IMO. Otherwise, stay with a more productive language >> like Python. >> > If you are just going to use the low level stuff (unless you are > talking about assembler within C++), you might as well use C. Exactly my point. > ISTM C++ was designed to let you *build* "levels" with layers of abstraction > through objects and generics. And IMO it's a really bad language for _learning_ those techniques. Learn Python and C first, get a clean understanding of C, and then learn C++ if you need to for pragmatic reasons. > IOW, one group can work at low level > to produce elements that others can use at high level. E.g., instatiating > an mp3-playing object and calling the play method is pretty trivial and high level, > yet the same C++ language can be used to write the guts of almost everything involved. Sure, you can write that object in C or even asm and have a high-level interface. If an OO approach is warranted for the problem at hand, C++ offers more language support for that programming style than C, but by that point you should really be thinking hard about whether either language is appropriate. Seriously, C++ was designed with backwards compatibility as a primary goal and not as a clean OO (or otherwise) language. The language itself (not incl. the library) is huge, has a lot of warts, and is in my experience prone to confuse beginning programmers and give them bad habits that are tough to shake later. > If you really want to get intimate with the[1] hardware, even C is > mostly isolating you from true carnal knowledge. Get an assembler[2], > and choose every instruction and every data location and access thereto. Right, that's why I listed "some platform's assembler" as one of the 4-5 first languages a beginning programmer who wants to master the craft should learn (along with "some statically typed functional language" (e.g. OCAML, Haskell), "some high-level dynamic OO language (e.g. Python, Ruby), C (as _the_ systems language and the basis for many other language implementations), and possibly a dynamic functional language (Lisp) or a declaritive language (Prolog) to expand the mind). > [2] OTOH, you'd be surprised what level chunks you can build with macros > in a good macro assembler. esp. Borland Object-Oriented Turbo Assembly. Double ugh. >>> If you start with C, you will get used to a procedural way of looking >>> at problems, and when you get to C++ you will be tempted to see it >>> as just C with extra features. You'll have to dislodge yourself from C >>> habits of thinking in order to "think objects" in C++. Coming from >> >>Conversely, if you learn in the other order you'll find yourself thinking >>of it as a limited version of C++ instead of a different language with >>its own idiom. The point of C is that it's procedural, small, and close >>to the metal. Viewing without the corrupting lens of C++ is extremely >>valuable, IMO. >> > I don't know what you mean by "corrupting lens of C++," > other than a rhetorical counter point ;-) Rephrase as "learn C without having the C++ way stuck in your head, but take it as a small procedural language that gets you deep inside details about memory management and data type implementation". > But even if you just want to learn C, you can largely use C++ as if > it were C. But the point of C is that it's very small (relative to C++) and much easier to get a handle on. If you need to figure out which subset of the language to use, you miss the whole point. C++ is big, gross, and useful. For real-world problems, the useful part is very important, but I personally think it's a really bad language to start out in until well after learning OO techniques and C-style procedural coding. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From pereira at cis.upenn.edu Sat Mar 2 12:20:04 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Sat, 02 Mar 2002 12:20:04 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: On 3/2/02 10:53 AM, in article mailman.1015084565.2836.python-list at python.org, "Paul F Dubois" wrote: > I also see the underflow problem on my Linux box 2.4.2-2. This is > certainly untenable. However, I am able to catch OverflowError in both > cases. I had a user complain about this just yesterday, so I think it is > a new behavior in Python 2.2 which I was just rolling out. It's not Python 2.2 itself: % python Python 2.2 (#1, Feb 10 2002, 13:29:43) [GCC 2.95.2 19991024 (release)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 -- F From geiseri at yahoo.com Wed Mar 27 13:33:37 2002 From: geiseri at yahoo.com (ian reinhart geiser) Date: Wed, 27 Mar 2002 13:33:37 -0500 Subject: interactive python shell Message-ID: <200203271333.38160.geiseri@yahoo.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Greetings I have an python application and I would like to provide a "console" in the application where users can have an interactive session with python that has all of the applications enviroment. This is for debugging the system in real time. Is there an easy way to do this? All it needs to do is execute commands and return data. I am using PyQt for my GUI, so it would be cool to fit into there, but I can get away with a input line and a display view if that is easier. This is not for production, only to make a more useful debug tool. TIA - -ian reinhart geiser -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE8ohCCPy62TRm8dvgRAvmSAKC/uf7E2UBG1Y+d33YXnK5KqUUavQCaAsv0 fMcYLvKXoPtl8pKj+XXuefs= =7Lv1 -----END PGP SIGNATURE----- _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From quinn at barf.ugcs.caltech.edu Mon Mar 4 16:08:05 2002 From: quinn at barf.ugcs.caltech.edu (Quinn Dunkan) Date: 4 Mar 2002 21:08:05 GMT Subject: Can Python do this? References: <7xvgccm5f5.fsf@ruckus.brouhaha.com> Message-ID: On 04 Mar 2002 12:41:50 -0800, Paul Rubin wrote: > x = my_class() # x is an instance of some class > method_name = "FuncCall" + "1" # gives "FuncCall1" > method = getattr(x, method_name) # find the method > method (args) # call the method > >is preferable to using eval, if method_name is actually defined for >my_class. However, if method_name is only defined for some class that >my_class inherits from, and not from my_class itself, then this won't >work. Really? Python 2.0 (#1, Oct 25 2000, 13:33:13) [GCC 2.8.1] on irix6-n32 Type "copyright", "credits" or "license" for more information. >>> class A: ... def m(self): pass ... >>> class B(A): ... pass ... >>> a = B() >>> a <__main__.B instance at 100e3f14> >>> a.m >>> getattr(a, 'm') >>> Or did you mean something else? From greg at cosc.canterbury.ac.nz Wed Mar 6 21:15:50 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Mar 2002 15:15:50 +1300 Subject: Status of PEP's? References: Message-ID: <3C86CD56.F8D213A@cosc.canterbury.ac.nz> James_Althoff at i2.com wrote: > > [Andy Gimblett] > > This just came to me: > > > > for index in indices(items): > > pass > > > > or maybe better yet: > > > > for index in items.indices(): > > pass > > Warning: the latter could get you into trouble with the "methods are > overrated" crowd . It would also preclude doing smart things like using the __len__ of an object if there wasn't a more specific method available. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From martin at v.loewis.de Sun Mar 3 15:44:49 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 03 Mar 2002 21:44:49 +0100 Subject: Newbie question References: <3c810efa.475638531@mammoth.usenet-access.com> Message-ID: netzapper at magicstar.net (A. Jones) writes: > What is the function that forces conversion to a three-quote string? > > I need to save a string that has a LOT of \n's in it, and need to save > both the formatting and the \'ns. > > I checked the manuals (and the online lists of functions), and all I > came up with was str(), which doesn't do the tripple quote. It doesn't need to generate triple quotes, because it will do the escaping of \n correctly. If you want to output a string in Python source format, but using triple quotes, I believe you have to implement this yourself. Regards, Martin From martin at v.loewis.de Sat Mar 30 06:37:42 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 12:37:42 +0100 Subject: [Python-Dev] RE: PEP 285: Adding a bool type In-Reply-To: References: Message-ID: Tim Peters writes: > > How will bool influence '__nonzero__'? Currently, Python insists that > > '__nonzero__ should return an int'. Will this be changed to 'should > > return a bool'? > > I hope so. > > > As that would break existing code, I hope not. > > No, "should" != "must". Guido won't call code that returns an int here > broken, although he might call it deprecated, and leave you wondering when > the hammer will drop . Interestingly enough, the exception message says "__nonzero__ should return an int" but really means "__nonzero__ must return an int". I guess under this PEP, the message needs to be changed to "should return a bool", but not the test (or, if you want it more explicit: "__nonzero__ must return an int and should return a bool" :-) Regards, Martin From Gabe.Newcomb at noetix.com Tue Mar 26 11:59:29 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Tue, 26 Mar 2002 08:59:29 -0800 Subject: Python Books Galore Message-ID: <0C7CA8D8DF75494EB09AB6016990107F011B186D@NOXMAIL.noetixad.com> Aye aye! I was thinking of writing a message like this myself. I can't believe what our options are like now. I'm still looking forward to a printed Python Cookbook-type-deal. Gabe In article , "Raymond Hettinger" wrote: [snip] > I went back yesterday and found a full row (3 1/2 to 4 feet) filled with > Python books. [snip] > This has got to be a good sign. -- http://mail.python.org/mailman/listinfo/python-list From garyr at fidalgo.net Fri Mar 29 21:31:56 2002 From: garyr at fidalgo.net (Garyr) Date: Fri, 29 Mar 2002 18:31:56 -0800 Subject: Program termination problem References: Message-ID: Thanks for your replies. The Tkinter selection_get(selection='CLIPBOARD') code works fine but the program still hangs when invoked from a DOS window but does terminate OK when invoked from an icon. "Garyr" wrote in message news:ua6r509m5uradc at corp.supernews.com... > I have a program that displays a Tkinter Text widget. I would like to be > able to place text in the window via the clipboard. I found the following > clipboard code in a Google post: > > import win32clipboard as clip > ... > clip.OpenClipboard(0) > if clip.IsClipboardFormatAvailable(clip.CF_TEXT): > newText = clip.GetClipboardData(clip.CF_TEXT) > textwidget.insert(END, newText) > clip.CloseClipboard() > > This works but it causes the program to hang on exit. mainloop() returns but > the DOS window is frozen. The problem is associated with the clipboard > functions; i.e., commenting the insert line has no effect. > > I'm using Python 2.1 (Pythonwin 2.1.211) on Win98. > Any suggestions? > > Thanks in advance, > Gary Richardson > > From andy.mckay at merlinsoftech.com Wed Mar 6 19:56:23 2002 From: andy.mckay at merlinsoftech.com (Andy McKay) Date: Wed, 6 Mar 2002 16:56:23 -0800 Subject: Python on W2K server and dos batch files? In-Reply-To: <3c866f0c$1_2@axion.net> References: <3c866f0c$1_2@axion.net> Message-ID: <200203070056.g270uDq16863@mail.merlinsoftech.com> On March 6, 2002 11:38 am, you wrote: > I would appreciate if you can tell me if Python is a good fit for what I > want to do. If not, please recommend another solution. Yes it will do all that easily. Mind you are asking a Python list. Look at the ActivePython distribution and all the win32all components which will give you access to lots of useful Windows stuff. -- Andy McKay From skip at pobox.com Wed Mar 6 11:18:31 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 10:18:31 -0600 Subject: dynamic loading of modules In-Reply-To: <000701c1c528$8acfea50$c19949d5@dkn02> References: <000701c1c528$8acfea50$c19949d5@dkn02> Message-ID: <15494.16727.684258.607639@beluga.mojam.com> Henry> I would like to be able to compound variables that will then form Henry> the name of the particular module to be loaded into the active Henry> script. Take a look at the docs for the exec statement and the __import__ builtin function. Briefly: mname = raw_input("enter a module name: ") exec "import %s"%mname in globals() or mname = raw_input("enter a module name: ") m = __import__(mname, globals()) print m.__doc__ -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From jkraska at san.rr.com Fri Mar 8 00:45:06 2002 From: jkraska at san.rr.com (Courageous) Date: Fri, 08 Mar 2002 05:45:06 GMT Subject: why is python slow? References: Message-ID: <7ckg8u0dsk9lpmje0p3cd04fca0flic69n@4ax.com> >P.S. I am just trying to understand and do not intend to put down python by >any means. Python is extremely dynamic; as a consequence, the most straightforward and easy to maintain implementation of Python language will by necessity be an exercise in processing strings. Often by hashing. That's expensive. C// From bergeston at yahoo.fr Thu Mar 7 13:02:18 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Thu, 7 Mar 2002 19:02:18 +0100 Subject: very newbie question References: <61ff32e3.0203070659.28cf5e1c@posting.google.com> <1015517718.445890@news.commspeed.net> Message-ID: Probably not saved at all ! Try this in Idle: menu File - Save as (choose a pretty name ending by .py and click on button Save) Run Read status bar if nothing happens ! "Tom Babbitt" wrote in message news:1015517718.445890 at news.commspeed.net... > > "ron nixon" wrote in message > news:61ff32e3.0203070659.28cf5e1c at posting.google.com... > > I've got a script called snakes saved to my c: drive and I want to run > > it from IDLE. By when I do file open and run script, I get an invalid > > syntax message. Likewise if I write the script in IDLE and hit "run > > script" it get a message saying that says "the buffer for Python Shell > > is not saved. Please save it first." Soooo. With all that being said. > > How do I save a script and then get python to execute it from IDLE(and > > where in the documentation is this?) > > > > Thanks in advance > > It's not clear why you want to run your program from IDLE, you mite want to > just run it with phython (ie 'c:\Python22\python snakes.py' (you could need > to rename the filename to *.py)). > > Tom Babbitt > > From gimbo at ftech.net Wed Mar 6 08:52:42 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 6 Mar 2002 13:52:42 +0000 Subject: Status of PEP's? In-Reply-To: <3C861BEB.60701@destiny.com> References: <3C861BEB.60701@destiny.com> Message-ID: <20020306135242.GB10985@andy.tynant.ftech.net> On Wed, Mar 06, 2002 at 08:38:51AM -0500, Michael Chermside wrote: > Not that my opinion means anything, but I'll go ahead and express it anyhow. > > 1) I think that "for i in range(len(items)):" is awkward, annoying, > and detracts from Python. There should be a better way. This just came to me: for index in indices(items): pass or maybe better yet: for index in items.indices(): pass ? -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From jgardn at alumni.washington.edu Fri Mar 1 03:04:58 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Fri, 01 Mar 2002 17:04:58 +0900 Subject: PyQT and shaped windows in X References: Message-ID: Moray Taylor wrote: > Hi, > > Can anyone point me in the direction of an example of shaped windows > using QT with Python, is the XLib module required? Is it even > possible? > I really doubt there is one. > BTW I have tried asking in the PyQT/PyKDE mailing list, but it wasn't > considered to be a PyQT question, go figure. > This is a Qt question - not a PyQt one. You'll probably figure out how to do it, but it will take a lot of study and experimentation. Perhaps you should investigate Xt, as there is a QXtWidget and QXtApplication class available in Qt. The silence was because no one knows how to do it, not because it was a stupid question or because we don't like you. Jonathan From theller at python.net Wed Mar 20 05:27:30 2002 From: theller at python.net (Thomas Heller) Date: Wed, 20 Mar 2002 11:27:30 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: "Martin v. L?wis" wrote: > "Thomas Heller" writes: > > > Problems with freeze, IMO, are that it requires a C-compiler, > > which most people on windows do not have, also the resulting > > files are much larger than those created by py2exe or installer, > > because the byte codes are not compressed. > > In the context of distutils, absence of a compiler may not be a > problem: people building packages with distutils will need a compiler, > atleast if the package contains extension modules. > > As for size of the resulting executable: if compressing the byte code > really provides a significant saving, I think freeze should make use > of that mechanism, too. Do you think that PyImport_FrozenModule() should be extended to handle compressed byte codes? Or should freeze simply append the compressed byte codes to the executable (as py2exe and installer do it) instead of compiling them with the C-compiler? > > I see the primary advantage of freeze over the other mechanisms in > that it provides (or can provide) a truly stand-alone binary. The > Windows-specific packagers always need to put pythonxy.dll into the > executable, and any required extension modules; this is ugly. If > libpython is available as a static library, freeze can produce more > compact binaries, too, since it can omit unused extension modules. An interesting idea would be to additionally distribute Python and extension modules (on windows) not only as dlls, but also as static libraries. In this case only a linker would be needed, and you avoid the problems compiling all the sources... Another possibility would be to use a program creating a standalone exe-file from exe and dlls. I have once tried such a program, it worked in simple cases, but not for Python. Then I wrote some code (in python) myself to do this, it is very tricky, but certainly possible. All in all, currently I don't care too much about single file executables. Thomas From khirmint at hotmail.com Wed Mar 13 13:37:29 2002 From: khirmint at hotmail.com (Ken) Date: Wed, 13 Mar 2002 10:37:29 -0800 Subject: Another socket/thread question Message-ID: Hey everyone.. I've got a thread that continously listens to a socket, and reports what it receives. Blocking is turned on, and I would like it to stay that way since the only thing the thread has to do, is listen to the socket. My question is when the socket needs to be closed (program shuts down, or that user is being disconnected by the server) is it possible to interupt a socket.recv ()? If not, whats the easiest way to cut processor time from looping endlessly with blocking turned off? Thanks in advance. From threehounds at worldnet.att.net Sun Mar 17 15:14:46 2002 From: threehounds at worldnet.att.net (Matt Austin) Date: Sun, 17 Mar 2002 20:14:46 GMT Subject: basic statistics in python References: <3C931C23.B0B2BF75@kfunigraz.ac.at> <3C946430.8A4408ED@kfunigraz.ac.at> Message-ID: <3C94DC23.2040304@worldnet.att.net> Quartiles are neither superior or inferior to quantiles, it's just another term. When people refer to quartiles they mean the 25th and 75th quantile. Another term you will see is quintiles which refer to the 20th, 40th, 60th, and 80th quantiles. This can be generalized to deciles, etc. The nice thing about R is that most of the functions are written in the language and can be viewed to see how they are calculated by simply typing the name of the function which uses the default show method for functions. If the functions are internal, then you can view the source code to verify the calculations. --Matt Siegfried Gonzi wrote: > Tim Churches wrote: > > >>> delivers: >>> >>> Min. 1st Qu. Median Mean 3rd Qu. Max. >>> 0.230 1.226 7.300 18.960 31.680 78.900 >>> >>> Everything is correct, except the 1st quantile and 3rd quantile. >> >> You mean 1st quartile and 3rd quartile, not quantile. And the values >> calculated by R are not wrong, just different (see below). > > > The book "Statistical Methods in the Atmospheric Sciences", by D.S. > Wilks, does not really make a difference between "quantiles" and > "quartiles". According to the book I got the impression that quartiles > is inferior to quantiles (e.g. page 24: "Example 3.1. Computation of > Common Quantiles". > > But you are right that I should be more precise in order to avoid > confusion. > > > >> There are a number of methods for calculating quantiles. In R, the >> summary() function calls the quantile() function to calculate the 1st >> and 3rd quartiles and the median. The quantile() function uses linear >> interpolation to calculate the sample quantile for the probabilities of >> 0.25 and 0.75, whereas XLispStat is just taking the arithmetic mean of >> the 2nd and 3rd, and 6th and 7th values respectively (using zero-based >> indexing/counting, since this is the Python list).# > > > My first guess was also that R just calculates the quantiles in a > different fashion; but I could not find any hints in the documentation. > According to the beforementioned book (page 23): > > "Almost as commonly used as the median are the quartiles, q0.25 and > q0.75. Usually these are called the lower and upper quartiles, > respectively. They are located halfway between the median, q0.5, and the > extremes, x(1) and x(n). In typically colorful terminology, Tukey (1977) > calls q0.25 and q0.75 the 'hinges', imagining that the data set has been > folded first at the median, and the quartiles." > > I simply thought (and note the word "halfway" in the citation) then > XLispStat is/was correct. > > >> The methods used by R are fully described in the R manual (see >> help(quantile)), but a commonsense explanation of the R approach is as >> follows (again using zero-based indexing/counting). > > > Maybe I did look too superficialy after the method of calculation. > > > Regards and especially thank you for your insight, > S. Gonzi From malletc3 at cti.ecp.fr Sun Mar 3 17:03:00 2002 From: malletc3 at cti.ecp.fr (DarkCed) Date: Sun, 3 Mar 2002 23:03:00 +0100 Subject: [newbie] Problem with os.system Message-ID: I would like to run a program from a python script (a source for a icecast server). The program works, but a simple two-line script with os.system('ices') does not. I get this message : "syntax error near unexpected token". If I type "ices" in the same repertory, it works... Shall I use another command to run my program ? Thanx Ced From michael at stroeder.com Thu Mar 14 13:06:11 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 14 Mar 2002 19:06:11 +0100 Subject: jython for a large-scale web site? References: Message-ID: <3C90E693.3080600@stroeder.com> Sandy Norton wrote: > > I work with a web company that has about 180,000 registered users, and > pretty good weekly traffic stats. Their current platform of > development includes Oracle for the data server, AOLServer for web > serving platform and TCL to script the whole thing together, with > everything running on Solaris on a few fat multiprocessor Sun > machines. > [..] > Now, I'm really happy to have turned the top tech decision-maker in > the company on to python Also check out http://pywx.idyll.org/ Ciao, Michael. From skip at pobox.com Wed Mar 27 10:43:34 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 27 Mar 2002 09:43:34 -0600 Subject: location of gmpy, google In-Reply-To: References: Message-ID: <15521.59558.878355.64531@12-248-41-177.client.attbi.com> FREDRIK> Where can I get gmpy? Try searching for "gmpy" on google. Google should be the first place people look for just about anything on the net my opinion. Pardon the digression non-Pythonic discussion, but let me tell you a story... A guy the incubator where I have an office had a blown output channel in his stereo. An *old* stereo. He tried swapping speaker wires. The quiet speaker changed. Popped open the case and pulled the suspect amplifier doodad. He went to Google, entered the long part number from the doodad (just the part number, one of those long alphanumeric things), and was led to some place in Georgia that had some of these in stock. Finding that doodad through the usual means would probably not have been anywhere as easy as that. Google is your friend... -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From gerhard at bigfoot.de Thu Mar 14 20:12:23 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 15 Mar 2002 01:12:23 GMT Subject: Dear Guru, I have added def and it doesnt work Sincerly, F References: Message-ID: Oscar wrote in comp.lang.python: > I have added > > def joinsplit = (join(split(lines, '"'), ' ')) > return joinsplit No wonder this doesn't work, as you've apparently haven't made very much effort to understand what you're doing here. Sorry to be so blunt, but you can't write software just by guessing about the syntax. If you want to learn programming in Python, then go to http://www.python.org/ and head to the newbie page there. If you don't want to learn programming, perhaps because it's too much effort, then the only option is to find somebody to do it for you. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From sjmachin at lexicon.net Thu Mar 28 18:03:34 2002 From: sjmachin at lexicon.net (John Machin) Date: 28 Mar 2002 15:03:34 -0800 Subject: Extending/embedding versus separation References: Message-ID: bokr at oz.net (Bengt Richter) wrote in message news:... > On Thu, 28 Mar 2002 11:12:09 -0000, "skoria" wrote: > > >Hi > > > >Thanks for your help. No, I didn't write the hash tables. I'm writing > >a stats program based on webalizer. Webalizer and Analog were the > >fastest and least memory hungry of all the programs I know of, and > >webalizer is GPL so I was able to use it as a basis for my work, so I > >get to make free software at work! The hash tables are already written > >there. I've just downloaded the webalizer source and inspected its hashtab.c -- 5 or more different hashtables each with its own constructor, destructor, insert, etc methods [maintenance nightmare] -- hash function effectively uses only the last 6 to 7 bytes of the key on a 32-bit machine [hashval is multiplied by 31 for each byte in the key] -- uses chaining for collison resolution but w/o move-to-front heuristic [IOW it could use less memory or go faster!] -- reaction: slam lid shut, nail it down, ... aarrgghh, how do we stop the timbot from seeing this lest it collapse with an ExcessiveSnortCount exception? [snip] > OTTOMH, I would guess that you may need to generate some special > representations of visitor paths directly from the logs, unless > the webalizer already does that. But if you have to process the > raw logs in a new way, it will most likely be easier to get right > in Python than by cannibalizing existing C. Especially *that* existing C. Look at its parser.c; do you want to have to understand that, let alone maintain it? And saving memory??? You don't need the following in Python: #define MAXHASH 2048 /* Size of our hash tables */ #define BUFSIZE 4096 /* Max buffer size for log record */ #define MAXHOST 128 /* Max hostname buffer size */ #define MAXURL 1024 /* Max HTTP request/URL field size */ #define MAXURLH 128 /* Max URL field size in htab */ #define MAXREF 1024 /* Max referrer field size */ #define MAXREFH 128 /* Max referrer field size in htab */ #define MAXAGENT 64 /* Max user agent field size */ #define MAXCTRY 48 /* Max country name size */ #define MAXSRCH 256 /* Max size of search string buffer */ #define MAXSRCHH 64 /* Max size of search str in htab */ #define MAXIDENT 64 /* Max size of ident string (user) */ Bottom line: do it in Python. From matkin at iar.se Fri Mar 15 04:47:34 2002 From: matkin at iar.se (Mats Kindahl) Date: 15 Mar 2002 10:47:34 +0100 Subject: YANRQ (yet another regex question) References: <4f5k8.435$zT5.13755@news.itd.umich.edu> Message-ID: Michael George Lerner writes: > I wanted to match this: > > (?Pfoo | foo | foo | foo | foo) > > without typing in all of the different combinations of 'foo' and spaces. > > (Tim kindly pointed out the typos in the above, which I've corrected) > > Mats Kindahl wrote: > > > Depending on the definition of easy, this is the alternative I would > > use. > > > r = re.compile(r'(?P(?=.{7}) *foo *)') > > > > Of course, your milage may wary. > > Doesn't quite work for me: > > >>> import re > >>> r = re.compile(r'(?P(?=.{7}) *foo *)') > >>> s = r.match('foo ').groupdict()['foo'] > >>> s > 'foo ' > >>> len(s) > 12 > >>> > > and I only want to match things that are seven characters long here. That's what I get for not reading the manual... :/ Of course it should be r = re.compile(r'(?P(?=.{7}$) *foo *)') ^ ! +-- notice missing dollar -- Mats Kindahl, IAR Systems, Sweden Any opinions expressed are my own, not my company's. From jim.jacobs at jacobshome.com Sat Mar 9 16:30:34 2002 From: jim.jacobs at jacobshome.com (Jim Jacobs) Date: Sat, 9 Mar 2002 16:30:34 -0500 Subject: Tkinter error Message-ID: I just installed ver. 2.2. When I try to run Tkinter script (include IDLE), the following error occurs: "self.tk = _tkinter.crate(screenName, baseName, className) TclError: Can't find a usuable init.tcl in the following directories: [list of directories]" Among the directories listed is the directory in which init.tcl is located. What gives? Thanks, Jim From Dave.Haynes at sia-mce.co.uk Fri Mar 22 16:07:43 2002 From: Dave.Haynes at sia-mce.co.uk (Dave Haynes) Date: 22 Mar 2002 13:07:43 -0800 Subject: Customisation of comparison operators Message-ID: Hi, Which of __lt__, __le__, __eq__, __ne__, __gt__, __ge__ are used when sorting lists of objects with .sort()? Which of them is used for the 'in' and 'not in' comparisons? Is __cmp__ no longer used at all if the above are defined? This might be dodgy practice, but I have some objects for which I want to provide subtly different behaviour for the comparison operators than for testing 'in' and 'not in'... Cheers, Dave. From greg at cosc.canterbury.ac.nz Mon Mar 4 23:46:01 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 05 Mar 2002 17:46:01 +1300 Subject: Status of PEP's? References: <1cef615e.0203021254.6bf3658@posting.google.com> <3C82C91C.A60B3242@cosc.canterbury.ac.nz> Message-ID: <3C844D89.31AB890F@cosc.canterbury.ac.nz> Raymond Hettinger wrote: > > Even for symmetric tables, a default direction should be assigned > (say, row-major). Then, the normal pythonic approach to nested > lists or tuples can be used. But part of the beauty of it is that it allows you to treat symmetric tables symmetrically, rather than have to know about and remember the "default direction". E.g. to iterate in the opposite order from usual: for j in indices(myarray, 1): for i in indices(myarray, 0): do_something_with(myarray[i, j]) This fits in nicely with Numeric arrays, which can be sliced and diced very flexibly without any directional bias at all. > forget the new > notation, save the repeated calls to len(), and use just one sample len() > from each dimension > > rowcnt, colcnt = len(arr), len(arr[0]) You mean like: row_indices = indices(myarray, 0) col_indices = indices(myarray, 1) for i in row_indices: for j in col_indices: ... > Given a ragged right, what would looping > over columns do with: > 10 20 30 > 40 50 60 70 80 > 90 11 12 13 Outside the scope of my proposal. This is not a 2-dimensional table, it is a 1-dimensional table of 1-dimensional tables. Calling indices(..., 1) on it would raise an exception, just as doing the same to a list would. > Let's use the optional argument for something different: > indices( anIterable, [start, [stop]] ) > Now, you can make friends with people who number their > arrays starting at one instead of zero ;) sub_indices = indices(anIterable)[start:stop] Now you're friends with them without even having to *know* where their indices start (or even whether they're contiguous or not!) > Also, indices() and indexed() should return a generator instead > of a fully evaluated list. Why eat-up memory unnecessarily. Certainly. (Actually, I would make it a lazy sequence a la xrange, so that my second example above would work (i.e. it needs to be re-usable)). > One final note, if indexed() is available, why would indices() > ever be needed? * It doesn't generalise well to symmetric multi-dimensional use. * Iterating over parallel lists can be written more symmetrically with it: for i in indices(list1): do_something_with(list1[i], list2[i]) looks better to me than for i, item1 in indexed(list1): do_something_with(item, list2[i]) * Also, I just don't like indexed() for some reason. It seems to be doing too much at once. I wouldn't object to its existence, but I wouldn't like to have to use it all the time. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From skip at pobox.com Thu Mar 21 20:49:53 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 21 Mar 2002 19:49:53 -0600 Subject: __file__ for relative imports In-Reply-To: References: Message-ID: <15514.36289.256160.98265@12-248-41-177.client.attbi.com> Ken> I keep bumping into that one too. I can't think of any advantage Ken> for the current semantics, so I am submitting a PEP. I didn't see Ken> a bug in sf or an existing PEP, but I might have missed something Ken> so please let me know. Seems like a PEP is more appropriate than a Ken> bug report though. Why? I'd just submit a bug report. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From skip at pobox.com Thu Mar 21 09:24:37 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 21 Mar 2002 08:24:37 -0600 Subject: eval of a private attribute In-Reply-To: <3C998F89.66DB1290@infomaniak.ch> References: <3C998F89.66DB1290@infomaniak.ch> Message-ID: <15513.60709.211340.425135@12-248-41-177.client.attbi.com> Cedric> I'd like to create a method which will be able to get any Cedric> attribute of the class. Why use eval? Why not simply p = getattr(self.__class__, var) ? The first arg restricts you to fetching class variables. You could also use 'self' there I suppose. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From skip at pobox.com Fri Mar 15 00:09:05 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 14 Mar 2002 23:09:05 -0600 Subject: readline() blocks after select() says there's data?? In-Reply-To: <2b57f654.0203141934.391d1bcc@posting.google.com> References: <2b57f654.0203141934.391d1bcc@posting.google.com> Message-ID: <15505.33265.747862.25428@12-248-41-177.client.attbi.com> >> selectables = [theProcess.childerr, theProcess.fromchild] >> (input, output, exc) = select.select([],selectables, selectables) ... >> It blocks forever waiting for theProcess.childerr.readline(bufsize) >> to return. I expect it to block waiting for select.select(); that >> would not be a problem. The problem is that select is claiming >> there's stuff to be read, then when I try to read it, it's not there! >> How can that be? Based upon the attribute names you are using, I suspect you instantiated os.Popen3 to create theProcess. These are file objects, not sockets. I believe select only blocks on sockets. See the comments about asynchronous file i/o near the bottom of asyncore.py. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From sjmachin at lexicon.net Mon Mar 11 01:00:02 2002 From: sjmachin at lexicon.net (John Machin) Date: 10 Mar 2002 22:00:02 -0800 Subject: Modulo operator : differences between C and Python References: <3C8BE537.74E55963@mega-nerd.com> Message-ID: Erik de Castro Lopo wrote in message news:<3C8BE537.74E55963 at mega-nerd.com>... > Hi all, > > Just recently I prototyped a relatively complex algorithm in Python > before converting it to C. During this conversion I noticed that > the modulo operator returns different results in C and Python if > the numerator is negative. For positive values they produce the same > result. [snip] > Anybody have any idea why this is? The Python reference manual: "The modulo operator always yields a result with the same sign as its second operand (or zero)" K&R2, p. 205 says: [paraphrased] If both operands are non-negative, then the remainder is non-negative and smaller than the divisor; if not, it is guaranteed only that abs(remainder) < abs(divisor). So what you see from C depends on the compiler and architecture. If you are at all interested in portablity of your C code, you will need to take precautions. Why? Philosophy, I suppose: C gives you generally what the hardware gives you. Python mostly gives you what is useful and consistent, even if the implementation has to work a bit harder to do that. There is also a lengthy thread in this newsgroup -- you can easily find it by googling "modulo remainder negative". <:-)> BTW, speaking of "easily find", were you having simultaneous problems with all of (1) the index in K&R (2) the Python reference manual (3) Google??? From fdrake at acm.org Mon Mar 4 23:24:13 2002 From: fdrake at acm.org (Fred L. Drake) Date: Mon, 4 Mar 2002 23:24:13 -0500 (EST) Subject: [development doc updates] Message-ID: <20020305042413.3598528696@beowolf.fdrake.net> The development version of the documentation has been updated: http://python.sourceforge.net/devel-docs/ Minor accumulated updates. From webmaster at greich.co.uk Fri Mar 1 00:01:53 2002 From: webmaster at greich.co.uk (David Russell) Date: Fri, 1 Mar 2002 05:01:53 -0000 Subject: Python's Syntax Message-ID: Hi, I can't get my head around Python's syntax for the if, for, while etc. statements. I'm used to the classic: if (condition == TRUE) { Do this } else { Do this } I've had a look at a couple of tutorials for Python and it appears like this: if condition == TRUE: do this How do you tell it when to stop? I just can't figure out how to do it. Could somebody explain it to me please, even though I have a strange suspicious that it is one of the simplest deatils imaginable. Also, another thing about Python's syntax. Are statements just sperated by their lines, or do they have some form of seperator (like a semi-colon)? Thanks for any help, it is appreciated. (Sorry if this appears twice, the first time I sent it I got an error so I'm not sure if both will show up) From max at alcyone.com Sat Mar 30 17:30:13 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 30 Mar 2002 14:30:13 -0800 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> Message-ID: <3CA63C75.569891AD@alcyone.com> David Abrahams wrote: > Well, I try not to play favorites <0.002 wink>, but the implicit > conversion rules in C++ are admittedly and unfortunately liberal. > However, bool is detectably NOT derived from int in C++: > > void f(int const&); > f(false); // error! > assert(boost::is_base_and_derived::value); // fails! Of course it does; in C++, int and bool aren't even classes, much less that they have some subclass relationship. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From cbbrowne at acm.org Thu Mar 7 23:54:47 2002 From: cbbrowne at acm.org (Christopher Browne) Date: Thu, 07 Mar 2002 23:54:47 -0500 Subject: why is python slow? References: Message-ID: les_ander at yahoo.com (les ander) wrote: > i am just curious as to why different programming languages have > different speed. I understand that if a language has an extensive > grammar (such as c++) the compiler would take longer. But what about > execution? why is a perl program faster than similar python > program? For example when java came out it use to be pretty slow, > but now it is pretty fast. How was this speed-up acheived and why is > it not possible to have such a speed up for python? The complexity of the language grammar will certainly affect how large the compiler is; the impact of that on speed of execution of compiled code should be minimal (except to the degree that it's harder to write good optimizers for complex languages than for simpler languages). You'd often be able to expect programs deployed in languages that compile to machine code like C, C++, Ada, and such, to be faster than programs deployed using environments that use interpreters and/or bytecode compilers. The bit of C code for (i=0; i < 50000; i++) { c = c + 1.0; } is likely to execute a whole lot faster (assuming it doesn't get compiled out of existence into a mere "c = 50000.0;") than the Perl: for ($i=0; $i < 50000; $i++) { $c += 1.0; } or the Python: for i in range(50000): c = c + 1.0 The latter two will at best involve interpretation of bytecompiled code, which is a whopping lot slower than the machine language generated by the C compiler. Java is an interesting case; the development of "JIT" compilers takes bytecompiled code and generates machine code which can be of comparable speed to C/C++/..., and that represents a relatively recent improvement to Java environments as they have matured. Pre-JIT, Java would have pretty similar performance characteristics to Perl and Python. In all cases, evaluating performance is rather a "black art." It is _not_ safe to say that C will "always be faster," or that Python will "always be slower;" even if that were always true, raw speed is by no meands the only evaluation criterion, which anyone that has looked at benchmark comparisons will know. The sorts of JIT speedups seen with Java don't happen with Python because Python doesn't directly define a virtual machine that is amenable to JIT analysis. But JIT is fairly abtruse, and part of the point is that Java _without_ JIT "sucks wind badly," performance-wise. They _needed_ JIT for Java to NOT suck badly. The answers for performance tuning of Perl and Python will differ from that. -- (concatenate 'string "cbbrowne" "@canada.com") http://www3.sympatico.ca/cbbrowne/python.html Your latest program has been judged UNTASTEFUL by the T daemon; and automatically deleted. From cgale1 at cox.net Sun Mar 17 06:47:45 2002 From: cgale1 at cox.net (Van Gale) Date: Sun, 17 Mar 2002 11:47:45 GMT Subject: Pythonic Porter stemmers (Was: Re: Word frequencies -- Python or Perl for performance?) References: Message-ID: W.B. Frakes and R. Baeza-Yates. 1992. "Information Retrieval: Data Structures and Algorithms," Prentice-Hall, describes the Porter algorithm as well as a few other stemming algorithms. The reference for the algorithm is: Porter, M. F. 1980. "An Algorithm for Suffix Stripping." Program, 14(3), 130-37. Frakes mentions nothing about a patent on the Porter algorithm, and I'd be surprised if there were since it was pretty rare back in the "good old days". I worked on a huge indexing project for a legal publisher, and we developed our own stemming algorithm. It was much simpler than Porter, basically being the most obvious conflations (like remove "s" and "ies") which covered the vast majority of English words, and then a list of "exceptions". Of course we had the advantage of 50+ editorial staff capable of proofreading the index finding new exceptions, but I still think that's a better way to go than trying to stem completely by algorithm. As hard as the Porter algorithm tries it still make a *lot* of mistakes. -- Van Gale From martin at v.loewis.de Sat Mar 30 17:24:57 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 23:24:57 +0100 Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: <3CA62CD8.6ABD44D0@accessforall.nl> Message-ID: Ype Kingma writes: > Python is sufficiently high level not to care about the bits. > Python never had a C float type, only a C double type, for precisily > this reason. Python does, however, have a long int type, side-by-side with the int type - because it cares about bits. Atleast it used to, there is a PEP for merging the two integer types. There is also a PEP merging all numeric types into a single one, or a hierarchy of types. Notice that the relationship of bool and int has two aspects: one is whether you can combine them in numeric operations, e.g. 28+isleap(year). There is absolutely no way to remove this property from the language - too much code would break if that would raise an exception. The other question is whether bool should inherit from int. Notice that this is unrelated: you could have the arithmetic operations even without inheritance. The inheritance from int is mostly an implementation convenience: too much code in the interpreter itself would need to change to make bool inherit from object only. > Somehow this reminds me of subclassing Square from Rectangle: > it just doesn't feel right, even though it might work. I can't see the relationship: A Sqare is-a Rectangle, so following classic OO principles, the inheritance is clearly right. Depending on how you define the Rectangle interface, this inheritance relationship would even satisfy LSP. > With a non int bool, True and False would be real singletons: > > bool(1) is True > bool(0) is False They are singletons even under the PEP: You have to work really hard to make two instances of True (bool(1) is (not bool(0)) is bool(1) is True); and if it was a type not inheriting from int, you could *still* make extra instances if you wanted to hard enough. > True is not 1 This is True in the PEP. > True != 1 This is False, and it should be, since making it True would break backwards compatibility. > Subclassing bool from int would also force 1 and 0 to be become > real singletons. Can you elaborate? This is not at all the case. > The only reason this would work is that current python > implementations happen to implement 1 and 0 in this way. Not at all: >>> (1>0) is 1 0 > But you could make the language definition simpler by explicitly > defining the cast to bool in contexts where a boolean is expected, > see above. This would allow the current casts (eg. list to bool as > non empty) to be described at the standard types instead of in the > language definition. It is already that way, the method determining truth is __nonzero__; for historic reasons, a number of fallbacks are taken if __nonzero__ isn't implemented. Regards, Martin From bernie at 3captus.com Sun Mar 3 15:33:09 2002 From: bernie at 3captus.com (Bernard Yue) Date: Sun, 03 Mar 2002 20:33:09 GMT Subject: Trouble running programs References: Message-ID: <3C828906.A6401D51@3captus.com> default_renegade wrote: > Just started learning Python, but having trouble running a programs. > First, I open IDLE, then open a new window > Then I write a program and save it, then I close the window > After save the program from script window, don't close the window. Just press Ctrl+F5 or select from menu Edit->Run script (of script window) to run the script from within IDLE. > When I'm back at the Python Shell and select Run Script It gives me > an error "Not Saved - The bugger for Python Shell is not saved. > Please save it first!" Run script command should not be part of Shell window (if it does, a file selection dialog box should popup for use to select a script to run). Anyway, IDLE is not a commercial product so as a user, as long as I find a way to make it work, I have no complains. > > However, I can run the program from the DOS prompt. Bernie -- There are three schools of magic. One: State a tautology, then ring the changes on its corollaries; that's philosophy. Two: Record many facts. Try to find a pattern. Then make a wrong guess at the next fact; that's science. Three: Be aware that you live in a malevolent Universe controlled by Murphy's Law, sometimes offset by Brewster's Factor; that's engineering. So far as I can remember, there is not one word in the Gospels in praise of intelligence. -- Bertrand Russell From pachy at 012.net.il Sun Mar 10 06:42:45 2002 From: pachy at 012.net.il (Tal Linzen) Date: Sun, 10 Mar 2002 13:42:45 +0200 Subject: Bidirectional widgets in Tk Message-ID: <001601c1c828$f8daf230$3f12c7d4@ussr6gwe8yu2pu> Hi. I'm trying to write a GUI that includes bidirectional text entries (to support both Hebrew and English). From a few searches I gathered that QT and GTK both support this kind of widgets, but I couldn't find any reference to Tk. Help? Tal From robin at jessikat.fsnet.co.uk Sun Mar 24 09:40:59 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 24 Mar 2002 14:40:59 +0000 Subject: 2.2 open Message-ID: I am just testing Python 2.2 and one of the oddities I have found is in some code that used to test __import__. if type(__import__) == type(open): ..... but now I see >>> __import__ >>> type(__import__) >>> open >>> type(open) So open is now a file? That seems a bit odd to me. Certainly it's causing my version 4 McMillan installer code to flop over. It seems that some built ins now have the type of the object they create. Pretty weird logic. -- Robin Becker From walter at livinglogic.de Tue Mar 12 14:19:32 2002 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Tue, 12 Mar 2002 20:19:32 +0100 Subject: New-Style-Classes: some questions References: Message-ID: <3C8E54C4.7030506@livinglogic.de> Tino Lange wrote: > Hi! > > [...] > > 1) According to the current documentation > > http://www.python.org/doc/current/ref/sequence-methods.html > > the special methods __getslice__ and __setslice__ are deprecated and should > not be implemented anymore (since 2.0) . But they exist automatically in > the subclassed list and are used for insertion like > > newlist[3:4] = 5 > > - so it seems I have to code/overload these deprecated methods. What's true > now? Deprecated or not? See Python Bug #473985 http://sourceforge.net/tracker/?func=detail&aid=473985&group_id=5470&atid=105470 for an explanation. > [MaxSizedList via XML-RPC] Bye, Walter D?rwald From maxm at mxm.dk Wed Mar 13 16:08:49 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 21:08:49 +0000 Subject: sorting nested dictionary References: <3C8F1B79.8000607@mxm.dk> Message-ID: <3C8FBFE1.6090500@mxm.dk> dsavitsk wrote: > thanks. the following solution was also sent, seems to work, but i don't > know why ... > def compare(a, b): > return cmp(a[1]['weighted'], b[1]['weighted']) > > pairs = h['ids'].items() > pairs.sort(compare) the "cmp()" function is the key here: cmp(x, y) Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. ---------------------------- And yes that is the 'correct' way of doing it, but the tuple way is faster. get it from the horses mouth below. regards Max M ---------------------------- Sorting From Guido van Rossum Sorting lists of basic Python objects is generally pretty efficient. The sort method for lists takes an optional comparison function as an argument that can be used to change the sorting behavior. This is quite convenient, though it can really slow down your sorts. An alternative way to speed up sorts is to construct a list of tuples whose first element is a sort key that will sort properly using the default comparison, and whose second element is the original list element. Suppose, for example, you have a list of tuples that you want to sort by the n-th field of each tuple. The following function will do that. def sortby(list, n): nlist = map(lambda x, n=n: (x[n], x), list) nlist.sort() return map(lambda (key, x): x, nlist) Here's an example use: >>> list = [(1, 2, 'def'), (2, -4, 'ghi'), (3, 6, 'abc')] >>> list.sort() >>> list [(1, 2, 'def'), (2, -4, 'ghi'), (3, 6, 'abc')] >>> sortby(list, 2) [(3, 6, 'abc'), (1, 2, 'def'), (2, -4, 'ghi')] >>> sortby(list, 1) [(2, -4, 'ghi'), (1, 2, 'def'), (3, 6, 'abc')] From thoa0025 at mail.usyd.edu.au Sun Mar 24 02:14:59 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 24 Mar 2002 07:14:59 GMT Subject: [rp] [newbie] embedding python Message-ID: Hi, so urgent! i have a python script "file.py" which has a function in it which i need to call from my c code. how can i do this! all my projects have been postponded becuase i cant do this! please helP! i would be so grateful!! ultimately im trying to embed some python into my c source in UNIX. i have absoutely no idea how to do this despite the tutorial on the web at http://www.python.org/doc/current/ext/building-on-unix.html#building-on-unix it's too general and not step by step enough for a noob like me :( Please help. asap!!! Cheeeers From kragen at pobox.com Wed Mar 27 15:14:30 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 27 Mar 2002 15:14:30 -0500 Subject: 2.2 open References: <1UtsCLAcngn8EwWc@jessikat.fsnet.co.uk> <3C9E9C74.781B3911@cosc.canterbury.ac.nz> Message-ID: <83663h3h09.fsf@panacea.canonical.org> Greg Ewing writes: > > So the question now is, how do I tell if __import__ is the built in one > > even if the import system is not fully initialized. > > You could compare its type with what you really > should have been comparing it with in the > first place: > > import types > if type(__import__) == types.BuiltinFunctionType: > ... That'll still break in Python 4.6 when __import__ becomes an alias for types.ModuleType, and again in Python 4.7 when __import__ becomes a Python wrapper around some builtin functionality. If you want to know if __import__ is the builtin __import__ because you change it somewhere, you should put a flag somewhere that says whether or not __import__ is overriden. E.g. getattr(__import__('sys'), "myimportisinstalled"). Generically, if you want to know whether someone *else* has overridden __import__, you are doing something immoral and should stop immediately. But I well know that people have to do immoral things in Python sometimes... From johnroth at ameritech.net Sun Mar 31 16:30:31 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 31 Mar 2002 16:30:31 -0500 Subject: PEP 285: Adding a bool type References: <3CA75DAC.17647CEA@alcyone.com> Message-ID: "Erik Max Francis" wrote in message news:3CA75DAC.17647CEA at alcyone.com... > Ralph Corderoy wrote: > > > Terry Reedy wrote: > > > > > C. Anyone learning Python has some idea of truth and truth values. > > > But I am sure there are some with no idea of what 'bool' means and > > > only a vague idea about 'Boolean'. Better formalizing Python truth > > > values should make them even easier to learn; why not call them what > > > they are? > > > > That's an excellent point, as are the others you make. My Mum would > > understand true but not bool or Boolean. > > I'm not really sure how beneficial this would be. In the real world, > not everything about a programming language -- even a low-overhead > language like Python -- can be instantly intuited by non-programmers. > After some elementary level they're going to have to start reading. > That bool (or boolean) is a Boolean type is not a hard concept to get > across, and I don't see how calling it "truth" is really all that much > more helpful. > > It's far better, in my opinion, to give it a standard name from computer > science (bool or boolean) and let new programmers take the tiny little > steps (in this case) to add a new word to their vocabulary -- a word > that will help them in future explorations of programming and computer > science, no less. The trouble is that 'bool' as a data type **isn't** the standard name from mathematics. Correct usage is something like: "Boolean logic manipulates truth values." That is, the data type is a truth value (see, for example, "truth table".) The usage in programming languages is simply incorrect linguistically. Python has always had Boolean logic - and, or not and so forth. What's being added is the truth data type. > Excessive attempts to make terms more approachable can lead to disaster > in the degenerate case, resulting in just a new form of terminology that > now nobody understands. But nobody has suggested calling it the Aristotelian data type. John Roth From sdm7g at Virginia.EDU Fri Mar 1 12:36:29 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Fri, 1 Mar 2002 12:36:29 -0500 (EST) Subject: Useful, robust shell utilities In-Reply-To: Message-ID: On 1 Mar 2002, Donn Cave wrote: > Quoth Jonathan Gardner : > > | I think it would be nice to make things like 'grep' even... > | > | Here is my wish list. Each of these should implement a significant portion > | of what the GNU utils do. They should be robust, and give reasonable > | results, and reasonable exceptions. > | > | touch, chmod, chown, chgrp, touch > | df, du > | cp, dd, install, mv, rm, shred > > Some of them are essentially POSIX 1003.1 functions, hence supported in > the posix module (which we usually call "os" so it will appear that these > functions are supported on all platforms, whether they really are or not.) > > chmod == chmod() > chown == chown() > chgrp == chown() > rm == unlink() > mv == rename() > dd ~= read(), write(), lseek() > df == fstatvfs() > ... And some like 'dd' have a zillion options mainly because they are command line tools and aren't programmable on any finer scale. In python, it would be easier to just write a little function that does exactly what you want than it would be to remember all of the various option switches. -- Steve Majewski From cfelling at iae.nl Sun Mar 3 16:55:30 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 3 Mar 2002 22:55:30 +0100 Subject: Status of PEP's? References: Message-ID: Jeff Hinrichs wrote: > "Carel Fellinger" wrote in message > news:a5ro01$b3u$1 at animus.fel.iae.nl... >> How strange the world is, I now end up defending a proposal I'm >> against (or was against, I'm still in dubio) > Sometimes it is easier to reach the truth by arguing against your > position.(i.e. devil's advocate) Yep. E.g. I didn't get why negative numbers where excluded, so I enhanced the proposal in a way that seemed logical and straightforward to me. Then Emile came to dampen my new found joy pointing out that there were other ligitemate interpretations for negeative integers in the for construct if you kept an eye on slice notation. So maybe my enhancement turns out to be a counter argument in disguise. The fact that it doesn't work well with negative integers surely looks like a show stopper to me. We could ofcourse decide, like Guido did in the key versus item debat for iter(dict), that the `count down' meaning is the one to use, but I doubt it would be a good decision. But then who cares, I'm no language designer. > but continued reading states that, "The expression list is evaluated once; > it should yield a sequence." > So what is the [0,1,2,3,4] returned by the 5 in, for i in 5: , called? (I > realized it's generated by iterable object)The indici? > I'm still trying to understand so bare with me... > So if we say that, for i in 5: has the same result as, for i in range(5): > then what happens, if python adopts this idea, when you try: >>>>print 5 > do you get 5 or [0,1,2,3,4] ? `for i in 5' and `range(5)' both yield the same result, but achieve this via a different route. `for i in 5' is transformed by the interpreter to `for i in iter(5)'. This transformation is triggered by the `in' keyword, and as there is no `in' keyword in that print statement, no transformation takes place, and 5 remains 5. > Why only make integers objects? Is there support for making all numbers > objects? Integers, after all, are a subset of all numbers. They already are:) -- groetjes, carel From aahz at pythoncraft.com Mon Mar 25 15:21:38 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Mar 2002 15:21:38 -0500 Subject: avoid gui being blocked References: <3c9f7f9f.40054515@news.easynews.net> Message-ID: In article <3c9f7f9f.40054515 at news.easynews.net>, Marcus Stojek wrote: > >let's say I have a Dialog (using wxPython) with a button. >This button starts a function thats takes some time to >return. During this time the GUI is not responding to >any action of the user. How can I keep the GUI alive? Take a look at my web page, and read the slides and examples from my OSCON2001 threading tutorial. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From cfelling at iae.nl Sat Mar 2 18:41:53 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 3 Mar 2002 00:41:53 +0100 Subject: Status of PEP's? References: Message-ID: How strange the world is, I now end up defending a proposal I'm against (or was against, I'm still in dubio) Jeff Hinrichs wrote: > "Carel Fellinger" wrote in message > news:a5pmvd$fic$1 at animus.fel.iae.nl... >> Jeff Hinrichs wrote: >> >> > What you are asking everyone to agree with is: >> > 5 = [0,1,2,3,4] >> >> No he isn't:) He explicitly says he doesn't think of sequences at all. > If it walks like a duck and talks like a duck... > It's a duck. How can one iterate over something that is not a > sequence/collection? This used to be the case in Python, but the invention of iterators has changed the landscape. The for-construct no longer works on sequences, it works on iterable objects. So it's not right anymore to reject such a proposal based on that the thing isn't a sequence. You now must reject it if you feel the thing can't be iterated over. This may seem like a word play, but it isn't, it's a vital though subtle difference. And it took me, being an old farth, quit some time to let it sink in. >> ... >> > If you were to restate the above as: >> > f(5)=[0,1,2,3,4] >> > Then, I believe, that you wouldn't have any problem convincing a large >> > majority that it is possible for f() to produce such an output. That > being >> >> And this is precisly what he's proposing, f is called iter in his >> case. > But this is already in the language. It is called range/xrange. I haven't ... Ah, missing smiley. The pun here was that the for loop calls the iter function, so the sole 5 there actually is a iter(5) to the interpreter. And f(5) turns into iter(5) when you replace f by iter:) Apart from that, your point of lacking convincing arguments for change is one of the reasons I'm still contemplating my stanze. > a) readability > b)robustness > c)minimizing bugs Ah my proposed change for down counting sure is a candidate for bug minimalisation, as one often makes one-off errors in the range call needed to achieve the same effect:) >>He comes from the camp that sees everything as an object, so ... > But I don't accept this. **Not everything is an object.** An apple is an Fair, and as I explained in an other post quit close to my believes. But it *is* a standard way of looking at the world in OO circles. >>Like the `for' >> construct recently got stretched to mean `over all lines' and `over >> its keys' for text-files and dictionaries. Admitted in those cases it >> still was a clear `iterate over', but the what was debatable. > The reason for this, is that it is natural to view a file/keys as a > collection. It is not natural to consider a number as a collection of other > numbers. No it's because it's natural to *iterate* over the keys of a dict. It's also natural to iterate over the values of a key, or over the key,value pairs, but general concensus changed recently to favor the key side. Quit a good thing I must say, for now it becomes so much easier to do generic programming in Python, now that files, dicts, sequences and what have you are unified in the way their iterating ability is used. >> >> > said, I would find that the argument favors the use of range/xrange over > the >> > concept of iterable integers. >> >> I'm still concerned how it releates to `programming for everybody', >> as that goal is a sure measure to keep Python lean and simple. > I am not sure whether you are referring to iterable integers or range/xrange > by the above. sorry for the confusion, english is not my native language. I still doubt that `for i in 5' is easily understood to mean what it's supposed to mean under this PEP. I don't have that reservation for range, and i still think I would prefer an extended range that could deal with iterable objects. My change in position is only that I now think I *understand* the proposal, not that I *like* it. So Jim finally got me to the point that for me it's a matter of preference:) -- groetjes, carel From lee.ingram at 432one.com Sun Mar 10 22:40:15 2002 From: lee.ingram at 432one.com (Lee Ingram) Date: 10 Mar 2002 19:40:15 -0800 Subject: Rule Engine in Python Message-ID: I have used Google to scour the web looking for an implementation of a rules engine using Python. I need a mechanism whereby slightly trained end users will be able to add / modify business rules and have them execute. I previously used Blaze Software's Advisor rules engine to do something similar. Has anyone seen, implemented, or tossed out this idea previously? Inquiring minds want to know... TIA Lee Ingram From woodsplitter at rocketmail.com Wed Mar 13 09:21:55 2002 From: woodsplitter at rocketmail.com (stalin) Date: 13 Mar 2002 06:21:55 -0800 Subject: Anonymous attribute/property possible? References: Message-ID: <7876a8ea.0203130621.798df8ff@posting.google.com> Excuse me, but haven't you read the Zen of Python? http://www.python.org/doc/Humor.html#zen Refer to #2: "Explicit is better than implicit." I can hardly think of any single feature that would be less Pythonic than the anonymous property. From greg at cosc.canterbury.ac.nz Mon Mar 18 01:00:12 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 18 Mar 2002 18:00:12 +1200 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: <3C95826C.648AC359@cosc.canterbury.ac.nz> Grant Edwards wrote: > > You don't have to read it 1 byte at a time. Just call > f.read(1024) and it will give you however many bytes are > available, up to the max of 1024. If you do this, keep in mind that what you get may not consist of a whole number of lines. After processing all the complete lines that you've got, you have to be prepared to put the rest aside and wait until select() tells you there's more to read. In other words, you have to do your own buffering. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From fperez528 at yahoo.com Sat Mar 16 09:05:07 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 16 Mar 2002 14:05:07 +0000 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: Jonathan Gardner wrote: > > It looks pretty good. However, it requires the users to install another > package just to install the main package. Mmh, what do you mean? I just said you'd need to install IPython if you want to test the code I sent you 'for real'. But what I gave you is basically a wrapper for Windows users which calls the -platform independent- setup.py first, and then does some windows-specific things. Maybe I'm misunderstanding you. > > I'll take a look at it, but isn't there a way to write some kind of > installation script in something native to windows? Again, I don't follow you. What do you mean by 'native to windows'? Do you mean binary-compiled, do you mean graphical, do you mean not in python??? Cheers, f. From huaiyu at gauss.almadan.ibm.com Mon Mar 18 14:52:35 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 18 Mar 2002 19:52:35 +0000 (UTC) Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: On Fri, 15 Mar 2002 23:58:28 -0500, Clark C . Evans wrote: >| I think items(x) can just piggy-back on the current iterator protocol, and >| can be made to work on any iteratable objects. > >Would "keys()/items()" be compatible with the iterator proposal? >It would be extending the iterator to return pairs... this might >be a bit divergent... I was not clear on this point, so let me try again. What I meant was that if you define items(A) to return an iterator, and write a program using 'for i,x in items(A)', it will work for any sequence A. Users who supply A do not need to do anything. The implementation of items(A) might reuse some of code implementing the implicit iterators. But it could be as simple as wrapping around iter(A). On the other hand, if you define A.items(), and write a program using 'for i,x in A.items()', it only works if A.items is defined. If later on you want to use it for a different kind of A, you have to make sure it has the right .items() method. This pushes the burden to the users of the program. Of course we can always have both, but each program using 'for i,x in something' has to decide what that something is. If it is A.items(), it puts one more constraint on A. If we do not check the growth of such constraints, eventually those collection classes would become like Java collection classes with many methods that are rarely used but has to be there just in case they might be needed in some situations. Huaiyu From weeks at vitus.scs.agilent.com Wed Mar 20 08:52:35 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Wed, 20 Mar 2002 13:52:35 +0000 (UTC) Subject: Popular style document? Message-ID: <1016641355.370859@cswreg.cos.agilent.com> Is there a popular style document for Python? I realize that there isn't a whole lot of scope for such a thing, but I wondered because of certain particular issues that came to mind. 1. I use "me" instead of "self" in method definitions. I mention this not to ask what people think -- I have an unpleasant suspicion -- but because I'll be using "me" below. 2. How should methods call other methods? Suppose that show_and_tell() simply calls show() and then tell(). Let the class be, say, "Demo". Then there are two choices: def show_and_tell(me): me.show() me.tell() def show_and_tell(me): Demo.show(me) Demo.tell(me) These have different semantics for subclasses, but I would hate to choose based on that. I simply use the first alternative. But only the second alternative was given in "Python Essential Reference" (by David Beazley). So I wonder. 3. Personally, I think that code is more readable (at least sometimes) when global variables are "declared". But how? If within a comment, what form does the comment take? Unable to answer that question, I found myself using a "global" statement, which is semantically a no-op and only acceptable if the reader knows what the heck it is doing there. These are hardly burning issues. But if these or similar issues happen to be addressed somewhere, I'd like to take a look. Greg From michael at stroeder.com Fri Mar 1 03:47:16 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 01 Mar 2002 09:47:16 +0100 Subject: ASV module, CVS modules References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: <3C7F4014.7090800@stroeder.com> John Machin wrote: > > You 2: On Windows, either use forward slashes "c:/test_data.csv" (it > works!) AFAIK this does not work on W2K anymore. I might be wrong. Ciao, Michael. From bkd at graphnet.com Wed Mar 20 10:18:47 2002 From: bkd at graphnet.com (Bruce Dykes) Date: Wed, 20 Mar 2002 10:18:47 -0500 Subject: classes for fun and newbies References: <3C989D10.5070409@mxm.dk> Message-ID: <0f5d01c1d022$8c0c0cf0$5102020a@graphnet.com> ----- Original Message ----- From: "Max M" Newsgroups: comp.lang.python To: Sent: Wednesday, March 20, 2002 09:30 Subject: Re: classes for fun and newbies > It would probably be simpler to it with just a function in this case: > > id = (0,5) > date = (6,11) > > def getPart(slice, line): > return line(slice[0]:slice[1]) > > print getPart(id, log[1]) > > or something like that. But just writing it in one big mess is probably > not out of the question either. > > for line in,lines: > id, date = line[0:5], line[6:11] > > But then you could do something like (untested). > > class Rec: > > def __init__(self, line): > self.line = line > > def __getattr__(self, attr): > if attr == 'id': > return self.line[0:5] > if attr == 'date': > return self.line[6:11] > > class Log: > > def __init__(self, fileName): > f = open(fileName,'r') > self.lines = f.readlines() > f.close() > > def __getitem__(self, index): > return Rec(self.lines[index]) > > def __len__(self): > return len(self.lines) > > Then you can use it like: > > log = Log('logfile.log') > print log[1].id > > or like: > > for item in log: > print item.id > > regards Max M Now, none of these seem as obvious-to-write or as readable-at-a-later-date as setting each record up as a class first. And setting up the class at the start seems to be almost self documenting (heck, I *generated* the class definition from the documentation 8-). Is there any particular reason to prefer using functions over class definitions, such as performance, or memory use? Or are we just speaking of stylistic differences? > Generally there is no need ti write objects before it is needed. Ie. > when your code violates the DRY (Dont Repeat Yourself) principle. As I said, it just seems more natural to me to define each record/line as an object, with each field being an attribute. aside: I realize that I'm actually building the guts of a database, but for something this small, it seems far more efficient to simply write the necessary text processing and search functions than to build a database in MySQL or PostgreSQL and then build the necessary connections and filters. A couple of Python scripts *must* be more lightweight than a fullbore database. bkd From amckay at merlinsoftech.com Wed Mar 13 18:10:34 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Wed, 13 Mar 2002 15:10:34 -0800 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: <200203132236.WAA11518@crown.off.ekorp.com> References: <20020313122953.B15069@ActiveState.com> <200203132236.WAA11518@crown.off.ekorp.com> Message-ID: <200203132309.g2DN9rq30923@mail.merlinsoftech.com> On March 13, 2002 02:36 pm, Richard Jones wrote: > > With bugzilla you can explicitly add yourself and remove yourself from > > the Cc lists of bugs. With roundup you get plopped onto a the nosy list > > of a bug by responding to traffic on the discussion. > > [snip] > > Roundup's use of the subject line of emails to carry bug attributes did > > not, in our experience, scale well. > > Have you investigated roundup recently? That is, since it was re-written > from scratch using the spec from the Software Carpentry project? Or are you > just making these statements based on several-year-old-knowledge? Yes I have and its much more than the Roundup Ping wrote. I was impressed by the quick play i had with the most recent version of Roundup, I don't know about a detailed feature comparison though, hopefully some of the more annoying features of the old Roundup have been patched / thrown out. Roundup has always struck me as a more of an issue tracker rather than a bug tracker which Bugzilla is aimed at. Bugzilla has lots of features and problems as well, but add email support to Bugzilla and you have a good scalable database with more features than Roundup. Unfortunately its in Perl :) I would recommend looking at both them to any one installing a bug tracker, but lets face it, the Python isnt likely to change soon ;) -- Andy McKay From thoa0025 at mail.usyd.edu.au Thu Mar 21 15:40:25 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Thu, 21 Mar 2002 20:40:25 GMT Subject: [newbie] embedding python Message-ID: Hi, im trying to embed some python into my c source in UNIX. i have absoutely no idea how to do this despite the tutorial on the web at http://www.python.org/doc/current/ext/building-on-unix.html#building-on-unix it's too general and not step by step enough for a noob like me :( i've found the Makefile director /local/usr/lib/python2.0/config/ . What must i do next?!? Please help. asap!!! Cheeeers From torstenson at no-spam.oti-hsv.com Mon Mar 4 14:04:56 2002 From: torstenson at no-spam.oti-hsv.com (Eric Torstenson) Date: Mon, 4 Mar 2002 13:04:56 -0600 Subject: open() error ---- what am I missing? References: <%6Og8.10755$hK4.4027177@e420r-atl1.usenetserver.com> Message-ID: OK I figured it out. It was a misleading error message. For those with similar troubles I have listed an explanation (and I was being stupid...I sort of figured as much) It was a bad path name after all. It is a nested structure, where at one point I left off one extra "\" (I'm using windows). I had looked at that path a dozen times, somehow missing that single "\" down toward the middle.... "Oleg Broytmann" wrote in message news:mailman.1015263607.7574.python-list at python.org... > On Mon, Mar 04, 2002 at 11:31:46AM -0600, Eric Torstenson wrote: > > self.fLog=open(filename, mode='w') > > IOError: invalid argument: w > > Do you have the os module imported? Especially in the form > "from os import *" or "from os import open"? > > Oleg. > -- > Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru > Programmers don't die, they just GOSUB without RETURN. > From phd at phd.pp.ru Sat Mar 2 10:27:57 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sat, 2 Mar 2002 18:27:57 +0300 Subject: Problems with multipart messages w/email class In-Reply-To: <1015006362.1673.7.camel@jwilhelm.ofsloans.com>; from jwilhelm@outsourcefinancial.com on Fri, Mar 01, 2002 at 11:12:42AM -0700 References: <1015006362.1673.7.camel@jwilhelm.ofsloans.com> Message-ID: <20020302182757.A8152@phd.pp.ru> On Fri, Mar 01, 2002 at 11:12:42AM -0700, Joseph Wilhelm wrote: > AttributeError: 'int' object has no attribute 'lower' This is well-known bug in the email package, and it was fixed in CVS. Please use the latest version from mimelib.sf.net. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jimd at vega.starshine.org Mon Mar 18 03:29:23 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 18 Mar 2002 08:29:23 GMT Subject: Optimising list comparison References: Message-ID: In article , Graham Ashton wrote: > A friend of mine is using Python in a research project where he needs to > compare each element of two vectors, such that comparing [a, b, c] and > [d, e, f] would involve comparing a with d, b with e and c with f. > The only possible values in either list are 0, 1 and -1. When comparing > two values, if either value is set to -1 then both values are deemed to be > equal. So we've got: > 0 == 0 > 0 == -1 > 1 == 1 > 1 == -1 > 1 != 0 > What he wants to know is simply whether all the values in the two lists > are "equal", in which case the comparison returns 1, otherwise it returns > 0. If I'm understanding you correctly then you should bel able to just use: map(lambda x,y: not (x+y == 1), a, b) Let me go back through your "truth" table and fill it out for all possible permutations: a b r a+b a+b == 1 0 == 0 1 0 0 0 == -1 1 -1 0 0 != 1 0? 1 1 1 == 1 1 2 0 1 == -1 1 0 0 1 != 0 0 1 1 -1 == 0 1? -1 0 -1 == -1 1? -2 0 -1 == 1 1? 0 0 ... the ? lines denote the ones that I've added, the r column is the (apparentely) desired result --- the only case where you want to return false (0) is if a or b are one AND the other is zero. I observe that in either of those cases the sum of a+b will be 1 (0+1 or 1+0). More importantly I note that ALL other cases the sum of a+b must NOT be 1 (4th column in my table). Finally I notice that this is the inverse of the (apparently) desired results in the third column. Thus the expression lambda x,y: not (a+b == 1) seems to work. But perhaps I misunderstand. I didn't do *any* benchmarking of this. It's just the simplest bit of code I could see that seems to match the desired table in a functionesque way. > ----cut---- > Cheers, > Graham. From thomas at gatsoft.no Mon Mar 11 03:09:01 2002 From: thomas at gatsoft.no (Thomas Weholt) Date: Mon, 11 Mar 2002 08:09:01 GMT Subject: Regular expressions newbie: something for templates References: Message-ID: > re.sub("\$([^$]+)\$","%(\g<1>)s",s) Ah, now I remember why I ditched Perl!! ;-) Anyway, thanks for your help! I now got several options to go with and they all seem to work just fine. Thanks!!! Thomas From gerhard at bigfoot.de Tue Mar 19 14:58:23 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 19 Mar 2002 19:58:23 GMT Subject: inheriting from curses window-objects References: Message-ID: Marco Herrn wrote in comp.lang.python: > Hi, > > i would like to create window-objects that are derived from the standard > curses windows (like window or pad). But I don't see any way to achieve > this. > Is this possible? No. But there's help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295 Btw. I had the exact same problem a few weeks ago: http://groups.google.de/groups?selm=mailman.1014046530.13105.python-list%40python.org > Or would I have to write a "new curses library" to get real objects > for window, one can inherit from? Fortunately, that's not needed. If you want to write a patch to make curses objects subclassable and submit it at Sourceforge, I'm sure it will be appreciated. By me, at least :-). Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From theller at python.net Fri Mar 1 10:33:10 2002 From: theller at python.net (Thomas Heller) Date: Fri, 1 Mar 2002 16:33:10 +0100 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7F6765.94A82394@engcorp.com> Message-ID: "Robin Becker" wrote in message news:PtFyMdAeY5f8EwjI at jessikat.demon.co.uk... > after investigation it seems that module nt is using > cmd.exe /c string > > to run programs and I can't find any way to quote things in the string. > A typically rubbish M$-ism. > -- > Robin Becker On win2k it seems to be even documented (for the first time?): C:\sf\python>type "\Program Files\test.py" import sys print sys.argv C:\sf\python>cmd /c ""\Program Files\test.py" "1 2 3" 4 5 "6"" ['C:\\Program Files\\test.py', '1 2 3', '4', '5', '6'] and here are the rules: C:\sf\python>cmd /? Starts a new instance of the Windows 2000 command interpreter CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] [[/S] [/C | /K] string] /C Carries out the command specified by string and then terminates /K Carries out the command specified by string but remains /S Modifies the treatment of string after /C or /K (see below) /Q Turns echo off /D Disable execution of AutoRun commands from registry (see below) /A Causes the output of internal commands to a pipe or file to be ANSI /U Causes the output of internal commands to a pipe or file to be Unicode /T:fg Sets the foreground/background colors (see COLOR /? for more info) /E:ON Enable command extensions (see below) /E:OFF Disable command extensions (see below) /F:ON Enable file and directory name completion characters (see below) /F:OFF Disable file and directory name completion characters (see below) /V:ON Enable delayed environment variable expansion using c as the delimiter. For example, /V:ON would allow !var! to expand the variable var at execution time. The var syntax expands variables at input time, which is quite a different thing when inside of a FOR loop. /V:OFF Disable delayed environment expansion. Note that multiple commands separated by the command separator '&&' are accepted for string if surrounded by quotes. Also, for compatibility reasons, /X is the same as /E:ON, /Y is the same as /E:OFF and /R is the same as /C. Any other switches are ignored. If /C or /K is specified, then the remainder of the command line after the switch is processed as a command line, where the following logic is used to process quote (") characters: 1. If all of the following conditions are met, then quote characters on the command line are preserved: - no /S switch - exactly two quote characters - no special characters between the two quote characters, where special is one of: &<>()@^| - there are one or more whitespace characters between the the two quote characters - the string between the two quote characters is the name of an executable file. 2. Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character. From andy at reportlab.com Fri Mar 8 16:11:18 2002 From: andy at reportlab.com (Andy Robinson) Date: Fri, 08 Mar 2002 21:11:18 GMT Subject: Autodiscovery of proxy settings from a python script References: Message-ID: Thanks to several people. I am once again stunned by how good the Python standard library is. I spent an afternoon surfing and assumed I'd have to write code, but urllib does most of what I want by default :-) Idiot's guide to proxy discovery and use: 1. if hacking at home, get a working proxy server. I found this which compiled fine and "sort of" works - dislikes GIFs but can receive plain pages: http://www.codeguru.com/internet/http_proxy.shtml 2. Thereafter, set the proxy in IE and you can do this: >>> urllib.getproxies() {'ftp': 'ftp://matterhorn:5060', 'http': 'http://matterhorn:5060'} >>> 3. Thereafter, calls to urllib.urlopen(myURL) seem to go through the proxy by default. - Andy From jkraska at san.rr.com Tue Mar 12 20:37:12 2002 From: jkraska at san.rr.com (Courageous) Date: Wed, 13 Mar 2002 01:37:12 GMT Subject: Is Python an object based programming langauge? References: Message-ID: <30gs8us5gur4rh593hl1iksf7f64thga95@4ax.com> >If you ask a smalltalker, he'll tell you python is not OO because... ...it doesn't have a proper message passing architecture. >if you ask a C++ hacker, he'll tell you python is not OO because ... ...it doesn't properly implement data hiding. >if you ask a Lisp programer, he'll tell you python is not OO because... ...it doesn't have multimethods. Of course, all of this is irrelevant, because all of these programmers have lost the forest for the trees; which is to say, being "object oriented" isn't nearly as important as what being object oriented achieves you. I'll leave what's really important as an exercise for the reader. From grante at visi.com Mon Mar 11 12:55:24 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Mar 2002 17:55:24 GMT Subject: wxProgressDialog wonky under Win32 Message-ID: Under Win32, the bargraph in a wxProgressDialog hits "full" about 10-20% of the way to the "max" value. The attached program illustrates this. The "cacnel" button changes to "close" at the correct point, it's just the bargraph that doesn't work right. It works fine under: RH7.2, Python 2.1.1, GTK 1.2.10, wxPython 2.3.2 Barphraph shows wonky behavior under: Win2K, Python 2.2, wxPython 2.3.2 Does anybody know how to get the bargraph to work right under windows? ------------------------------8<------------------------------ import time from wxPython.wx import * class MyButton(wxButton): def __init__(self, parent, ident, *argt, **argd): c = None if argd.has_key("command"): c = argd["command"] del argd["command"] wxButton.__init__(self, parent, ident, *argt, **argd) if c: EVT_BUTTON(self,self.GetId(),c) class MyFrame(wxFrame): def __init__(self, *argt, **argd): wxFrame.__init__(self, *argt, **argd) sv = wxBoxSizer(wxVERTICAL) sv.Add(MyButton(self,-1,"Go",command=self.progress)) self.SetSizer(sv) self.SetAutoLayout(1) sv.Fit(self) self.Show(1) def progress(self,event): size = 500000 dlg = wxProgressDialog("Downloading", "Downloading...", size, self, wxPD_CAN_ABORT | wxPD_APP_MODAL) bytes = 0 while bytes < size: time.sleep(0.1) bytes += 10000 print bytes if not dlg.Update(bytes): break class MyApp(wxApp): def OnInit(self): frame = MyFrame(NULL, -1, "Download") frame.Show(true) self.SetTopWindow(frame) return true MyApp(0).MainLoop() ------------------------------8<------------------------------ -- Grant Edwards grante Yow! LOOK!!! I'm WALKING at in my SLEEP again!! visi.com From wall at adinet.com.uy Fri Mar 22 16:24:02 2002 From: wall at adinet.com.uy (Walter Moreira) Date: Fri, 22 Mar 2002 18:24:02 -0300 Subject: PySequence_Check is always true on instances? Message-ID: <20020322182402.B7591@casa.parque> Hi. If I define a simple class >>> class eggs: ... pass >>> a = eggs() and I call PySequence_Check on the instance 'a', at C level, it returns 1. If the class is a new style class: >>> class eggs(object): ... pass >>> b = eggs() then PySequence_Check on 'b' returns 0. I proved this on Python 2.2 and 2.1 (couldn't download 2.2.1 yet). Is this a bug? If it is not a bug, which is the standard way to check that an object is sequence, in C? Thanks. Walter From brian at sweetapp.com Tue Mar 5 18:58:39 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 5 Mar 2002 15:58:39 -0800 Subject: Newbie Python+XML Question In-Reply-To: <3C85597D.D0DD25FE@bellsouth.net> Message-ID: <005301c1c4a1$abf34470$445d4540@Dell2> Jeff wrote: > % python2.1 testg.py > Traceback (most recent call last): > File "testg.py", line 26, in ? > class XmlHandler(saxutils.DefultHandler): > AttributeError: 'xml.sax.saxutils' module has no attribute 'DefultHandler' > > It looks like the SAX stuff is not getting imported correctly. > Does anyone feel like helping a lowly Newbie with this one? Easy one: you spelled "Default" incorrectly. Change 'DefultHandler' to 'DefaultHandler' everywhere in that script. Cheers, Brian From thoa0025 at mail.usyd.edu.au Fri Mar 29 22:51:42 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sat, 30 Mar 2002 03:51:42 GMT Subject: python cgi design patterns? Message-ID: Greetings, im looking for python cgi design patters. does anyone have any cool urls? i've found 1 and it's quite nice. http://www.webtechniques.com/archives/1998/02/kuchling/ Cheers trungie From brueckd at tbye.com Mon Mar 25 11:11:21 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 25 Mar 2002 08:11:21 -0800 (PST) Subject: Indentation problem In-Reply-To: <3C9F2341.1000802@udcast.com> Message-ID: On Mon, 25 Mar 2002, Gilles Diribarne wrote: > I've some problem with identing code. I'm allright with the example. > But, I think it's important to have an "end" building block like "!:" > > What do you think about that? Rather than changing the language, get a smarter code editor. The current way works very well for lots of people. > Why I would like to put this in the code? > 1/ Because it's almost impossible to paste python code with ident = n > spaces to another code with indent = m spaces How much code pasting do you do? It's common to do some, but 99% of it will probably be your own code, in which case you'll have the same number of spaces. Pasting in large blocks of other peoples' code is kinda scary anyway. > This kind of examples occurs more and more and you can indent the code > by hand when it's 10 lines of codes, but not 1000 code lines. This is sounding more and more like a hypothetical corner case and not a real problem you're encountering every day. I'd stick the 1000 lines in its own module anyway. > It prevents the re-use of code pieces. Copy/paste is one of the lowest and worst forms of code reuse - try reusing modules instead if you can. > 2/ Programmers wants independence: some wants to manage building blocks > with spaces, other with tabs, some wants length = 4 with tabs. Um, isn't this the problem you're complaining about? ;-) Seriously though, I'd always be willing to give up an insignificant amount of independence if it bought me fewer code headaches and more consistency. Just set a coding standard for your organization and the "problem" evaporates. > 2/ Emacs and a great number of editors cannot indent region, since the > building blocks are only in programmer's mind. ??? Are there any Python editors that do _not_ have this? I don't know of any... > 3/ A large number of programming language use this. C, PERL, Ruby, ... > Why not Python? Because Python isn't broken? Herd mentality and peer pressure are always poor reasons for doing anything. > 4/ Solve the problem of space and tabs length. But, we should keep the > indenting mode which produces beautifull syntax. Going back to the start of this post, I think the source of your pain has less to do with block delimiters and more to do with choice of editor and/or your approach to code reuse. Please don't think I'm trying to be rude, but if you're encountering this problem a lot then you're doing something wrong. -Dave From anthony at interlink.com.au Wed Mar 20 08:56:21 2002 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 21 Mar 2002 00:56:21 +1100 Subject: how to ask different DNS for gethostbyname? In-Reply-To: Message from koji@twinsun.com (Koji Nobumoto) of "20 Mar 2002 02:04:16 -0800." <8de6d3da.0203200204.31b083d9@posting.google.com> Message-ID: <200203201356.g2KDuLY06032@mbuna.arbhome.com.au> > Is there any way to use a DNS which is not looked up > when I just use the socket.gethostbyname(), without > changing /etc/resolv.conf or any system configuration? try pydns.sf.net -- Anthony Baxter It's never too late to have a happy childhood. From mlh at vier.idi.ntnu.no Wed Mar 20 22:52:17 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Thu, 21 Mar 2002 03:52:17 +0000 (UTC) Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: In article , Thomas Heller wrote: [...] >Gordon's installer also works on linux (and solaris?). >Myself I'm only working on windows, so there is no need for me >to extend py2exe to work on linux systems. If anyone is willing >to provide patches for linux (or other systems), and is willing >to maintain them, I will happily add him as developer ;-). :) Maybe some time far in the future, but at the moment I think I would have to expent too much time just to figure out how to do this... But even in the "windows-only" incarnation, I think it would be a nice switch to have in distutils to begin with. (It does so many other wonderful things -- why not this too ;) >Thomas -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From James_Althoff at i2.com Mon Mar 4 19:22:02 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 16:22:02 -0800 Subject: Status of PEP's? Message-ID: [David Eppstein] > It seems like it should be really easy to modify the parser to > parse "for" expression ":" > and then check whether the expression is an "in" or a > comparison... You might want to think this through a bit more since neither arbitrary "expression" nor arbitrary "conditional" is supported in the suggestions posted so far. Jim From phlip_cpp at yahoo.com Wed Mar 27 06:09:44 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 27 Mar 2002 11:09:44 GMT Subject: Where is an unbroke version of PyMagick? References: <63604d2.0203261631.7731b2e7@posting.google.com> Message-ID: Phlip wrote: > Hypo Nt: > > The version here says it's broken, and does not explain why: > > http://bel-epa.com/pyapache/Python/PyMagick/ > > When I build it, it complains about serious errors regarding its > opinion of the API found in ImageMagick-devel-5.3.3-5mdk.i586.rpm. > > Careful consideration of the matter reveals the possibility that the > library is broken because it's from last year and that ImageMagick is > recent. > > I don't want to do Magick to my Images thru C or C++. Could have taken a PIL, have gone with imlib2-ruby-0.1.0. cheerfully-jumping-ship'ly y'rs Phlip From mwh at python.net Thu Mar 14 08:51:25 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Mar 2002 13:51:25 GMT Subject: SF vs. Lynx (was Re: zlib vulnerabilities and python) References: Message-ID: aahzpy at panix.com (Aahz) writes: > In article , Michael Hudson wrote: > >> [Michael Hudson] > >>> > >>> But because mail from the sf tracker seems to be hitting the bit > >>> bucket, noone knows about this. > > > >sf support believe this is now fixed, btw. > > OTOH, I still can't submit my stupid bug report AFAICT. I don't see it, certainly. > Is there anyone who uses Lynx to access SF? I've used w3m in the past. Don't think I've actually submitted a bug, but I did modify them. Not recently. Cheers, M. -- 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 Moo at houston.rr.com Mon Mar 25 01:30:30 2002 From: Moo at houston.rr.com (Avi Homes) Date: Mon, 25 Mar 2002 06:30:30 GMT Subject: files and reading from them Message-ID: I am writing a dictionary to a file, like so f.write(str(Info)) and what it is writing to the file is the following.. {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} and if i write in two things, i get.. {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} {'IPrice': '2', 'IName': 'notworking, 'IDesc': 'annoying'} What i would like to do is pull a readline or somesuch.. and have it take in the whole thing, and then just let me assign that to a empty name, and turn it into a new dictionary.. like say file.seek(1) //thats how i'd go to the first place in the file correct? X=file.readline() and now i can say print X['IName'] ... and its turned into a dictionary.. i am most likely going about this *all* wrong. From phr-n2002a at nightsong.com Thu Mar 7 22:29:37 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 07 Mar 2002 19:29:37 -0800 Subject: [ANN] istring 1.0.1 released; announce list created References: Message-ID: <7x3czbag9q.fsf@ruckus.brouhaha.com> "Steven D. Arnold" writes: > obstacle keeping it from inclusion in the standard library. In the > meantime, it's practically like, say, an r or u string, except with > parentheses: > > >>> from neo.istring import istring as i > >>> l = [1,2,3] > >>> i('first value is $l.0') > 'first value is 1' It occurs to me, you could get rid of the parentheses by making the i object an instance of a class that overrides (say) division: >>> from neo.istring import istring as i >>> l = [1,2,3] >>> i/'first value is $l.0' 'first value is 1' From peter at engcorp.com Thu Mar 7 22:03:40 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Mar 2002 22:03:40 -0500 Subject: NoteTab Lite References: Message-ID: <3C882A0C.DB4B81B8@engcorp.com> William Kennedy wrote: > > Does anyone use the NoteTab series of editors for their coding, Is this anything like the NotePad series of editors? ;-) > if so do they have a Python library I can have. I confess to never having used the program, but I wonder if your question is very clear. Does the editor use Python as a scripting language, and you want a library of routines? Or are you asking for a set of configuration options for working with Python code? Or something else that isn't clear (to me)? Hoping this isn't more obvious to others.... -Peter From grey at despair.dmiyu.org Wed Mar 6 21:11:45 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 07 Mar 2002 02:11:45 -0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 17:57:57 -0800, David Eppstein wrote: > I started with a positive number n, Actually, you never defined what n was, positive or negative. It could have been either. I decided to start with a negative. > and claimed that it was hard to create and understand expressions such as > range(n-1,-1,-1). You said that if that was so hard, I should instead > simply create range(n-1,0) and reverse it. > range(n-1,0) is empty when n is positive. You should have told me to > reverse range(n). So, clearly, you did not understand the expression > range(n-1,-1,-1), contradicting your claim that range is easy to > understand. No, I decided that one might want to do something funky like: n=-9 range(n-1) That yields an empty set. Now, if you'd like to clearly define what N was beforehand instead of worrying about presumptions only you hold you might just have something. > I agree, there are already ways to do it. There are already ways to do > everything you might ever want to do in Python, because like most > sensible languages it's Turing-complete. So should we stop trying to > improve the language? No. However, building in specific case statements for narrow range perception problems is not improving the language, it is degrading it. > that the proposed syntax gives a simple easy-to-understand alternative. Easy-to-understand to David Eppstien, not to others. I do believe you nailed me with that, didn't you? > Anyway, according to > > it's not a problem if there's more than one way of doing things, but > there should preferably one obvious way. This proposal would give one > obvious way of doing most integer loops. Which we can already do. We also don't want to build in special syntax for every special case. See any discussion on while(1):. > That's not covered by the current proposal. It's supposed to be an > improvement, not a panacea -- now is a good time for another Tim-quote > "now is better than never", which is what we'll get if we wait for a > perfect solution to all our problems. How about coming up with your own arguments instead of quoting others. Just because someone's got a bug up their butt about their shortcomings and has a woody for some solution looking for a problem doesn't mean it should be implemented without thought or consideration. Point, after several messages, still stands. PEP is too restrictive, doesn't do anything other than complicate the language, has no compelling reason to be implemented, is nothing more than special syntax to solve one person's special nitpick. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From cliechti at gmx.net Thu Mar 21 17:56:17 2002 From: cliechti at gmx.net (Chris Liechti) Date: 21 Mar 2002 23:56:17 +0100 Subject: Telnet References: Message-ID: "Billy Ng" wrote in news:d4tm8.2110$oi.93984 @newsread2.prod.itd.earthlink.net: > Thanks! "\r\n" is the key. It works after I added into the write > (). functon > > Okay, now I have 2 more questions. > > 1) How can I save the returned data into a list? I tried to use > the read_all() function, but it just stops there. > > tn.read_until("ending line") > lines = [] > lines = tn.read_all() this simply replaces the list you bound to "lines" with a string containig all the data. read_all() will block until the other side closes the connection. if you can send a "quit","exit" or "logout"command to the other side it might hang up, so that this works but that depends on your server. > 2) I was also trying to do this, > > tn.read_until("beginnig line to grap") > lines = [] > lines = tn.read_until("ending line") same note as above > for line in lines > print line > > But it prints one character in each line yes, as "type(lines)" will point out its now a string and not a list bound to the name "lines" i don't see a method to read by lines in telnetlib. but you can do (untested): import cStringIO memfile = cStringIO.StringIO(tn.read_until("ending line")) for line in memfile.readlines(): print line chris -- Chris From amuys at shortech.com.au Tue Mar 26 02:37:37 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 25 Mar 2002 23:37:37 -0800 Subject: The OOM-Killer vs. Python References: <3c9e2b5f.9993062@news.t-online.de> Message-ID: <7934d084.0203252337.4e0e1325@posting.google.com> jimd at vega.starshine.org (Jim Dennis) wrote in message news:... > Personally I think the various libraries, compilers and applications > which are blindly allocating far more memory then they actually use are > really the heart of the whole overcommit problem. That might not be > Python (or it might be indirectly due to Python's use of some libraries > on your system, possibly it could be glibc and libm bloating). > Unfortunately memory is a shared resource, so it only takes one bad > appl. (so to speak) to ruin the whole basket for all of us. Unfortunately the alternative is a substantial performance hit. Note that with overcommit enabled, applications that over allocate but don't use the memory won't trigger the OOM, which is triggered by VM memory pressure. The issue with overcommit isn't so much that applications get killed when the system actually does run out of memory, but that applications get killed asynchronously accessing successfully malloced memory (ie, believed a promise the OS made, which it couldn't deliver on) when they may have been perfectly willing to do a graceful recovery if they had been given -ENOMEM on malloc. The problem with not overcommitting is that system calls are signifigantly slower then function calls, so malloc libraries normally block allocate memory to save reduce the number of syscalls made. Another popular optimisation trick is to use anonymous mmapping of /dev/zero to provide memory pools for malloc. These are routinely over-committed. OTOH, the clincher is that regardless of any overcommit flag, if you permit them (and they are very very useful :) private, rw, mmap's can always leave you with undefined current memory allocation, and therefore vunerable to overcommitting. Andrae Muys P.S. I may be mistaken, but IIRC this was the final resolution of the overcommit flag thread. ie. Any suggestion that you can actually avoid overcommitting provides a false sense of security or tends to break the very applications that make it an issue, so you're better off not pretending to offer it or at least making it an obscure config option for people who understand the consequences of enabling it. From tim at vegeta.ath.cx Tue Mar 12 00:39:26 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Tue, 12 Mar 2002 05:39:26 GMT Subject: Is Python an object based programming langauge? References: Message-ID: Graz Bukanoff graced us by uttering: > Is Python an object based programming langauge? According to Smalltalk enthusiasts, definitely not. According to some Pythonistas, yes. IMNERHO, Python is object _oriented_, but not object _based_. I don't fault Python for this; it was a design decision, and probably a good one. If the question were "Can Python model my OOP idea?", the answer is an emphatic yes. HTH Tim Hammerquist -- All language designers are arrogant. Goes with the territory... :-) -- Larry Wall in <1991Jul13.010945.19157 at netlabs.com From marduk at python.net Tue Mar 5 08:04:53 2002 From: marduk at python.net (marduk) Date: Tue, 05 Mar 2002 07:04:53 -0600 Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> Message-ID: <3c84c0d4_4@Usenet.com> You're better off using htmllib (and httplib for that matter). I haven't looked at your examples, but I can tell just by looking at your code that it will fail, for example, when "" and "" are on seperate lines in the HTML. Also, I might be mistaken, but it doesn't look like you are re search is case insensitive. Either way, try the htmllib. It takes care of all that stuff for you! --m On Tue, 05 Mar 2002 06:43:10 -0600, Simon Willison wrote: > I've written a simple Python script to scan a bunch of URLs for "live" > sites and grab the title of those pages. It works by using popen() to > call lynx and analyse the HTTP response: > > ----------------------------------------------------------------- > > command = "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~"+user+"/" > f = os.popen(command) > l = f.readline() # Read first line of output, the HTTP status line try: > # Look for '200' HTTP status code indicating page exists i = > l.index('200') > except ValueError: > i = 0 > if i: > print "Web page exists!" > # Now try and get the title of the page for line in f.readlines(): > line = string.strip(line) > # look for * using regular expression result = > re.search('\s*([^<]*)\s*', line) if result: > # Found the title > title = result.group(1) > found[user] = title > print "Page Title: " + title > break > if not found.has_key(user): > found[user] = "[unknown]" > > ----------------------------------------------------------------- > > You can see the output of the script here: > > http://www.bath.ac.uk/~cs1spw/cs1sites.html > > As you can see, the code works fine for most pages but fails to grab the > tag on some of them (resulting in an [unknown] entry in the > list). I've checked the HTML for these pages and a <title> tag > exists in a form that should be picked up by my regular expression, but > for some reason it just doesn't work. > > Any ideas? Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From missive at frontiernet.net Sat Mar 9 17:20:50 2002 From: missive at frontiernet.net (Lee Harr) Date: Sat, 09 Mar 2002 22:20:50 -0000 Subject: Newbie question References: Message-ID: On Sat, 9 Mar 2002 21:34:26 -0000, Nick wrote: > How do you get the ordinal value (ASCII) of a character? For example, to > make a ROT13 program. > > >>> ord('a') 97 >>> 'abcdef'.encode('rot13') 'nopqrs' [the second one requires 2.2] From senux at senux.com Fri Mar 29 03:49:32 2002 From: senux at senux.com (Brian Lee) Date: Fri, 29 Mar 2002 17:49:32 +0900 Subject: multicast test program Message-ID: <20020329084932.GA4359@jupiter.senux.com> Is there any python code which test multicast? I want to send and receive multicast packet by python code. Any docs or links about this? -- ____ |o | i / Brian Lee #######|< Web - http://www.senux.com/en/ (x-x-x-x) \ GnuPG public key - 0x46C763A3 From tdelaney at avaya.com Tue Mar 19 01:44:28 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 19 Mar 2002 17:44:28 +1100 Subject: Java and Python Message-ID: > From: Ahmed Moustafa [mailto:amoustafa at pobox.com] > > 1. Where can I find an unbiased comparison between Java and Python? Nowhere. The best place to look though is http://www.python.org/doc/Comparisons.html which has comparisons with various languages. > 2. Will Python dominate? Of course! Actually, no language will ever dominate, and Java and Python are not mutually exclusive (in fact, there is an implementation of Python which runs on top of the Java VM and has full access to all java classes, etc ... http://www.jython.org/. > 3. Who does support Python? What type of support are you talking about? If you want commercial support, I think ActiveState gives it. If you are talking about who maintains and enhances Python, that's the Python development team in general (but with a lot of community involvement. If you are asking these questions to decide if you should learn Python, don't bother - the answer is an unqualified "yes". Python is very easy to learn, and will make it much easier to learn other languages. If you are asking to decide if you should learn either Java or Python, the answer is "no" - learn both. Then learn a few more languages. But Python is a great language to start with. Tim Delaney From mhammond at skippinet.com.au Tue Mar 19 02:23:04 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 19 Mar 2002 07:23:04 GMT Subject: modifications of PythonWin? References: Message-ID: <3C96E764.6070101@skippinet.com.au> Alex K. Angelopoulos wrote: > Per Murphy's law, I will stumble across this 30 seconds after I post. > > I'm looking for information on the PythonWin IDE - specifically, any modifications or customizations that may have been done to it in the past. I have found the sources to it, of course, as well as the basic documentation on it - which seems to be very well done, but is a bit dense for someone who is "MSVC-impaired" such as myself. I'm grinding through it right now, but I think I would do a bit better if I could see some "hacks" that have been done to it... > > Is anyone aware of open modifications made to the PythonWin environment for special purposes - hopefully with links or a couple of search terms I can use to find such mods? I've come up with nothing but the "real" PythonWin using PythonWin as a search term. I don't know of any. Modifications and customizations tend to be for "in house" or limited distribution projects. I know of a few, but they have no public information. Pythonwin itself is exactly what you want, though! Many many features have been contributed by users over the years. Mark. From gs at styrax.com Mon Mar 11 11:13:12 2002 From: gs at styrax.com (Garry Steedman) Date: Mon, 11 Mar 2002 16:13:12 +0000 Subject: (Fwd) Re: Need Help in Plone Message-ID: <3C8CD798.19910.253BB556@localhost> michael, 'fraid you'll have to bend your mind round CMF first! plone isnt difficult to understand once you know how CMF works... check out CMFDocumentation.stx in the /doc directory below your CMF install (its there in CMF-1.2 anyway), then you might want to read: http://cmf.zope.org/CMF/Members/beehive/ZWACKChap5.html enjoy ;-) garry On 11 Mar 2002, at 6:59, Michael Toldo wrote: From: Michael_Toldo at hotmail.com (Michael Toldo) Subject: Need Help in Plone Organization: http://groups.google.com/ To: python-list at python.org Date sent: 11 Mar 2002 06:59:17 -0800 > I installed the newest version of Plone. But now I have to adapt it > to a cms. The different objects and the different templates make me > crazy. Can anybody tell me, where to get a usefull documentation. > > Mick > -- > http://mail.python.org/mailman/listinfo/python-list +-------------------------------------------+ Garry Steedman mailto:gs at styrax.com Styrax Associates http://www.styrax.com/ "The Good Man has no shape." +-------------------------------------------+ From brian at lodoss.org Mon Mar 4 04:51:19 2002 From: brian at lodoss.org (Brian) Date: 4 Mar 2002 01:51:19 -0800 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <3C82F9F0.2A2DBF16@engcorp.com> <3C82FD24.122E16B3@engcorp.com> Message-ID: <8fc4b19e.0203040151.de463c8@posting.google.com> Peter Hansen wrote in message news:<3C82FD24.122E16B3 at engcorp.com>... > Peter Hansen wrote: [..snip..] > > (I'd suggest if you're just trying to save typing five > > keystrokes that you find more critical things to work on first.) Actually, I did. I left the less critical item for someone on the NG to answer for me. ;-) > Oops, sorry. That sounds a little callous. I really just meant > to give a response similar to my "programmers always try to optimize > when they don't really need to" diatribe. I originally meant to ask a question more along the lines of "what is the most pythonic way of doing this." Then I decided all that extra typing in my message was suboptimal. Was that something that didn't really need optimization? Thanks for the welcome. :) From jriveramerla at yahoo.com Tue Mar 26 18:27:32 2002 From: jriveramerla at yahoo.com (Jose Rivera) Date: 26 Mar 2002 15:27:32 -0800 Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> <11e94203.0203232201.4dde9883@posting.google.com> <20020324081829.193$iP@news.newsreader.com> Message-ID: <11e94203.0203261527.89fb2ca@posting.google.com> >>Is there a better way? > A better way of what? I missed the original post. I mean a better way of fetching the info from the Web Page, I like Python, but if anyone knows of any utiliy that can download that pages automatically to text files... that would be great. Because it would be more easy for me to process the info in Python from files saved on disk, than from WEB PAGES. Taking in account that this is the first time I am using urllib library. Thanks... From grante at visi.com Sun Mar 10 11:31:51 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 16:31:51 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> <3c8b8112.27836128@news> Message-ID: In article <3c8b8112.27836128 at news>, brobbins333 at shaw.ca wrote: > OK, that makes perfect sense. In my case, I was simply looking > for a predictable way to return a number with two decimal > places That's just not possible. The "number" you're talking about doesn't _have_ decimal places. It's a binary floating point number. It has "binary places". In theory you could write a function that rounds to N binary places, but I don't know how useful that is going to be. In order to talk in a meaningful way about decimal places, you have to use a base-10 representation: BCD floating point or BCD fixed point. Strings such as "123.456" are sort-of BCD floating point, and you can round to N decimal places when converting from binary floating point to "String/BCD FP": f = 123.4567 s = "%0.2f" % f >>> f = 123.456 >>> s = "%0.2f" % f >>> f 123.456 >>> s '123.46' "String/BCD FP" as I've termed it can represent numbers just fine, but since you can't do any mathematical operations on them it's of limited value. Since you're using binary floating point, the round() function is actually converting it's binary floating point input value to the closest value to X such that if X were converted to BCD in the future it will have the requested number of decimal places. But, X may not be exactly representable. If you're using round(x,N) your probably just fooling yourself. If you _really_ do want a number with N decimal places: the topic of base-10 numbers for Python comes up occasionally, and I believe that there are BCD packages available. If you really want to do your calculations in base 10, you might want to search the newsgroup archives for "BCD". -- Grant Edwards grante Yow! Please come home with at me... I have Tylenol!! visi.com From joonas at olen.to Fri Mar 15 16:11:47 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Fri, 15 Mar 2002 23:11:47 +0200 Subject: Library for wmf/emf to png conversion? References: Message-ID: <3C926392.E8B3346C@olen.to> dominikush wrote: > > Hi, > > does anybody know of a python library that enables > conversion from a > > (Enhanced) Windows Metafile > to > png Python Imaging Library supports Wmf atleast partitially. Maybe this works? import Image Image.open("pic.wmf").save("pic.png") From rpm1deletethis at frontiernet.net Sat Mar 9 08:23:11 2002 From: rpm1deletethis at frontiernet.net (RPM1) Date: Sat, 9 Mar 2002 08:23:11 -0500 Subject: Q: How can I lock a file in Windows? References: Message-ID: > Thanx! That should work, except I don't seem to have the following > extension modules ... win32con, win32file, and pywintypes. Any idea where I > can get them? > > Go here and get the windows extensions. http://starship.python.net/crew/mhammond/ Active State's python comes with them already. Python Labs needs the extension module. Patrick From robin at jessikat.fsnet.co.uk Sat Mar 30 03:35:33 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 30 Mar 2002 08:35:33 +0000 Subject: PEP 285: Adding a bool type References: Message-ID: <2zRcLUAVjXp8EwVv@jessikat.fsnet.co.uk> In article , Guido van Rossum writes ...... This pretty much seems unwanted to me. Done purely for political correctness. Whenever new keywords are discussed the Gods are against them. Now we have to accept new constants true, false + a new type. Silly like all those programmers who have constants like one and zero or ten in code. If we get bools can sets be far behind, and what about quaternions and abelian groups? >Review > > Dear reviewers: > > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. no. If needed implement a library module for those who want to bog down their code. This will not improve the python interpreter one bit and has already consumed vast quantities of hot air ie has taken time and effort away from more important issues. > > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) > if yes to 1, str(true) == "1", str(false) == "0" > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). > > Most other details of the proposal are pretty much forced by the > backwards compatibility requirement; e.g. True == 1 and > True+1 == 2 must hold, else reams of existing code would break. > true, false > Minor additional issues: > > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). Personally, > I think we shouldn't; 28+isleap(y) seems totally reasonable to > me. > no true==1, false==0 is what's required. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. int -- Robin Becker From nospam at bigfoot.com Mon Mar 18 18:06:32 2002 From: nospam at bigfoot.com (Gillou) Date: Tue, 19 Mar 2002 00:06:32 +0100 Subject: Syntax color hightlight References: <3C966603.5010605@club-internet.fr> Message-ID: Perhaps you should consider using scintilla for this. I'm (pretty successfully) working on a DTML editor with it. There's a scintilla wrapper class in wxPython (www.wxpython.org). You can have a look at this too... http://archaeopteryx.com/opensource/pyscintilla "Fabien Henon" a ?crit dans le message news: 3C966603.5010605 at club-internet.fr... > I am writing a text editor for POV-RAY (with Python-Tkinter) and > I'd like to know if it is possible to implement syntax color > highlighting for a specific language. > I'd like to implement <>,(),[] matches as well. > Is Tkinter powerful enough or do I have to use megawidget, wxpython. > > Thanks > From claird at starbase.neosoft.com Fri Mar 1 19:54:39 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 1 Mar 2002 18:54:39 -0600 Subject: What readers want (was: Deitel and Deitel Book...) References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> Message-ID: <91F926228151D5F5.946DE1D959605688.72F5DF01B36707F9@lp.airnews.net> In article , DeepBleu wrote: . . . >> I would love to see books on Algorithms with Python (makes a perfect >> fit), and more advanced topics such as threads and extending python. > >I'd love to see something like that specially on threads and extending >Python. This is something I can use. >DeepBleu > > How would you feel if such material appeared in magazines rather than books? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From tim.one at comcast.net Tue Mar 5 19:50:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 05 Mar 2002 19:50:10 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: Message-ID: [Huaiyu Zhu] > ... > 1. The -lieee is indeed the most direct cure. On the specific platform tried. The libm errno rules changed between C89 and C99, and I'm afraid there's no errno behavior Python can rely on anymore. So I expect more changes will be needed in Python, regardless of how things turn out on this specific platform. > ... > 2. Is there a configure option to guarantee -lieee? If anyone can answer this question, please don't answer it here: it will just get lost. Attach it to Huaiyu's bug report instead: Thanks. > ... > 3. errno 34 (or -lieee) may not be the sole reason. > > On a RedHat 6.1 upgraded to 7.1 (both gcc and glibc), errno 34 > is indeed raised in a C program linked without -lieee, and Python is > indeed compiled without -lieee, but Python does not raise > OverflowError. I expect you're missing something. Skip posted the Python code before, and if errno gets set, Python *does* raise OverflowError: errno = 0; /* Skip forgot to post this line, and it's important */ ... ix = pow(iv, iw); ... if (errno != 0) { /* XXX could it be another type of error? */ PyErr_SetFromErrno(PyExc_OverflowError); return NULL; If you can read C, believe your eyes . What you may be missing is what an utter mess C is here. How libm behaves may depend on compiler options, linker options, global system flags, and even options set for other libraries you link with. > ... > 4. Is there an easier way to debug such problems? The cause was obvious to the first person (Skip) who stepped into Python to see what the code did on a platform where it failed. It's not going to be obvious to someone who doesn't. > 5. How is 1e200**2 handled? It goes through exactly the same code. > Since both 1e-200**2 and 1e200**2 produce the same errno all the time, > but Python still raises OverflowError for 1e200**2 when linked with > -lieee, there must be a separate mechanism at work. You're speculating from a false base: if platform pow(x, y) sets errno to any non-zero value, Python x**y raises OverflowError. What differs is when platform pow(x, y) does not set errno. In that case, Python synthesizes errno=ERANGE if the pow() result equals +- platform HUGE_VAL. > What is that and how can I override it? Sorry, you can't override it. > I know this is by design, but I think the design is dumb (to put it > politely). I won't get into an argument here. I'll write > up my rationale against this when I have some time. I'm afraid a rationale won't do any good. I'm in favor of supplying full 754 compatibility myself, but: A) Getting from here to there requires volunteers to design, implement, document, and test the code. Given the atrocious state of C's 754 story, and the subtlety of 754's requirements, this needs volunteers who are both 754 experts and platform C experts. That combination is rare. B) Python's floating-point users will never agree it's a good thing, so such a change requires careful backward compatibility work too. This isn't likely to get done by someone who characterizes the other side as "dumb (to put it politely)" <0.9 wink>. Note that the only significant floating-point code ever contributed to the Python core was the fpectl module, and its purpose is to *break* 754 "non-stop" exception semantics in the places Python happens to let them sneak through. > I do remember there being several discussions in the past, but I don't > remember any convincing argument for the current decision. Any URL > would be greatly appreciated, beside the one pointed by Tim. Which "current decision" do you have in mind? There is no design doc for Python's numerics, if that's what you're looking for. As the text at the URL I gave you said, much of Python's fp behavior is accidental, inherited from platform C quirks. From greg at cosc.canterbury.ac.nz Mon Mar 11 19:08:22 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 12 Mar 2002 13:08:22 +1300 Subject: Syntax to catch specific exceptions ? References: <3C8BD227.7D1D5539@vip.fi> <6vQi8.24234$n4.4716288@newsc.telia.net> <3C8C6315.9020805@vip.fi> Message-ID: <3C8D46F6.4637A6B8@cosc.canterbury.ac.nz> pekka niiranen wrote: > > So I will end up writing function with a huge "if-else"-structure > under except -clause > that catches all cases I want react to? Sounds like C. Perkele ;) You could keep a tuple of all the error numbers you're interested in somewhere and use 'in' to test membership of it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From mike at csc.liv.ac.uk Wed Mar 13 15:00:54 2002 From: mike at csc.liv.ac.uk (M.Beis) Date: Wed, 13 Mar 2002 20:00:54 -0000 Subject: telnet Message-ID: Hello everybody, I'm connected to a network with a number of telnet servers. I want to get a list with the names (hostnames) of each availiable server. Any ideas?? Thanks Mike From olc at openlearningcommunity.org Sat Mar 23 13:02:16 2002 From: olc at openlearningcommunity.org (Michael Hall) Date: Sun, 24 Mar 2002 03:32:16 +0930 (CST) Subject: MySQLdb Message-ID: G'day All: I've been writing PHP/MySQL for a couple of years now and am now cross-skilling into Perl and Python. I'm interested in web database integration for Python CGI scripts. Is this the right list for general questions about using the MySQLdb module? If so: I have installed the MySQLdb module but find the docs pretty sparse. Can anyone suggest a good tutorial that demonstrates the basic moves in extracting and printing data using MySQLdb? I guess I'm looking for a `translations' of PHP routines like: $query = mysql_query("$sql"); while ($row = mysql_fetch_array($query)) { $data0 = $row[0]; $data1 = $row[1]; } Also, a newbie-friendly discussion of MySQL modules (history/variety) and things like MySQLdb versus _mysql would be helpful. If not: Where do I go? Thanks Mick ----------------------------- Michael Hall mick at ninti.com ----------------------------- From huaiyu at gauss.almadan.ibm.com Mon Mar 4 19:30:09 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 5 Mar 2002 00:30:09 +0000 (UTC) Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> <87sn7g2stu.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: On 05 Mar 2002 01:36:29 +0900, Stephen J. Turnbull wrote: > Consider: does it make sense to concatenate a >string of Java byte codes with a string of English text? To produce a kind of tar file, perhaps? To send something through socket? There are certainly many cases where one wants to manipulate a byte sequence without any interpretation of it as a character string. If the discussion is only concerned with source code encoding, that's fine. But if it in the end restricts the kind of operations that can be performed on raw strings, it's simply untenable. Huaiyu From neal at metaslash.com Tue Mar 26 18:31:48 2002 From: neal at metaslash.com (Neal Norwitz) Date: Tue, 26 Mar 2002 18:31:48 -0500 Subject: seek in a file References: Message-ID: <3CA104E4.266A68F2@metaslash.com> Andreas Penzel wrote: > > Hello NG! > > How to jump to a specified line in a file which is read-opened? > With seek() I can jump to an exact position of the complete file in > "byte-steps". > Is seek able to jump to a line-number? > If not, what else can I do? seek() only works in bytes. This should work: >>> f = open('/etc/termcap') >>> lines = f.readlines() >>> print lines[0] ######## TERMINAL TYPE DESCRIPTIONS SOURCE FILE >>> print lines[1] # etc. lines is a list of strings (which include the newlines). Neal From grante at visi.com Sun Mar 10 02:12:16 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 07:12:16 GMT Subject: wxPython: generating event IDs? References: <3C8B0273.A3651580@engcorp.com> Message-ID: In article <3C8B0273.A3651580 at engcorp.com>, Peter Hansen wrote: >> There must be a way to eliminate the need to predefine unique >> ID numbers. I hate trying to maintain lists of numbers like >> that (well, more accurately, I'm just bad at it). > This little method which I've used inside a wxFrame subclass > demonstrates a slightly simpler approach than "define a unique > ID number". Note the use of wxNewId() to make that part > trivial. If you attach your commands to buttons using a > method you can wrap the little bit of ugliness and never have > to see it again: Thanks. I'll keep that in mind. Here's what I came up with for buttons: class MyButton(wxButton): def __init__(self, parent, ident, *argt, **argd): c = None if argd.has_key("command"): c = argd["command"] del argd["command"] wxButton.__init__(self, parent, ident, *argt, **argd) if c: EVT_BUTTON(self,self.GetId(),c) The usage of MyButton() is identical to wxButton() except you can add a command=self.foobar: MyButton(self,-1,"Button Text",command=self.buttonCommand) -- Grant Edwards grante Yow! I'm dressing up in at an ill-fitting IVY-LEAGUE visi.com SUIT!! Too late... From gimbo at ftech.net Wed Mar 6 12:08:01 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 6 Mar 2002 17:08:01 +0000 Subject: Status of PEP's? In-Reply-To: <20020306135242.GB10985@andy.tynant.ftech.net> References: <3C861BEB.60701@destiny.com> <20020306135242.GB10985@andy.tynant.ftech.net> Message-ID: <20020306170801.GE10985@andy.tynant.ftech.net> On Wed, Mar 06, 2002 at 01:52:42PM +0000, Andy Gimblett wrote: > This just came to me: > > for index in indices(items): > pass > > or maybe better yet: > > for index in items.indices(): > pass > > ? I've just seen PEP 212 which contains this very proposal... Should have known someone would have thought of this before! :-) -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From peter at engcorp.com Wed Mar 27 01:35:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Mar 2002 01:35:37 -0500 Subject: instrumenting Python code References: <1010a26.0203262213.4a0d4b11@posting.google.com> Message-ID: <3CA16839.1A21E36A@engcorp.com> Amir Michail wrote: > > I was wondering if there is an easy way to instrument Python code > so that I can collect information about a particular execution. In > particular, I am interested in collecting the following info: > > * functions called in execution > > * which function called what other function (the call graph) > > * the values of local/global variables > > It seems I can get all this from the debugger module though it doesn't > appear to have been designed to be used from another program. The profiler > module only gives the first item above. Among other things, you might want to check out the use of sys.settrace() (see the sys module) and the standard module 'profile' or the trace module included as python/Tools/Scripts/trace.py. -Peter From h.e.w.frater at cs.cf.ac.uk Tue Mar 5 06:35:58 2002 From: h.e.w.frater at cs.cf.ac.uk (Hugh) Date: 5 Mar 2002 03:35:58 -0800 Subject: Problems importing anything using _socket Message-ID: Hi all, I'm totally new to python, but have decided to use it to do a first year uni project. I've got to develop a web based library. I'm using oracle with the DCOracle2 module, and that works fine. But I can't import anything that uses _socket. If I try and do an "import cgi" frok inside the interpreter, I get this message: >>> import cgi Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.2/cgi.py", line 39, in ? import urllib File "/usr/local/lib/python2.2/urllib.py", line 26, in ? import socket File "/usr/local/lib/python2.2/socket.py", line 41, in ? from _socket import * ImportError: No module named _socket >>> import cgi >>> However, As you can see from above If I then type and run the line "import cgi" again, it forks fine. Any ideas? Thanks Hugh (Cardiff, UK) From peter at engcorp.com Sat Mar 2 00:32:32 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 02 Mar 2002 00:32:32 -0500 Subject: Want to monitor process.. References: <87550ef1.0202272315.15779bbd@posting.google.com> <97ae44ee.0202280901.3153bdfc@posting.google.com> <3C7EC9C6.D11FB17@engcorp.com> <97ae44ee.0203010102.14ebf2bb@posting.google.com> <3C7F66AB.D51BEA03@engcorp.com> <97ae44ee.0203011909.620b829b@posting.google.com> Message-ID: <3C8063F0.8BBD4A5C@engcorp.com> Stephen wrote: > > Peter Hansen wrote in message > > I'm not sure what the interactive thing would add, since the > > interpreter will already print exception tracebacks to the console > > whenever your program exits exceptionally. If you aren't seeing > > a traceback, maybe you aren't really exiting with an exception. > > Sorry, I should have explained that the reason I don't see the output > is that I run the programs in the background since I log into the > servers from remote and don't want the programs exiting when I log > out. Ah, I understand now. Could you just redirect stdout to a file for those? Then when they've crashed, you'll be able to pop in and check the log. -Peter From tim at vegeta.ath.cx Tue Mar 12 17:47:23 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Tue, 12 Mar 2002 22:47:23 GMT Subject: Is Python an object based programming langauge? References: Message-ID: Roy Smith graced us by uttering: > In article , > > What does he think of Ruby? > > He thinks it's pretty cool. To the best of my knowledge, he's never > written a single line of code in either Ruby or Python, but he's sure > Ruby is a much better language. Funny how that works :-) Tell him to try them! He may very well come to the same conclusion, but at least he'll have experience to back it up! I don't think that any language is "better" than another (with the obvious exception of VB), and there are certain projects that Python excels at, and others that Ruby excels at. The real determining factor, though, is the programmer's preference. I only hope it's a preference based on experience and not solely on opinions. Cheers, Tim Hammerquist -- It's illegal in Wilbur, Washington, to ride an ugly horse. From p.magwene at snet.net Fri Mar 22 21:15:29 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sat, 23 Mar 2002 02:15:29 GMT Subject: The IDE is important too [was Develop-test-debug cycle] References: Message-ID: On Fri, 22 Mar 2002 20:54:59 -0500, Dale Strickland-Clark wrote: > If you could fix all these four requirements, I reckon you could more > than quadruple my productivity on large projects. > > > i.e. What can YOU do for ME today?! Sure, there's lots of gee-whizness we'd all love to see in Python IDEs, but since I ain't payin' for it I try not to moan too much about it. Since it's open source why don't YOU implement the cool ideas you've suggested, submit 'em back to the community, and WE can all be four times more productive? Ciao, Paul From gleki at gol.ge Mon Mar 4 16:59:21 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Mon, 04 Mar 2002 13:59:21 -0800 Subject: more functional programming Message-ID: <3C83EE39.B3665205@gol.ge> Hi all! Please, accept my appologies for this naive question. I have taken a careful look on the operator module docs. The module enables one to make procedures as lists. That's too good. However, is there already something like scheme's "define" abstractor? This'd be used as the first element of such list, yielding the result of the procedure... Is this, or anything similar, already present in Python? If not, does someone of the Python gurus plan to do so? Thank you very much for your time. Greetings, Giorgi PS. Is a genetic programming library written in/for Python available? From thomas at gatsoft.no Thu Mar 14 02:46:12 2002 From: thomas at gatsoft.no (Thomas Weholt) Date: Thu, 14 Mar 2002 07:46:12 GMT Subject: Telnet-like interface with authentication in server Message-ID: <8zYj8.63$5Kn.179044352@news.telia.no> Got a webserver based on BaseHTTPServer using threads and I want a simple text-based interface to, like telnet. Would it be possible to have a normal telnet-client connect to my server somehow, get a prompt for username and password and be able to run simple commands and see some output ? This would be very handy for debugging etc. Thomas From tim.one at comcast.net Thu Mar 14 17:31:45 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 14 Mar 2002 17:31:45 -0500 Subject: GC thread safe? In-Reply-To: Message-ID: [Dieter Maurer] > Several Zope users face crashing Python 2.1.2 (SIGSEGV inside > the garbage collector). The problem only occurs when > the following conditions are true: > > * Zope runs in multi-threaded mode > * the cyclic garbage collector is not deactivated > > Is the cyclic garbage collector known to be thread safe? [Martin v. Loewis] > The garbage collector runs while having the GIL, so it does not need > to be thread-safe. There's still a vulnerability here: gc *assumes* the GIL is held when _PyObject_GC_Malloc gets called, and doesn't verify that the GIL is in fact held. A rogue extension module could violate this precondition without triggering a predictable error (and then "random" segfaults would be likely). From tdickenson at devmail.geminidataloggers.co.uk Tue Mar 5 08:27:55 2002 From: tdickenson at devmail.geminidataloggers.co.uk (Toby Dickenson) Date: Tue, 05 Mar 2002 13:27:55 +0000 Subject: OT - file permission checks on Windows References: Message-ID: Skip Montanaro wrote: >Given this simple file access permission code: I would be mildly suprised to see code like that outside a unix kernel, and the equivalent for NT's more sophisticated security model would be very much longer. >how would I do this under Windows? The usual way in Windows is the same as the usual way on Unix: try to open the file, and see if works or if you get an error code meaning "permission denied". If you want to check accessibility for another user then the equivalent of setuid are ImpersonateLoggedOnUsed and RevertToSelf Toby Dickenson tdickenson at geminidataloggers.com From djc at object-craft.com.au Tue Mar 26 05:16:55 2002 From: djc at object-craft.com.au (Dave Cole) Date: 26 Mar 2002 21:16:55 +1100 Subject: [albatross-users] Re: Python embedded like PHP References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> <1017000019.3094.31.camel@localhost> Message-ID: >>>>> "Ian" == Ian Bicking writes: Ian> Well, you might be able to help the situation some if you create Ian> a new scope for the macro, and have something like dtml-let -- Ian> that way you could do stuff like. That way variable assignments Ian> inside your macro will pass out of scope when the macro finishes, Ian> and at least not overwrite things in the main scope. That seems reasonable. A simple way to do that would be use a special tag to enclose the fragment of template which you wanted to be in a local scope. Ian> You can use some form of let to manipulate the namespace when it Ian> doesn't match what the macro expects. This is what DTML does, Ian> and I assume ZPT uses the same mechanisms (it only seems to be a Ian> change of syntax). Ian> I don't like this at all, though, as there's all sorts of Ian> problems that pop up when you start abstracting things more Ian> deeply. Also, I think macros are very important, and keeping Ian> them python-like is a very nice. Then you can define, inside a Ian> single template, not only the full page style, but the style of Ian> components of the page. For instance, I create pages that create Ian> headers with lists underneath them, all entirely dynamic. If the Ian> template can define what a header and what a list should look Ian> like, then I have much more power over the look of the page. Ian> I'd pass arguments like: Ian> Ian> This seems pretty straight-forward, and also maps directly to Ian> keyword arguments. You could add the syntax: Ian> Albatross macros are a little bit more interesting and useful. In one of the samples (the sybase browser) there is a macro for drawing a box around enclosed content. The HTML for doing a box is a bit nasty and non-obvious. This is the macro:
    The interesting thing to note is the tag. This is where content passed to the macro will be placed. To enclose anything in a box all you need to do is this: Draw a box around me! This is what happens when you combine the two things: >>> from albatross import SimpleContext, Template >>> ctx = SimpleContext('.') >>> t = ctx.load_template('macros.html') >>> t.to_html(ctx) >>> t = Template(ctx, '', ''' ... Draw a box around me! ... ... ''') >>> t.to_html(ctx) >>> ctx.flush_content()
    Draw a box around me!
    You can nest macros if you like: >>> t = Template(ctx, '', ''' ... ... Draw two boxes ... ... ... ''') >>> t.to_html(ctx) >>> ctx.flush_content()
    Draw two boxes
    There are lots of interesting things you can do with the macros. The above example used a single argument macro. You can pass multiple arguments simply by naming them. The Albatross manual goes into quite a bit more detail. Ian> It should also be fairly easy to create Python functions that do Ian> the same thing as the macro. It is quite easy. That would defeat the effort to separate the presentation and implementation though. Ian> Some people will still want to pass in entire namespaces... you Ian> could use inclusion instead of macros in that case, or make Ian> another form of macros. You could also make another form of Ian> setting variables, that sets them globally (perhaps as constants) Ian> -- this is much cleaner than making every passing variable and Ian> loop global. I agree - there are lots of things that could be done. Coming up with some "simple" things which can be used for multiple purposes is the challenge. It is only by having our assumptions challenged that we will be able to improve what we currently have. Your constructive criticism is making me revisit some of the early decisions and look at them in a new light. - Dave -- http://www.object-craft.com.au From aahz at pythoncraft.com Wed Mar 27 12:36:47 2002 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2002 12:36:47 -0500 Subject: instrumenting Python code References: <1010a26.0203262213.4a0d4b11@posting.google.com> <3CA16839.1A21E36A@engcorp.com> Message-ID: In article , Skip Montanaro wrote: > >Or, in 2.2, the new hotshot module, which is a lot more efficient at >profiling than the profile module. Where is hotshot? I don't see it anywhere. It's not even on the Vaults of Parnassus. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From emile at fenx.com Thu Mar 14 11:40:10 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 14 Mar 2002 08:40:10 -0800 Subject: Good book on Python? References: Message-ID: phil hunt > >I recently bought "Programming Python" by O'Really, > > Oh. Really? > LOL... good ketch... ;-) -- Emile van Sebille emile at fenx.com --------- From selectfincon at yahoo.com Thu Mar 14 21:51:00 2002 From: selectfincon at yahoo.com (Jim) Date: 14 Mar 2002 18:51:00 -0800 Subject: python shell Message-ID: When I try to exit the python shell under windows XP it hangs. Is there some trick to this? From robin at jessikat.fsnet.co.uk Fri Mar 1 18:58:21 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 23:58:21 +0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7FF015.D1A00D13@ccvcorp.com> Message-ID: In article <3C7FF015.D1A00D13 at ccvcorp.com>, Jeff Shannon writes ..... >Note that you've got an extra backslash in your version -- you want a >single escaped double quote after 'bongo.exe', not an escaped backslash >followed by an unescaped double quote. Raw strings will save you much >pain. > ..... interestingly I don't seem to need the \ quotes in win2k. What system is it that needs those? I know that in unices it's possible to create files with very odd names including things with spaces in. Therefore the included space can happen and there I would expect to be able to use either " " or ' ' and provided that system/popen uses a shell I would expect to get away with quite strange paths. -- Robin Becker From wayne at mishre.com Thu Mar 7 01:43:38 2002 From: wayne at mishre.com (Wayne Pierce) Date: Wed, 06 Mar 2002 22:43:38 -0800 Subject: [Newbie] Code for web-based "members" database? References: Message-ID: <3C870C1A.6000802@mishre.com> Damon Lynch wrote: > Hi everyone, > > Does anybody have any suggestions for finding code that will help > solve the following problem: > > I have a members database whose main purpose is to allow members to > view other members based on interest areas (and geographical location, > projects etc. etc.). The database should reflect that areas of > interest are related to one another in non hierarchal ways. For > instance, supposing an area of interest is biodiversity conservation, > and another area is urban air pollution, and another is organic > agriculture. Anyone doing a members' search on environment should > find people with those areas of interest. But someone doing a search > on agriculture should find organic agriculture, and not urban air > pollution. > > It would be nice if people could suggest new areas of interest for > validation. Not sure what you mean by this, any examples? > The database is currently stored in a flat file (yuck!). It could be > stored in a relational database, assuming that is the best way of > storing it. Or any other manner I suppose! I've done similar things with skills for tech projects in the past, I dind't want to deal with SQL schemas so I typically use Metakit. In the situations I have needed there was only a few people writing to the database. Depending on the amount of data, you may want to consider SQL or ZODB. I don't like making SQL schemas so I tend to avoid it. > Unsurprisingly, access to this database is over the web. A relatively > minor point is that I use e-mail addresses from to send out regular > e-mail updates. > > Is there already-existing python code that handles this type of > problem? The stuff I wrote was for my last company, so I don't have the code any more...it should be straight forward to implement though. Create a list for the groups, with each entry in the list being the sub groups. This way if you search for a group it will know what sub-groups to match as well, but you can still search for the individual item without dealing with the groups. HTH, -- Wayne Pierce web: http://www.mishre.com email: wayne at mishre.com "What you need to know." From aahz at pythoncraft.com Sun Mar 31 12:22:31 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 12:22:31 -0500 Subject: newbie question on lists, getting an error on basic addition References: Message-ID: In article , John Warney wrote: > >>>> alist = [1, 2, 3, 4] >>>> counter = 0 >>>> answer = 0 >>>> alist >[1, 2, 3, 4] >>>> counter >0 >>>> answer >0 >>>> while counter < 6: >... answer = answer + alist[counter] >... counter = counter + 1 >... >Traceback (most recent call last): > File "", line 2, in ? >IndexError: list index out of range >>>> answer >10 Add a print counter at the top of your loop and you'll see why. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From dix at none.com Sun Mar 3 06:38:36 2002 From: dix at none.com (dix) Date: Sun, 03 Mar 2002 11:38:36 GMT Subject: Twain Scanners and some other questions Message-ID: <0Xng8.33257$Ns4.1344751@news2.tin.it> Hi to all, I am going to develop a client server application in Python. It will be a Document Management software (Windows environment). I choosed Python as language, wxPython for GUIs building and MySQL for data storing. Since I need this app deals with both binary documents (Word files, Excel files, etc.) and with paper based documents, I need to know if there is a free library for Python to manage Twain scanners in order to pilot the scanner and have an image representation of the paper document. I would like also your advice to find a solution to convert these images in Acrobat PDF format: for the moment I just tought at the possibility to automate the COM interface of Acrobat Distiller from Python. Any other idea? Thank you very very much in advance for your kind help! dix From cbbrowne at acm.org Tue Mar 12 00:52:42 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 12 Mar 2002 00:52:42 -0500 Subject: Is Python an object based programming langauge? References: Message-ID: Tim Hammerquist wrote: > Graz Bukanoff graced us by uttering: > > Is Python an object based programming langauge? > > According to Smalltalk enthusiasts, definitely not. > > According to some Pythonistas, yes. > > IMNERHO, Python is object _oriented_, but not object _based_. I don't > fault Python for this; it was a design decision, and probably a good > one. > > If the question were "Can Python model my OOP idea?", the answer is an > emphatic yes. That depends somewhat on your OOP idea. If the OOP idea is to use classes to define a hierarchy of methods, then sure. If your "OOP idea" is to have generic functions ala CLOS, or to do FLAVORS-style mixins, then possibly not. -- (reverse (concatenate 'string "gro.gultn@" "enworbbc")) http://www3.sympatico.ca/cbbrowne/wp.html From grante at visi.com Sat Mar 9 01:22:13 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 09 Mar 2002 06:22:13 GMT Subject: wxPython seg faults under RH7.2 References: Message-ID: In article , Grant Edwards wrote: > I can not get wxPython to work on a RH7.2 system. > > I have gtk 1.2.10 and wxGTK 2.3.2.1 installed. Gtk came with > RH7.2 and wxGTK was installed from binary RPMs downloaded from > wxwindows.org. > > I built and installed wxPython 2.3.2.1 from sources using > Python 2.1.1. The build/install seemed to work fine, but > even the most trivial wxPython apps just seg fault. Switching from gcc 2.95.4 to 2.96 fixed the problem. Some other program I was trying to build wouldn't work with 2.96, so I had downgraded to 2.95.4. Somebody owes us all an apology for the 2.96 mess... -- Grant Edwards grante Yow! .. Now KEN and BARBIE at are PERMANENTLY ADDICTED to visi.com MIND-ALTERING DRUGS... From jjb5 at cornell.edu Wed Mar 20 12:30:28 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Wed, 20 Mar 2002 12:30:28 -0500 Subject: Python2.2 Installation Message-ID: I downloaded and almost installed Python 2.2 from the Python-2.2.tgz release on SF by doing the 'usual "gunzip; tar; configure; make" dance'. I now have a Python-2.2 directory which seems to work by itself. Now I'm trying to add the pyserial-1.12 extensions by using distutils and getting the following error: distutils.errors.DistutilsPlatformError: invalid Python installation: unable to open /usr/local/lib/python2.2/config/Makefile (No such file or directory) So how do I complete the installation so that Python2.2 is at least in /usr/bin? How do I replace the 1.5.2 installation that came preinstalled (which is in /bin)? Joel From greg at cosc.canterbury.ac.nz Sun Mar 3 19:07:27 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 04 Mar 2002 13:07:27 +1300 Subject: Status of PEP's? References: Message-ID: <3C82BABF.B632A4FB@cosc.canterbury.ac.nz> David Eppstein wrote: > > In article , > "Bjorn Pettersen" wrote: > > > Of course, if anyone actually cared about this syntax, we would have a > > PEP with a pro/con section, so we wouldn't have to reiterate the same > > arguments over and over again > > I was starting to think it might be time to write a PEP, > but then Tim's comment about how he dislikes iterating over 3 > discouraged me. Bjorn is talking about "for x < i < y", though, which is a different proposal from the one about iterating over 3. I think they deserve to be judged separately. I'm too busy to write a PEP on this myself right now, as I'm working on another Python-related project. I may do it if nobody else has done it by the time I get through that. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From gleki at gol.ge Sun Mar 24 18:25:12 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Sun, 24 Mar 2002 15:25:12 -0800 Subject: advanced Python Message-ID: <3C9E6058.8D3EFE6F@gol.ge> Hello! I wonder if someone prompts me a book dedicated to the advanced topics of python? Something tailored a-la "Advanced C++" by James O. Coplien... Thanx in advance! Best regards, Giorgi From usenet at thinkspot.net Sun Mar 17 18:53:57 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 15:53:57 -0800 Subject: Eliminate Spam Now... >g< Python w/DNS/&POP3 References: Message-ID: On Sun, 17 Mar 2002 21:56:15 GMT, Benjamin Schollnick wrote in comp.lang.python in article : > Folks, > > I'm running into a slight problem... > > I'm attempting to use the (py)DNSlib (sourceforge project), to look > up Spammers via ORBZ (or similiar group)... > > And I'm able to pull up the DNS information, but every entry I try > response with a valid root level DNS entry.... Can anyone enlighten me > regarding the operations of the black hole lists? I can't seem to find > any of the sights that explain the actual functionality. > > (I've tried reversing the octets [i.e. 13.175.214.14 == > 14.214.175.13], with no luck) > > = Benjamin This will do it for you. Note that I'm using the Spamcop black hole list, but you can use any one you want: import socket def IP_in_bl(host, IPaddy): IPquads = IPaddy.split('.') IPquads.reverse() reverseIP = '.'.join(IPquads) IPlookup = "%s.%s" % (reverseIP, host) try: resolvesIP = socket.gethostbyname(IPlookup) if resolvesIP.startswith('127.'): return 1 except socket.gaierror: return 0 ############################### # # begin main test program # ############################### IPaddy = '211.192.182.125' host = 'bl.spamcop.net' if IP_in_bl(host, IPaddy): print "OPEN RELAY!!!" else: print "not a known Open Relay." -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From andreas at mtg.co.at Fri Mar 1 03:33:19 2002 From: andreas at mtg.co.at (Andreas Kostyrka) Date: Fri, 1 Mar 2002 09:33:19 +0100 Subject: xor on strings In-Reply-To: <%hI98.3302$pC1.668524@newssrv26.news.prodigy.com> References: <3c674cbd_2@corp.newsgroups.com> <%hI98.3302$pC1.668524@newssrv26.news.prodigy.com> Message-ID: <20020301093319.4b73f174.andreas@mtg.co.at> On Mon, 11 Feb 2002 05:04:59 GMT "dsavitsk" wrote: > the truncate part is the problem. I am building VB Hex strings to send to a > VB server. so > > >>> red = hex(56)[2:4] What about: red=56 green=156 blue=12 thestring="%02x%02x%02x" % (red,green,blue) > >>> green = hex(156)[2:4] > >>> blue = hex(12)[2:4] > >>> thestring = '&H' + blue + green + red > > but here, since the blue string is only 1 character it throws the rest off. Andreas From bh at intevation.de Mon Mar 11 13:18:32 2002 From: bh at intevation.de (Bernhard Herzog) Date: 11 Mar 2002 19:18:32 +0100 Subject: Integers class...? References: <3C882BF0.B7B6A239@cosc.canterbury.ac.nz> <6qd6yf461k.fsf@abnoba.intevation.de> <3C8C2ACF.D7B2FEA@cosc.canterbury.ac.nz> Message-ID: <6qk7sjhssn.fsf@abnoba.intevation.de> Greg Ewing writes: > Bernhard Herzog wrote: > > > > Slices support a step parameter, so > > > > for x in int[9:-1:-1]: > > I don't consider that a good solution, for > two reasons: > > (1) I'm not sure what the semantics are of > slices with negative steps. There are at > least 4 equally plausible interpretations of > [a:b:-c] if you count all the possible > combinations of endpoint swapping and > open/closed swapping. I'm not sure about this, too. However, if it meant anything else than in range it would be very confusing. > (2) Even if the semantics are well-defined, > it's too mind-bending remembering and applying > them correctly in any given situation. It's > no better than range(a,b,-c) in that respect. Right. And for the most simple case where you only have the stop value it seems more inconvenient than range because you have to supply the start value or assume that int considered as a sequence implicitly starts at 0 (which would be the only reasonable thing to do, perhaps, otherwise int[:10] would start with -sys.maxint - 1). The only advantage I can see in subscripting int over range is that it could be defined to return an interator. It might be better to introduce special code in the interpreter for the case where the sequence argument of for is just a range call and range is actually the builtin function. This would only take care of the optimization possibilities, of course. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From ralph at inputplus.demon.co.uk Sat Mar 30 06:39:51 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 30 Mar 2002 11:39:51 GMT Subject: PEP 285: Adding a bool type References: Message-ID: Hi Tim, > [Guido] > > > 5) Should operator.truth(x) return an int or a bool. Tim Peters > > > believes it should return an int because it's been documented as > > > such. > > [Ralph Corderoy] > > Unlike Tim to produce such a poor reason. Has he been paraphrased > > a little too much? > > Not in Guido's eyes . We don't need 3 equivalent ways to turn > an arbitrary expression into a bool ("bool(x)" same-as "not not (x)" > same-as "truth(x)"). *Especially* if str(bool) and repr(bool) > produce 'True' and 'False', people have a legitimate need to make an > arbitrary true/false expression produce 0 and 1 too, if only to > preserve 0/1-based true/false output. operator.truth() has always > been the best way to do exactly that. Alternatives like "(boolexpr) > + 0" and "(boolexpr) and 1 or 0" and "(0, 1)[boolexpr]" reek in > comparison. Aha! Well, now I've got your side of the argument, and you've co-incidentally snipped Guido's point of view, I'm firmly in favour of yours ;-) I've happily used `!!x' in C and found `not not x' in Python wordy so I'm much in favour of operator.truth returning 0 or 1. Cheers, Ralph. From martin at v.loewis.de Sun Mar 31 05:47:11 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 31 Mar 2002 12:47:11 +0200 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> <3CA5F90F.BF37B528@engcorp.com> <3CA6B051.6D55B4D5@engcorp.com> Message-ID: Peter Hansen writes: > But your point in the message I was replying to was that there > are 300 functions which have code that says "return 0" or "return 1" > or "return None" and the change will help users of those functions. > Didn't that imply those users are not looking at the documentation, > but are trying to read the source to figure out how the code works? No. It implied that users read the source of the code; whether or not they look at the documentation was not implied. > If the documentation must be changed, why not just make it clear in > the documentation what it means when a method returns 1 or 0 or > None? The documentation already says that. However "If the section in fact existed, return 1. Otherwise return 0." leads to the question "why aren't you returning a boolean value?", to which the answer is "because they are not supported in the language". > True, False = 1, 0 > > Or, now that I think of it, will that continue to work as these > will just be built-ins now hidden by my local definitions? Indeed, yes. > If so, my bad for mentioning code breakage. There still might be code breakage, but it will be much less frequent than you feared. Regards, Martin From peter at engcorp.com Wed Mar 27 07:19:10 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 27 Mar 2002 07:19:10 -0500 Subject: list comprehension question References: Message-ID: <3CA1B8BE.3DB000B7@engcorp.com> Laura Creighton wrote: > > > >Peter Hansen: > > > > If it's a bot, you don't have to apologize. Bots feel no emotion. > > > > And you're safe, too -- remember the First Law. > > > > > > Tisk tisk. Only half of the apologising you do for the other person. > > > The other half you do for yourself. > > > > Not sure I understand the sentiment, but perhaps it would have > > helped you if I included an explicit smiley? That _was_ a joke. > > Happily, I think from Tim's reply he understood and took it that way. > > (The reference to Asimov might be obscure to some. Sorry.) > > > > Thanks for the gentle advice though. :) > > > > -Peter > > Ick, i thought that _was_ from Asimov, but now that I looked that up, > it isn't there. So the new question is -- where did I read that? And > clearly a long time ago ... I haven't been to the tree I remember reading > the book in for at least 25 years .... >From "I, Robot" and others, the Three Laws of Robotics. (I just happen to have been rereading this on the weekend, so I guess the thought stuck.) First Law was "A robot may not injure a human being or, through inaction, allow a human to come to harm". Second: "A robot must obey the orders given it by human beings except where such orders would conflict with the First Law". Third: "A robot must protect its own existence as long as such protection does not conflict with the First or Second Law". * * * I'm told your posting was "definitely a form of humor" although there's uncertainty whether it was sarcasm, irony, or something else (uncertainty mostly on my part :-). Not sure we're on the same wavelength, but as long as no one meant to offend anyone else, I guess we'll survive even if I still don't understand what just happened. :-) -Peter From scarblac at pino.selwerd.nl Sun Mar 10 07:04:35 2002 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 10 Mar 2002 12:04:35 GMT Subject: import gadfly causes 500 Server Error -- anyone know how to fix? References: <3C8AFB43.275714BB@erols.com> Message-ID: Jerry Gitomer wrote in comp.lang.python: > Hi, > > I have an application I am porting from Python with Tkinter to > Python on the Web. > I built my first set of scripts by copying something that worked > and then modifying > one idea at a time. Everything was fine until I tried to add a > query into a gadfly database. > > I discovered that adding the "import gadfly" statement results > in: > > 500 Server Error > > The server encountered an internal error and could not complete > your request. > > > Anyone have any ideas on why and how to fix? Is gadfly installed on the server? If not, the import is obviously going to fail... -- Remco Gerlich From ark at research.att.com Sat Mar 30 11:04:13 2002 From: ark at research.att.com (Andrew Koenig) Date: 30 Mar 2002 11:04:13 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type In-Reply-To: <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: Guido> Another argument for deriving bool from int: implementation Guido> inheritance. A bool must behave just like an int, and this is Guido> most easily accomplished this way: the bool type doesn't have Guido> implementations for most operations: it inherits them from the Guido> int type, which find a bool acceptable where an int is Guido> required. Liskov substitutibility would seem to suggest deriving int from bool, not the other way around. That is: If I have a program that uses bool values, I can change it so that it uses int values without affecting the behavior of the program. The reverse is not true. I wonder if this is the circle-ellipse problem over again? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From news at charneyday.com Tue Mar 5 00:37:37 2002 From: news at charneyday.com (Reginald B. Charney) Date: Tue, 05 Mar 2002 05:37:37 GMT Subject: Order of constructor/destructor invocation Message-ID: In Python, are destructors defined to be invoked in reverse order of constructors? The following program illustrates the problem: class HTML: def __init__(self): print "" def __del__(self): print "" class BODY: def __init__(self): print "" def __del__(self): print "" class PHP: def __init__(self): print "" if __name__ == "__main__": print "Start of program" h = HTML() b = BODY() p = PHP() print "Body should appear before all destructors" The output I get using Python 2.2 is: C:\WINDOWS>python "c:\my documents\t1.py" Start of program C:\WINDOWS> The last two tags are out of order. They should have been and then . I also ran this program with the names of the classes changed to T1, T2, and T3 and the order of destructor invocation was correct: T3, T2, T1. Thus, it seems to be a "order of name" issue. This problem also occurs under Python 2.2 under Linux (SuSE 7.3). Under Python 1.5.2, the destructors are never invoked. Basically, I need to know if the order of destruction is guaranteed to be the reverse of construction when reference counts on the objects are the same (e.g., 1 on this case). Without this guarantee, I don't understand how Python can effectively use destructors - it falls into the same hole as Java. For me, this is a show-stopper. Reg. From daniel.dittmar at sap.com Tue Mar 12 07:59:41 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 12 Mar 2002 13:59:41 +0100 Subject: Has Mark Hammond attained pariah status yet? References: Message-ID: > all the evidence suggests that python.net (or whatever it will be > called) will not be python as we know it. Apparently .net will not > support multiple inheritance etc etc. There was an interesting recent I don't see how the limitations of .NET (or rather the CLI part of it) differ from those of the Java VM. So it might not be Python as we know it, but it might be useful in certain applications. And of course it might also be useful to port CPython to the .NET C compiler and adding a .NET <-> Python layer. > Another > example of embrace and strangle. .NET is more another failed example of UNCOL Daniel From shalehperry at attbi.com Sat Mar 23 15:09:07 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 23 Mar 2002 12:09:07 -0800 (PST) Subject: Extending the interactive mode [not really an ANN :) ] In-Reply-To: Message-ID: On 23-Mar-2002 Tjabo Kloppenburg wrote: > hi, > > I use python22 and dreamt about a comfortable way of using the interactive > mode to find information about what methods/functions a class/module provides > and what the helpful __doc__ string says (keeping ri [ruby] in my mind). > > The annoying way to do this in python interactive mode -- with lots of key > strokes and many risks of mistypnig -- is to type: > print mod.__doc__ +Enter > print dir(mod) +Enter > > So I finally wrote a very small function to be loaded from PYTHONSTARTUP when > using interactive mode. It is self explanatory and gives you information > about a module by typing "info(mod)". Fairly easy... > from pydoc import help help() give that a shot. From loewis at informatik.hu-berlin.de Fri Mar 1 08:50:12 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 01 Mar 2002 14:50:12 +0100 Subject: fileinput not Unicode compatible? / UTF16 codec problems References: <9ac02e81.0203010507.377dba0d@posting.google.com> Message-ID: jhorneman at pobox.com (Jurie Horneman) writes: > Is it possible that the fileinput module is not Unicode compatible? That is certainly possible. You'd need to tell it the encoding for opening files; that is currently not supported. > Because I have a little endian 16-bit Unicode file and have trouble > reading it in. Decoding it with the UTF16 LE decoder gives me a > 'truncated data' error. I assume you first split the input into lines, then try the decoding? That does not work with UTF-16; you first need to decode, then split into lines. > Oddly, this problem doesn't occur for every line. No, but for every second line. The UTF-16 decoder will complain if you don't give it an even number of bytes. After the first line is read, the second will (incorrectly) start with a NUL byte, which fills this line to an even number of bytes, again. Decoding as UTF-16 will succeed, but will give you garbage: the wrong bytes will get grouped to form a character. > Is there a solution for this, apart from rewriting a number of modules > myself? As long as it is fileinput only, I recommend to rewrite your code to not use that module; this is probably simpler than rewriting the module to support encodings in full generality. Of course, patches will be welcome; if you do change fileinput, please submit a patch to sf.net/projects/python. > Is there any documentation on which Python modules are Unicode-aware > or not? Not that I'm aware of. In most cases, if issues become known, they problems will be corrected instead of being documented. > Oh, and how does one handle big endian / little endian Unicode when > the UTF16 decoders look for BOMs at the start of each string, but I > only have on at the start of the file? There seems to be no way for me > to tell it which endianness I have, apart from circumventing the codec > and calling the right version myself. You cannot decode UTF-16 on a line-by-line basis. Instead, you need to use a stream reader, which will remember the right encoding across .read or .readline invocations (only since Python 2.2, AFAIR). The most convenient way to open a Unicode stream is to use codecs.open, passing the encoding. In case of UTF-16, the endianness will be determined on first .read* invocation. HTH, Martin From robin at jessikat.fsnet.co.uk Wed Mar 20 10:22:35 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 20 Mar 2002 15:22:35 +0000 Subject: __file__ for relative imports Message-ID: <2OVMEJA7kKm8EweI@jessikat.demon.co.uk> Is there an obvious reason why modules imported from the current directory don't have an absolute pathname for __file__? I can see there might be a need to identify such relative modules in some way, but it would be good to always be able to identify the modules. -- Robin Becker From gh_pythonlist at gmx.de Sun Mar 17 20:05:25 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 18 Mar 2002 02:05:25 +0100 Subject: Python/JXTA In-Reply-To: References: Message-ID: <20020318010525.GA56981@lilith.hqd-internal> * moxie [2002-03-17 16:54 -0800]: > It may be a good idea to create Python bindings for > JXTA (P2P [peer-2-peer] networking solution from Sun)... > > http://www.jxta.org/project/www/background.html Sure. Go on. Or just use Jython (IIRC the reference implementation was in Java). Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 7.9 ?C Wind: 2.2 m/s From gimbo at ftech.net Wed Mar 20 11:33:40 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 20 Mar 2002 16:33:40 +0000 Subject: Message bug? In-Reply-To: <99dh9us1b4d8r9u7p5ltt41g34vlun4kjj@4ax.com> References: <99dh9us1b4d8r9u7p5ltt41g34vlun4kjj@4ax.com> Message-ID: <20020320163340.GF18847@andy.tynant.ftech.net> On Wed, Mar 20, 2002 at 04:15:38PM +0000, Dale Strickland-Clark wrote: > Would I be right in thinking that this message quite what the > developer intended? > > AttributeError: 'module' object has no attribute 'work' > > I have no module called 'module'. > > Python 2.2 on Win2K. I don't think you would be right, ie that message is probably perfectly correct, you're just misinterpreting it. The error message doesn't imply that you have a module called 'module'. It implies that you're trying to access the 'work' attribute of some object which _is a module_, but whose name is not, alas, reported here. Here's a demonstration using python2.3. I import some module, then try to access a non-existent attribute called "foo", and get the same error as you. Python 2.3a0 (#1, Mar 19 2002, 14:46:42) [GCC 2.95.4 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import struct >>> struct.foo Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'foo' Interestingly, the error message in 2.1 is somewhat more helpful in that it tells us which module we're trying to acces: Python 2.1.2 (#1, Mar 14 2002, 10:30:29) [GCC 2.95.4 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import struct >>> struct.foo Traceback (most recent call last): File "", line 1, in ? AttributeError: 'struct' module has no attribute 'foo' Does anyone know why this changed? Even so, if you have a traceback from a running program that'll probably tell you the module name. By the way, it's almost always a good idea to post actual code (and/or a full traceback, if talking about exceptions). That way we might actually be able to tell you _exactly_ what's wrong. :-) Hope this helps, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From tdelaney at avaya.com Tue Mar 12 17:56:51 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 13 Mar 2002 09:56:51 +1100 Subject: NormalDate 1.2 released Message-ID: > From: Duncan Booth [mailto:duncan at NOSPAMrcp.co.uk] > > sjmachin at lexicon.net (John Machin) wrote in > > > There's even a story that the date of > > introduction in Sweden varied by parish! > > Dont forget that Sweden even had a 30th February one year! All calendars are ridiculous. It should be very simple ... 13 x 28 day (4 week) months = 364 days. 1 "extra" day (new year?) 1 additional day in leap years. The extra days can be used to absorb leap seconds, etc. You can also define that each month begins on a particular day of the week (say Sunday). The extra days of the year do not actually have a day of the week, and would always be between Saturday and Sunday. IIRC this is the system that the shire hobbits used. Why was this simple system never adopted? Tim Delaney From emile at fenx.com Fri Mar 15 22:01:36 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 15 Mar 2002 19:01:36 -0800 Subject: This may seem a slightly strange problem ... References: Message-ID: "Chris" wrote in message news:jSSm1aIaVlk8Ewdu@[127.0.0.1]... > I want to learn programming - just for fun - and to learn more about > computing - and the problem is I don't know what to write! > Maybe you want to start simple with web pages? > That was to write a program to display all the possible 24-bit colours > in a systematic way. > If that interests you, take a look at trying to duplicate something like: http://www.hypersolutions.org/images/rgbhex.gif as html. You could also use python to generate the html. -- Emile van Sebille emile at fenx.com --------- From tim.hochberg at ieee.org Wed Mar 27 00:33:56 2002 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Wed, 27 Mar 2002 05:33:56 GMT Subject: reduce vs. for loop References: Message-ID: <8Rco8.1017$0b.176940@news1.west.cox.net> Try this out! For n=100, it's only twice as fast, but try it for n=1000, or n=2000 and it really shines.... (I think it even gives the right answer, which is a plus.) -tim def fact4(n): from sys import maxint mult = 1 result = 1L subresult = 1 max_sub_result = maxint / n for mult in range(n+1): subresult *= mult if subresult > max_sub_result: result *= subresult subresult = 1 return result * subresult "Steven Majewski" wrote in message news:mailman.1017181541.7972.python-list at python.org... > > > On Tue, 26 Mar 2002, Sean 'Shaleh' Perry wrote: > > > > > On 26-Mar-2002 m2 at plusseven.com wrote: > > > > > > Just out curiosity, > > > why is fact2 a bit faster than fact1? > > > > > > def fact1(n): > > > return reduce (operator.mul, range(1L,n + 1)) > > > > > > > bigger problem here. fact2 returns a long, fact1 returns an integer. So > > fact1(100) fails. > > > > > reduce(operator.mul, range(1,n+1), 1L ) > > fixes that, but it's even slower. > > -- Steve Majewski > > > From quadzero at users.sourceforge.net Fri Mar 15 14:41:14 2002 From: quadzero at users.sourceforge.net (Richard Harlos) Date: 15 Mar 2002 11:41:14 -0800 Subject: unittest.py: what is TestResult.__repr__ ? Message-ID: <332433e4.0203151141.1e7d92d7@posting.google.com> I'm not a Python programmer (at least, not yet ;) I am, however, trying to port the unittest.py framework to another language. Of all the languages that this testing framework has been ported to, I thought that Python would be the easiest for me to decipher. For the most part, it seems pretty straightforward, except for... I'm presently stuck in the TestResult class. Though I've searched for the meaning of "__repr__" in the Python22 documentation, I cannot find it. Please help me understand this this convention of using leading and/or trailing underscores in Python. Thanks in advance... Richard From johnroth at ameritech.net Fri Mar 15 08:55:59 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 15 Mar 2002 08:55:59 -0500 Subject: Disabling rexec for ActiveScripting in Local Intranet Zone? References: <3C912376.7020902@skippinet.com.au> Message-ID: "Gerson Kurz" wrote in message news:a6saj7$isv$1 at nixe.ISAR.net... > Mark Hammond wrote: > > > I have no idea :) I would expect that if > > IE has set security approriately, then Python > > would not operate under rexec at all - this is > > certainly what happens for WScript and ASP. > > It doesn't. Is there a way to manually > disable rexec? (Like, patching lib/rexec.py). > > > What version of win32all? > > win32all-146.exe for python2.2 Correct my occasionally faulty memory, but wasn't there a bug report on this, and the feature was withdrawn until the sandbox (?) could be fixed properly? John Roth > > From pearu at cens.ioc.ee Sun Mar 24 10:34:46 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Sun, 24 Mar 2002 17:34:46 +0200 Subject: 2.2 open In-Reply-To: References: Message-ID: On Sun, 24 Mar 2002, Robin Becker wrote: > but now I see > > >>> __import__ > > >>> type(__import__) > > >>> open > > >>> type(open) > > > > So open is now a file? That seems a bit odd to me. Correction: open is the type of file. > It seems that some built ins now have the type of the object they > create. Pretty weird logic. Correction: some built ins are the type of the object they create. Notice that in 2.2 types and classes are unified. Regards, Pearu From deltapigz at telocity.com Sun Mar 31 13:09:58 2002 From: deltapigz at telocity.com (Adonis Vargas) Date: Sun, 31 Mar 2002 13:09:58 -0500 Subject: Tkinter + import question Message-ID: <3ca754d4$1_1@nopics.sjc> i am writting a program utilizing Tk as my gui engine, and i have broken down sections of the form into modules and loaded them through a main script. my only question is in every module i am forced to import the Tkinter module, and does this pose consume too much memory? or does python delegates itself? or is there a way to just load Tkinter into one module and have it received by all? i assumed this was done when i declared Tkinter in one module then all other modules would 'inherit' the Tkinter module, but that wasnt the case. any sugguestions is greatly appreciated. Adonis From BgPorter at NOartlogicSPAM.com Thu Mar 14 09:35:28 2002 From: BgPorter at NOartlogicSPAM.com (Brett g Porter) Date: Thu, 14 Mar 2002 14:35:28 GMT Subject: Good book on Python? References: Message-ID: "Federico Caboni" wrote in message news:B8B657B9.B46%msx at crs4.it... > On 14-03-2002 12:26, in article > Pine.GSO.4.43.0203141117120.6137-100000 at muir, "Antonis C Koutalos" > wrote: > > > Hi, > There are a lot of books about Python nowadays (and, yes,that's GOOD). > I found "Python Essential Reference" by New Riders a very useful book > (that is, if you want a brief but deep explanation of the language, > Provided that you had previous programming experience with other > Languages..) but, AFAIK, it's still based on Python 1.5.2. The second edition (updated to Python 2.1) has been available for some time now. I second the recommendation. -- // Brett g Porter * Lead Engineer, Development Practices // BgPorter at artlogic.com * www.artlogic.com // Art & Logic, Inc. * software engineering and design // Desktop * Embedded * Web From cuiod-tec at web.de Sat Mar 9 07:40:18 2002 From: cuiod-tec at web.de (Jens Gelhaar) Date: 9 Mar 2002 04:40:18 -0800 Subject: need something like __init__ in classes __classinit__ References: Message-ID: Kevin Jacobs wrote in message news:... Hi Kevin, when I use the Persistent class from ZODB like import ZODB from Persistence import Persistent # and then your stuff > class ClassInit(type): > def __new__(cls, name, bases, cls_dict): > # Transform __classinit__ into a static method > class_init = cls_dict.get('__classinit__',None) > if class_init: > cls_dict['__classinit__'] = staticmethod(class_init) > > # Call super instead of type.__new__ to allow cooperative metaclasses > return super(ClassInit,cls).__new__(cls, name, bases, cls_dict) > > def __init__(self, name, bases, cls_dict): > # Call __classinit__ if it exists and is callable. > # This cannot be done in __new__ since the class may not be completely > # initialized by its metaclasses. > if callable(getattr(self, '__classinit__',None)): > self.__classinit__(self) > > class ClassInitObject(object): > __metaclass__ = ClassInit > > class Persistent: > pass > > class primary(ClassInitObject,Persistent): > def __classinit__(cls): > print "In __classinit__:",cls > def __init__(self): > print "In __init__:",self > I get the following Traceback (most recent call last): File "D:\PROGRA~1\Python22\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "E:\daten\Python\SELBST\meinpythontest.py", line 24, in ? class primary(ClassInitObject,Persistent): File "E:\daten\Python\SELBST\meinpythontest.py", line 12, in __new__ return super(ClassInit,cls).__new__(cls, name, bases, cls_dict) TypeError: metatype conflict among bases I looks like a conflict between "type" and "extensionclass". Beside, for me it would be natural to have a hook during "compile time" like __classinit__. Serveral years ago I worked with FORTH and there was no difference between compile and runtime. It was easy to do everything what can be done during compile time. I will try to hack a little bit in the source. Thanks Jens From martin at v.loewis.de Fri Mar 1 15:59:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 21:59:45 +0100 Subject: what I would like to see in python to make a better "glue" language (Newbie) References: <899f842.0202261325.6ff3dd54@posting.google.com> <899f842.0202270934.281b65e4@posting.google.com> Message-ID: anthony_barker at hotmail.com (Anthony_Barker) writes: > If there is a package that supports distutils. what is the best way to > get this done? Post to the python-dev mailing list? Getting it into the standard library? Add a patch to the SF patch manager. Make sure you are the author of the code you are contributing, though - we won't normally incorporate anything without the explicit permission of the author. Regards, Martin From fredrik at pythonware.com Tue Mar 19 17:38:32 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Mar 2002 22:38:32 GMT Subject: Dictionary Comprehension References: <3mbe9usoufc2f5ppjmk7lh6ks71pgb45f9@4ax.com> <7xsn6w9pad.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > dict comprehensions should be in Python if list comprehensions > are, even if no one uses them I'm so glad you're not involved in Python's development. > I hope no one would say Python needn't recognize 901472937 > because hardly anyone wants to specify that particular integer > in a program and you can always say 901472936+1 insead. as I said. From gvdbogae at vub.ac.be Fri Mar 1 19:12:14 2002 From: gvdbogae at vub.ac.be (Geert-Jan Van den Bogaerde) Date: 02 Mar 2002 01:12:14 +0100 Subject: Stedents Question In-Reply-To: <3c80126f_1@news.iprimus.com.au> References: <3c80126f_1@news.iprimus.com.au> Message-ID: <1015027935.1342.3.camel@gandalf> On Sat, 2002-03-02 at 00:45, Tony K wrote: > The question below is a tutorial question that stumps me. Any suggestions > would be appreciated. > Tony > > Write a Python function findABBC which takes a single string as parameter > and returns all substrings thereof which match the regexp pattern ab+c. You > are NOT allowed to use the re module. > Haven't used regexps in a while, but I believe that just means: def findABBC(str): return str == "a" + "b" * len(str[1:-1]) + "c" Geert-Jan From vlcusa at vlcank.co.jp Sun Mar 10 21:33:53 2002 From: vlcusa at vlcank.co.jp (vlcusa at vlcank.co.jp) Date: 11 Mar 2002 02:33:53 -0000 Subject: Image questionnaire - VLC Co. Ltd. Message-ID: <20020311023353.8739.qmail@www.canausr.com> Starting March 11, 2002, we have a 'Image questionnaire' posted in our web site. Please visit http://www.vlcank.com/usa/index.html to participate. It takes only 10 minutes to complete the questionnaire. Hurry and become one of 1 respondent who will be randomly selected to win $2,000 in cash! * This questionnaire is for workers of private corporations only. * Please refrain from participating if you or your family members work in the field of mass communications, surveys, or advertising business. * Please discard this message if you do not qualify or have no interest. Thank you for your time and continued cooperation. Hiromi Nomura VLC Inc. Marutomi Daiichi Bldg. 6F, 2-10-16 Higashikanda, Chiyoda-ku, Tokyo, 101-0031 Japan TEL 03-5820-7222 FAX 03-5820-7266 E-Mail vlcusa at vlcank.co.jp From gbreed at cix.compulink.co.uk Thu Mar 14 09:07:56 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Thu, 14 Mar 2002 14:07:56 +0000 (UTC) Subject: Hexadecimal bytes to integers References: <3C908ADF.7040009@vip.fi> Message-ID: pekka niiranen wrote: > How can I convert messages below to list of bytes: > > message = 0x01040000000271 > or > message = 0104000000A271 > to > m = [0,1,0,4,0,0,0,0,0,0,0,0,'A',2,7,1] You're showing nybbles, not bytes. For bytes, [int(message[i:i+2], 16) for i in range(2, len(message),2)] or [int(message[i:i+2], 16) for i in range(0, len(message),2)] From akuchlin at ute.mems-exchange.org Fri Mar 22 15:34:39 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 22 Mar 2002 20:34:39 GMT Subject: FastCGI References: <3C9A8548.5020404@stroeder.com> Message-ID: In article <3C9A8548.5020404 at stroeder.com>, Michael Str?der wrote: > Would you mind providing a separate distribution I can refer to? A simple > link would be sufficient. Just grab the latest Quixote distribution from http://www.mems-exchange.org/software/files/quixote/ and extract fcgi.py; there aren't any dependencies on the rest of Quixote. Feel free to make fcgi.py available from somewhere; I don't think we'll bother to do so. --amk (www.amk.ca) "I never make exceptions. An exception disproves the rule." -- Sherlock Holmes, in "The Sign of the Four" From shalehperry at attbi.com Sat Mar 23 00:16:09 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 22 Mar 2002 21:16:09 -0800 (PST) Subject: circular imports (don't yell!) In-Reply-To: <3C9BFCF1.3CF03E1C@engcorp.com> Message-ID: > > Also, do you realize that "from X import *" is a bad idea > in general? I'll assume that was just something you did > to try to reproduce the problem in a small sample program... > in his defense, the gui libs often expect you have done a from X import *. otherwise your commands are fiendishly long and ugly. win = gui.create_window(gui.top_level, gui.foo, gui.bar) and so on. From tdelaney at avaya.com Wed Mar 13 22:54:40 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 14 Mar 2002 14:54:40 +1100 Subject: Performance problem with filtering Message-ID: > From: Gerhard H?ring [mailto:gh_pythonlist at gmx.de] > > I have two lists of files (approx. 50000 entries). Now I want > to have all the > entries of list b, that are not in list a. However, the primitive: > > results = [] > for entry in b: > if entry not in a: > results.append(entry) > > is terribly slow. I mean *really* slow. Any recommendations > on how to optimize > this? Wouldn't it be nice if I could simply do b.removeall(a)? Firstly, you are doing 'entry in a' for each entry in b. This is a linear search through a ... *very* slow. So, the first thing I would recommend is ... results = [] c = {} for entry in a: c[entry] = None for entry in b: if c.has_key(entry): results.append(entry) This means you are searching for a key in a dictionary ... a very quick operation. A further optimisation is to use the filter() function. results = [] c = {} for entry in a: c[entry] = None results = filter(c.has_key, b) This should give you a couple of orders of magnitude speedup. I would suggest trying both and comparing the performance. Tim Delaney From warrierajit at hotmail.com Sat Mar 9 23:03:59 2002 From: warrierajit at hotmail.com (warrier) Date: 9 Mar 2002 20:03:59 -0800 Subject: Tutorials for Tix extension widgets Message-ID: Are there some good tutorials for using Tix extension widgets from python ? Most of the tutorials I have seen only tell how to do so using Tcl. From gh_pythonlist at gmx.de Mon Mar 11 09:05:40 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Mon, 11 Mar 2002 15:05:40 +0100 Subject: Standalone Win32 wxPython apps? In-Reply-To: References: Message-ID: <20020311140540.GB1573@lilith.hqd-internal> Le 10/03/02 ? 15:08, Gordon McMillan ?crivit: > [...] > Inno is a free GUI installer you can use: > http://www.jrsoftware.org/ > (I recently ran across another free one that claims to be > lighter weight, but I guess I didn't bookmark it :-(). You're probably thinking of NSIS, the "Nullsoft (SuperPiMP|Scriptable) Install System" at http://www.nullsoft.com/free/nsis/ I'm using it because it fits my mind and because its bzip2 compression is sexy :-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 17.3 ?C Wind: 1.2 m/s From phd at phd.pp.ru Wed Mar 13 13:30:47 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 13 Mar 2002 21:30:47 +0300 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: <20020313201539.2995aad0.andreas@mtg.co.at>; from andreas@mtg.co.at on Wed, Mar 13, 2002 at 08:15:39PM +0100 References: <3C86047F.1080601@stroeder.com> <20020313201539.2995aad0.andreas@mtg.co.at> Message-ID: <20020313213047.F31967@phd.pp.ru> On Wed, Mar 13, 2002 at 08:15:39PM +0100, Andreas Kostyrka wrote: > And what about: > db.query("""SELECT foo, bar > FROM %(table)s > WHERE rsrc_id = %(rsrc_id)d > AND name = '%(name)s'""" % locals()) > > pure standard Python :) This will fail if name = "O'Hara". Or name = 'Tutti"""Frutti'. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From bergeston at yahoo.fr Wed Mar 13 09:45:25 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Wed, 13 Mar 2002 15:45:25 +0100 Subject: Parsing system ini files (beginner) References: <9sJj8.32670$hb6.1954714@news20.bellglobal.com> Message-ID: Take a look at: http://www.python.org/doc/lib/module-ConfigParser.html "Jeremie Legault" wrote in message news:9sJj8.32670$hb6.1954714 at news20.bellglobal.com... > I am currently teaching myself how to use Python, I have no programming > experience. In one of the books I am using they have an exercise that asks > you to create a program that parses the contents of an ".ini" system file. I > am not sure what they mean by parse the ".ini" file. If anyone has any ideas > could you email me at jivesojer at hotmail.com. > > Thank You > Jeremie > > From narnett at mccmedia.com Thu Mar 21 23:20:33 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Thu, 21 Mar 2002 20:20:33 -0800 Subject: sgmlParser infinite loop? How to empty and re-user parser object? Message-ID: Anyone know of circumstances under which sgmlParser will hang, presumably in an infinite (well, exceeding my patience, anyway) loop? I don't seem to be able to reliably reproduce this, but occasionally during processing of a large number of pages, I seem to get stuck in it. I'm doing very simple parsing, basically just extracting the contents of tables. I'll re-try the same set of documents and it'll hang in a different spot. If it weren't so unpredictable and infrequent, I'd dig into it with the debugger... Still fairly new to Python... I'm wondering if I should be re-using a parser object for each document I'm processing in a loop -- and wondering if the fact that I'm not is causing these freezes. But if I call it without re-instantiating it, I get the same text parsed again... and I can't see how to tell it to not do that. Calling reset doesn't seem to do the trick, even though I seem to have the appropriate reset method that calls the parent reset. Thanks for tips. Nick -- narnett at mccmedia.com (408) 904-7198 From tdelaney at avaya.com Wed Mar 6 19:44:52 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 7 Mar 2002 11:44:52 +1100 Subject: PEP 284, Integer for-loops Message-ID: > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > When you say "incorrect", do you mean that "making integers > iterable" is > different from "allowing automatic conversion of integers to > iterators"? Yes. > It was my understanding that "for x in y" and "if x in y" > converted y to > an iterator automatically, by calling iter(y) if necessary. Integers > can be made iterable now, by calling range() on them, but that is not > automatic. That's automatic, but not a *conversion*. It is asking the iterable object to *supply* an iterator. Calling range() on an integer does not make the integer iterable ... it creates an (iterable) list using the integer as one of the bounds. > In what way would you propose rewording the PEP? If it's > just "PEP 274 > [4] proposes to make integers iterable, simplifying..." that seems > unobjectionable enough. Or possibly make it more explicit ... "PEP 274 [4] proposes to make integers iterable by implementing __iter__, simplifying ... I would also possibly add the discussion of what iter(-x) should mean i.e. either counting up from -x to 0 (upper bound exclusive, matches slice semantics), or counting down from 0 to -x (upper bound exclusive, useful for traversing sequences in reverse order). Tim Delaney From sjmachin at lexicon.net Thu Mar 21 06:53:51 2002 From: sjmachin at lexicon.net (John Machin) Date: 21 Mar 2002 03:53:51 -0800 Subject: Problem with Python Extensions References: <5c2b81.0203202321.50bf8908@posting.google.com> Message-ID: cmbardon at engmail.uwaterloo.ca (Chris Bardon) wrote in message news:<5c2b81.0203202321.50bf8908 at posting.google.com>... > I'm trying to write a simple Python extension for use in Truespace > 4.3. > The problem is, my extension crashes truespace whenever I > try to import it. I've created the dll using MS Visual C++ 6 and > Python 1.5-I've also included the source for the dll below (like I > said-starting simple). When I try to import this into truspace's > python interface (import CommExt), the script causes an invalid page > exception in MFC42.DLL. I'm linking this against python15.lib, as > obtained from python.org. I presume that Truespace (which I had never heard of until now) is constraining you to use Python 1.5.2. I also presume that you know that you can't mix and match --- if the Truespace/Python side is say 2.0, then it will barf on your 1.5.x (you didn't say what x was; it had better be 2). "I'm linking this against" implies you are not using distutils. You should be; it greatly simplifies making extensions. It is available for Python 1.5.2 as a separate download. > If anyone has had a similar problem, or can see from my source what my > problem might be, your help would be greatly appreciated. > > Thanks, > > Chris Bardon > > > //CommExt.cpp Uh-ohh -- try it as C, not as C++ > //Another stab at making a truespace extension > > #include "Python.h" > > PyObject* comm(PyObject *self, PyObject *args); > It's usual to put the PyMethodDef *after* all the functions; this reduces the need for forward declarations. > static PyMethodDef commMethods[] = > { > {"comm", comm, 1}, This is unlikely to be the cause of your crash, but you should really be using METH_blah_blah instead of magic numbers like 1. > {NULL, NULL} /* Sentinel */ > > }; > > static PyObject *CommExtError; > > extern "C"__declspec(dllexport) void initCommExt() This doesn't even compile with Borland C version 5.5. Try the standard spell from xxmodule.c: DL_EXPORT(void) initCommExt() If that doesn't work, try just void InitCommExt() > { > Py_InitModule("CommExt", commMethods); //this is the line that > crashes TS! > } The comm() function should be declared as static... > PyObject* comm(PyObject *self, PyObject *args) > { > int result=42; > return Py_BuildValue("i", result); > } With the DL_EXPORT line (and no other changes), your code in commext.c (not .cpp) and a suitable setup.py give the following with Python 1.5.2 and the Borland BCC 5.5 compiler: Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import CommExt >>> CommExt.comm() 42 >>> If you manage to get it that far with Python at the command line, then try using it through Truespace. HTH, John From peter at engcorp.com Fri Mar 8 00:48:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 08 Mar 2002 00:48:08 -0500 Subject: [GERMAN] "ziegenproblem" References: <7x3czc87qq.fsf@ruckus.brouhaha.com> <3C882CBC.4553D21C@engcorp.com> Message-ID: <3C885098.F834FE0A@engcorp.com> Gerhard H?ring wrote: > > Peter Hansen wrote in comp.lang.python: > > See also http://c2.com/cgi/wiki?MontyHallProblem for full discussion. > > Most of the explanations are too complicated IMHO. This is how I > finally understood the problem: [snip description and ASCII art] Good job. I can understand your way of looking at it, and I agree most (but not all) of the explanations on that wiki were harder to see. The nature of wikis being what it is, you really should click on Edit and add your version to the page. Eventually somebody will remove the really obscure ones and leave only the useful ones. You could do that now if you wanted... -Peter From DavidA at ActiveState.com Tue Mar 26 12:39:44 2002 From: DavidA at ActiveState.com (David Ascher) Date: Tue, 26 Mar 2002 09:39:44 -0800 Subject: PEP262 - database of installed packages References: Message-ID: <3CA0B260.AAA76F66@activestate.com> Thomas Heller wrote: > # According to David Ascher , utime() should be done > # before chmod() (at least under NT). Wow. Old email addresses etched in stone. And claims of knowledge which I have no memory of ever posessing. Alzheimer's striking so soon... While we're on the topic of PEP262, I want to mention that we're currently revisiting the PyPPM architecture. For those of you who don't know PyPPM is the Python version of PPM, which is the Programmers Package Manager. It was designed for Perl, but there's almost nothing in PPM which is Perl specific. PPM uses an XML file for the 'database of locally installed packages', SOAP for the querying of the remote database, and is based on a standard (OSD). PPM has supported uninstallation, dependencies and versioning for a long time, and is probably worth a look. There are issues with the way the PPM bdist target works which we're looking at replacing soon. PPM3 (for Perl only so far) is a major rewrite of PPM which added a bunch of cool features. For info on that, see: http://aspn.activestate.com/ASPN/PPM. I'll try to poke my head in this discussion periodically and will read up on the PEP, but feel free to ask if you have questions about PPM. --david PS: Thomas -- where's the source to the code that's embedded in bdist_wininst? From fgeiger at datec.at Mon Mar 11 03:22:41 2002 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 11 Mar 2002 09:22:41 +0100 Subject: HTML -> XML: Where's HtmlBuilder()? References: Message-ID: > If you have control over the source HTML files, why don't you just > require that they are XHTML? That would simplify processing > significantly. I am working on that, as there already many HTML files already. But as it's not that bad to mistrust HTML-editors, I'd like to have a kind of built-in bastion which makes *always sure* that it's XHTML. Thanks for your answer Franz "Martin v. Loewis" schrieb im Newsbeitrag news:m3d6ycrzk6.fsf at mira.informatik.hu-berlin.de... > "F. GEIGER" writes: > > > Is HtmlBuilder() deprecated? > > It is not supported in PyXML 0.6 and later anymore, since the entire > DOM implementation has been replaced with 4DOM. > > > Which module was it replaced with? > > Try xml.dom.ext.reader.HtmlLib. > > > What else could I use to convert HTML to XML? > > Depends on what you want the conversion to do. If you want to convert > HTML to XHTML, I think HTMLTidy can do that for you. > > > Do I need additional modules for this? > > Or am I already prepared w/o knowing it? > > If you want to use 4DOM, yes, you should have everything you need. > > > For those who are curious - the big picture: > [...] > > A Shaper applies an XSL file to the HTML pages to make them all look equally > > formatted (this is where I am stuck now). > > If you have control over the source HTML files, why don't you just > require that they are XHTML? That would simplify processing > significantly. > > Regards, > Martin From phd at phd.pp.ru Sun Mar 17 16:55:26 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 18 Mar 2002 00:55:26 +0300 Subject: Where to download bugfix for email Module? In-Reply-To: ; from usenet@thinkspot.net on Sun, Mar 17, 2002 at 09:36:10AM -0800 References: Message-ID: <20020318005526.B30949@phd.pp.ru> On Sun, Mar 17, 2002 at 09:36:10AM -0800, Sheila King wrote: > (1) stability. Can I expect this latest code to be stable? Somehow I would > think that would be questionable with late releases? No, you have to learn development history (CVS is *developer's* tool!) and checkout latest stable release. I heard that Brry is going to release an archive of a stable version... don't know *when*. I suspect the usual time - Real Soon :) > (2) distribution. If I want to distribute code that I'm developing, and I > use the latest CVS releases to develop my code, such that my code relies on > these CVS releases, how do I distribute code to others who are running the > standard 2.2 install? The simplest (though not the best) solution would be to distribute a copy of the email package with your code. You know, Python inserts the path to your application in the beginning of sys.path, so upon "import email" your copy of the package will be imported, and not standard package. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From st-newsgroups at thomas-guettler.de Thu Mar 7 11:42:17 2002 From: st-newsgroups at thomas-guettler.de (Thomas Guettler) Date: Thu, 07 Mar 2002 17:42:17 +0100 Subject: popen3 on win32 python:2.1.2 Message-ID: <3C879869.3090803@thomas-guettler.de> Hi! popen3() hangs on W2K: (stdin, stdout, stderr)=popen3('wvWare -x wvware.xml foo.doc') text=stdout.read() --> read() never ends. It works if wvware produces few output, but with larger files it hangs (0% CPU usage). wvware is a binary from gnuwin32.sourceforge.net I use the python version which comes with zope: 2.1.2 Platform: Windows 2000 SP2 Is this a know problem? Are there workarounds? thomas From grante at visi.com Mon Mar 11 21:48:48 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Mar 2002 02:48:48 GMT Subject: Standalone Win32 wxPython apps? References: Message-ID: In article , Grant Edwards wrote: > I'm considering writing a wxWindows app for Win32. The only > way I'm willing to do this is by doing all of the development > under Unix, and then grit my teeth while I package up the > final product for Win32. Well, I wrote and debugged my little app using wxPython under Linux. wxPython is pretty easy to pick up. I tripped over the geometry management stuff once or twice, but I've been doing Tk stuff for 6-7 years and never have figured out how Tk packs things. The only widget layout scheme I've found that's easier than wxPython was the box/glue setup in Trestle. Moving the app to Win32 was surprisingly easy -- there was one bug in the Win32 wxWindows port I had to work around. Other than that it just plain worked. Then I used py2exe to generate my app as an "exe" file along with about a half-dozen dll and pyd files needed by the exe file. It would have worked right the very first time, except I didn't read any of the docs and generated a "console" mode app instead of a "window" mode app. A one character change to setup.py fixed that. The startup time for my app isn't great, but I was testing under Win2K on a P266 with 70 or 80 MB of RAM. Everything pretty much sucks when run on that machine, and mine doesn't suck that much worse than anything else. Packaged up the files with inno, and Bob's your uncle! wxPython and py2exe are just _too_cool_. Total time required (including writing an emulator for the network-enabled device to whic my app talks) was about 12 hours. The previous version of the app (which nobody can get to work the way they think it's supposed to) was written in C++ and took 5 or 6 weeks to develop. I must admit that it does have a couple feature mine doesn't, although nobody seems to know how/if they work. ;) Now, back to real-time stuff and device drivers for a while... -- Grant Edwards grante Yow! I hope something GOOD at came in the mail today so visi.com I have a REASON to live!! From a.clarke11 at pop.ntlworld.com Sat Mar 9 18:46:49 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Sat, 09 Mar 2002 23:46:49 +0000 Subject: round() function strange behaviour References: <3c8a9261.149508269@news> Message-ID: <3C8A9EE8.4E32CE5B@pop.ntlworld.com> Hi, I think it's a bug intrinsic to the round function: I use a Mac, and I tried differnt arguments for round. Where the decimal ends in nine, in whatever decimal place I tried, the answer is a recurrent decimal, usually nine but sometimes zero. Has it been reported?? Tony You wrote: the round() function will sometimes return a predictable result, as in: round(45.67891, 2) >>> 45.68 but sometimes it will return something like: round(56.78923, 2) >>> 56.789999999999999 2.1 and 2.2 both behave this way on two different (Windows) computers. What's going on here? Bruce Robbins From dominikush at yahoo.com Fri Mar 15 08:34:35 2002 From: dominikush at yahoo.com (dominikush) Date: Fri, 15 Mar 2002 13:34:35 -0000 Subject: Library for wmf/emf to png conversion? Message-ID: Hi, does anybody know of a python library that enables conversion from a (Enhanced) Windows Metafile to png ??? Regards, Dominikus From gerson.kurz at t-online.de Fri Mar 1 06:28:42 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 01 Mar 2002 11:28:42 GMT Subject: Import-Hook and subclassed file objects Message-ID: <3c7f65c2.357716562@news.isar.de> I want to create an import hook that reads data from encrypted files. To redirect the import hook, I do this: ----------- (snip here) ------------- # redirect import hook old_import_func = __import__ def my_import_func(name, globals=None, locals=None, fromlist=None): global old_import_func if name[:10] == "encrypted.": # todo: load encrypted module return imp.load_module(name, file, '', ('.dat','rb',imp.PY_SOURCE)) # use original code return old_import_func( name, globals, locals, fromlist ) __builtins__.__import__ = my_import_func import encrypted.test ----------- (snip here) ------------- (Of course, I'll use lambda for that in the final version ;) Anyway, I have two problems with that. imp.load_module expects a file object. But, Problem #1, the file object cannot be a subclassed "file-type" class. If I define my own file class, I get an error bad/closed file object. Looking at the PythonCore source, I find that the C runtime uses the raw FILE* and not abstract PyFile functions. See function "imp_load_module" in "Python\Import.c": converts Py-File-Object to raw FILE* and then uses that further on. I think I'll have a more deeper look at the python sources and see if I can add PyFileObject-style access. Problem #2, how do I subclass files? I try this: ----------- (snip here) ------------- class my_file_class(file): def read(self,size): # todo: add read implementation ----------- (snip here) ------------- the problem is - where to I subclass a file returned from open()? open() always returns the builtin file class. Attempting to do this ----------- (snip here) ------------- raw_file = open(...) my_file = my_file_class() raw_file.read = my_file.read ----------- (snip here) ------------- I'll get an error that read is a read-only method. From weeks at vitus.scs.agilent.com Sat Mar 16 17:40:35 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Sat, 16 Mar 2002 22:40:35 +0000 (UTC) Subject: HP-UX, PyThread_* missing References: Message-ID: <1016327435.513664@cswreg.cos.agilent.com> Martin v. Loewis (martin at v.loewis.de) wrote: : In any case, the common understanding is that Python does not really : support threads on HP-UX, and probably never will unless some HP-UX : user who understands all the issues provides patches. Still, I've been using threads with HP-UX 10.2 and Python 1.5.2 for months now. (Maybe I haven't stressed it.) Also, "make test" passed cleanly with HP-UX 11 and Python 2.2. It seems to be the combination of HP-UX 10.2 and Python 2.2 that is causing trouble. Greg From krissepu at vip.fi Sat Mar 23 13:54:36 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Sat, 23 Mar 2002 20:54:36 +0200 Subject: Replacing excel: but with what ? Message-ID: <3C9CCF6C.F1099089@vip.fi> Does anybody have a recommendation of what GUI to use in Windows to build an spreadsheet view of a dictionary. Application should support +, - , * and division -operations between cells, columns and rows. The size of the grid would be at maximum 2000 rows x 2000 cells. I am plotting values to 2D -grid and giving string replacements for individual cells. One row consists of values in a file. Column -values are an union of all parameters found from all files. I would like to copy values from a selected cell to all rows. Grid should also support row and column-wise sorts. I can allready create and start an Excel -sheet after parsing the file contents with re-execs. I am using WxPython for the toolbar, but sticking with Excel worries me. Plus I do not have a use for all of its features. WxWindows has a grid, but does anybody have experience of its stability ? I have managed to crash its demo that comes with WxPython... -pekka- From greg at cosc.canterbury.ac.nz Wed Mar 6 22:37:19 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Mar 2002 16:37:19 +1300 Subject: PEP 284, Integer for-loops References: Message-ID: <3C86E06F.670AFB4E@cosc.canterbury.ac.nz> James_Althoff at i2.com wrote: > > Will the syntax not work for > instances of a subclass of int (now possible in Python 2.2), for example? Subclasses should work too, I think. > Or is it the intention that the construct is *not* limited strictly to the > Python builtin classes "int" and "long"? Will it work for any class that > defines __lt__, __lg__, __gt__, __ge__, __add__, and __radd__ methods, for > example? No, I don't think so. It won't be possible to implement it by just starting with the lower bound and repeatedly adding 1 or taking its successor or something. Firstly, the values bound to the index variable are always *integers* (just like range() et al always return sequences of integers). We're *not* intending that, e.g. you should be able to use mxDateTime objects for the bounds and get a range of times one second apart or something! Secondly, if the bounds are floats, the correct place to start is ceil(lowbound), not lowbound itself, or even int(lowbound). So, floats will have to be treated as a special case, and if we're having special cases, it would be better to have *only* special cases -- i.e. restrict it to types that we'res sure we know enough about to do the right thing with. That means ints, longints and floats. In any case, you're right that the PEP needs to nail things down better in this area. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From mal at lemburg.com Wed Mar 6 06:20:05 2002 From: mal at lemburg.com (M.-A. Lemburg) Date: Wed, 06 Mar 2002 12:20:05 +0100 Subject: [DB-SIG] Passing Unicode strings to Database References: <77188782494.20020306181117@tomsk.net> Message-ID: <3C85FB65.546871F5@lemburg.com> Mikhail Astafiev wrote: > > [Env: Win2k, Python 1.5.2] > > Hi people! > > I have a string in Japanese encoded in UTF8. I need to put it into > database in Unicode form. > > import dbi, odbc > o=odbc.odbc(self.ODBC_name+"/"+self.ODBC_sql_username+"/"+self.ODBC_sql_password) > c=o.cursor() > runes = UTF82Runes(string.replace(self.pr_table[row]["description"],"'","''")) > operator="""INSERT INTO %s VALUES('%s','%s');"""%(self.ODBC_table, > int(self.pr_table[row]["pr_no"]), > runes.tostring()) > c.execute(operator) # update database > > I'm getting the following error trace: > > Traceback (innermost last): > File "C:\dev\Products\MRATES~1\server.py", line 34, in ? > PR.sync_all() > File "C:\dev\Products\MRATES~1\PRML\code\prml.py", line 2837, in sync_all > self.__sync_with_sql__(i) > File "C:\dev\Products\MRATES~1\PRML\code\prml.py", line 2797, in __sync_with_sql__ > c.execute(operator) # update database > TypeError: argument 1: expected string without null bytes, string found > > runes is array.array('H') containing Unicode string. > > Database string field has "ntext" type. How can I overcome this > problem? Use mxODBC ? It has Unicode support builtin. Whether your ODBC driver has is a different question, though. -- Marc-Andre Lemburg CEO eGenix.com Software GmbH ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From dalke at dalkescientific.com Thu Mar 7 07:37:26 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 7 Mar 2002 05:37:26 -0700 Subject: Code Bash!!! (CacheDictionary) References: Message-ID: Sean 'Shaleh' Perry: >*) maxlength=1000, I belive this variable is poorly named. A dictionary >is not 10 items long, it contains 10 items. Something like maxitems >or maxcount. >>> d = {"a": "b", "c": "d"} >>> len(d) 2 >>> A dictionary *can* be written as having a length, although "maxlen" would probably be more technically correct. To me, "maxcount" reminds me of the "count" method of string, so I would ask "count of what?" Andrew dalke at dalkescientific.com From richard at stockcontrol.net Wed Mar 13 08:22:25 2002 From: richard at stockcontrol.net (Richard Walkington) Date: 13 Mar 2002 05:22:25 -0800 Subject: python -c cmd bug? References: Message-ID: <2144d9df.0203130522.15ede578@posting.google.com> erik.wilsher at iname.com (erik_w) wrote > When I do > >python -c "import sys;print sys.argv" > ['-c'] > > (Python 2.1.2 on NT4) > > Is this the right behaviour? I would expect that the -c was an option > to the python interpreter, not to my script. Yup, it is correct. To quote the python tutorual: "When known to the interpreter, the script name and additional arguments thereafter are passed to the script in the variable sys.argv, which is a list of strings. Its length is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. Options found after -c command are not consumed by the Python interpreter's option processing but left in sys.argv for the command to handle. " See http://www.python.org/doc/current/tut/node4.html#SECTION004100000000000000000 Regards Richard Walkington From zlu at extremenetworks.com Tue Mar 12 18:47:10 2002 From: zlu at extremenetworks.com (Zihong Lu) Date: 12 Mar 2002 15:47:10 -0800 Subject: is time.sleep a thread safe function? Message-ID: Can someone please tell me the answer? Recently, we have seen some weird behaviors in our python application in Solaris 2.6, 2.7,and 2.8 platform. The application is a web based server, that uses threads heavily. It runs fine in Linux and win32 platforms, but in Solaris, it stopped accepting after ran for couple of hours. One of our guesses is that the time.sleep() used through out our application is not thread safe. Can any one please help us eliminate/confirm this factor? Thanks. -Zihong From neal at metaslash.com Thu Mar 21 17:27:26 2002 From: neal at metaslash.com (Neal Norwitz) Date: Thu, 21 Mar 2002 17:27:26 -0500 Subject: TKinter Question References: Message-ID: <3C9A5E4E.763FA400@metaslash.com> > Paul Sage wrote: > > Hi all. I am new to the list; the impetus for my signing up is a roadblock. J > > I am currently working with a quick and dirty little App for learning Python. I am using Tkinter because the app > really needs a GUI. > > Global variables within the module: > > pointsAvailable = 5 > > currentPointsToSpend = "Current Points left to spend: %s"%pointsAvailable > > Inside the class definition of an object that is the GUI window: > > self.pointsLeftToSpend = Label(root, relief = RIDGE, borderwidth = 1, > > anchor = N, justify=CENTER, > > textvariable = currentPointsToSpend).pack() > > My problem is with textvariable. No matter what I seem to do, it just won??t show up. Is this because it falls out > of scope somehow? No, textvariable needs to be a Tcl/Tk 'textvariable', ie, StringVar. Try this: currentPointsToSpend = StringVar() currentPointsToSpend.set("Current Points ... %s"%pointsAvailable) Neal From kare at speech.kth.se Fri Mar 15 06:05:22 2002 From: kare at speech.kth.se (Kare Sjolander) Date: Fri, 15 Mar 2002 12:05:22 +0100 Subject: Snack mod for python References: Message-ID: <3C91D572.76D851B9@speech.kth.se> Try specifying the device: .play(device='/dev/sound/dsp') Kare Russell Voutour wrote: > Hi i'm using the Snack sound module for python and i've run into a problem and > was wondering if anyone had ever used it before. It installed find but when i use > the .play() method it tries to open my /dev/dsp and it gets a error because the > device does not exists it's under dev/sound/dsp. i've looked in the tkConfig file > and the tclConfig file and can't find anything any sugestions would be helpfull > thanks > > Russ > > -- From bokr at oz.net Fri Mar 15 19:18:47 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Mar 2002 00:18:47 GMT Subject: multiline raw input References: Message-ID: On 15 Mar 2002 15:06:50 -0800, les_ander at yahoo.com (les ander) wrote: >Hi, >i have a program that takes input from the command line >however this input is multi-line and will have a lot of backslashes >I tried using sys.stdin but it ignores the backslashes. >i tried with raw_input but that only takes in the first line > >can some suggest a remedy? > > > > >for example: >i would like to run my program as follows: > >>> myprog.py >Type in some input (type in '.' to end) : >\sum_{i=1}^{n} \frac{\sqrt{2}}{\alpha} \infty >\begin{itemize} >\item this equation says that >\end{itemize} >. > > >>> def rawlines(prompt, lineprompt=''): ... lines = [raw_input(prompt+'\n'+lineprompt)] ... while lines[-1:][:]!=['.']: ... lines.append(raw_input(lineprompt)) ... return lines ... >>> lines = rawlines("Type in some input (type in '.' to end) :","=>") Type in some input (type in '.' to end) : =>\sum_{i=1}^{n} \frac{\sqrt{2}}{\alpha} \infty =>\begin{itemize} =>\item this equation says that =>\end{itemize} =>. >>> for line in lines: print line ... \sum_{i=1}^{n} \frac{\sqrt{2}}{\alpha} \infty \begin{itemize} \item this equation says that \end{itemize} . Return lines[:-1] if you don't want the ending dot line back. I passed a line prompt of '=>', but you can let it default to '' to get what you specified. OTOH, you might want to consider something other than '' as the line prompt, to make it clear that it's waiting for input. Regards, Bengt Richter From aahz at pythoncraft.com Sun Mar 31 14:30:19 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 14:30:19 -0500 Subject: PEP 285: Adding a bool type References: <3CA75EFB.A79F6D61@alcyone.com> Message-ID: In article <3CA75EFB.A79F6D61 at alcyone.com>, Erik Max Francis wrote: >Ralph Corderoy wrote: >> >> What do you think of `truth(x)' for all the good reasons listed >> elsewhere in the thread? You used truth yourself instead of Boolean >> above. > >But you already have precisely this: > > from operator import truth 13. There should be one-- and preferably only one --obvious way to do it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From cgale1 at cox.net Sat Mar 23 02:10:54 2002 From: cgale1 at cox.net (Van Gale) Date: Sat, 23 Mar 2002 07:10:54 GMT Subject: Why do Windows sockets break after exactly 4 minutes? References: Message-ID: <2UVm8.30655$J54.1855090@news1.west.cox.net> "Geoffrey Talvola" wrote in message news:mailman.1016825146.27883.python-list at python.org... > Gordon McMillan wrote: > > > > Your client does a shutdown(1) after sending some data. > > The shutdown(1) causes the server to fall out of the > > receive loop. It then sleeps for however long specified, > > sends some data and closes the socket. > > > > In other words, the behavior is exactly what you asked > > for, and Windows' socket implementation has nothing to > > do with it. Geoff, I'm a little late in this conversation so haven't read all the replies, and I'm not really a Windows programmer (IANAWP?), but I'll try to contribute anyway :) I think Gordan is right, given the following information: ftp://ftp.microsoft.com/bussys/sql/kb/q105/7/94.txt http://support.microsoft.com/default.aspx?scid=kb;EN-US;q149532 Do a "Find on this page" for MSL at http://www.microsoft.com/technet/treeview/default.asp?url=/TechNet/itsolutio ns/network/deploy/depovg/tcpip2k.asp So, I'm guessing what's happening is the shutdown(1) is causing the server to stop responding to keepalives after 4 minutes. I can't say off the top of my head whether or not this is buggy behaviour. Try setting TcpTimedWaitDelay in the registry to 300 and see if the client connection breaks at the 5 minute mark. Don't forget the obligatory Windows reboot! If this isn't the problem I'll just place the blame on not having an NT/2k box for testing before posting :) -- Van Gale From tim.one at comcast.net Mon Mar 4 20:04:12 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 04 Mar 2002 20:04:12 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: Message-ID: [Tim] >> For the rest of it, it looks like the "1e-200**2 raises OverflowError" >> glitch is unique to platforms using glibc. [Jon Ribbens] > No, it happens on OpenBSD 2.7 also. > > Python 2.2 (#2, Feb 3 2002, 18:27:17) > [GCC 2.95.2 19991024 (release)] on openbsd2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 1e-200**2 > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: (34, 'Result too large') I don't understand your "no": the output shows that Python was built using GCC 2.95.2, yet you're claiming this does *not* use glibc? gcc and glibc go together like Guido and Van Rossum . From scott2237 at yahoo.com Tue Mar 12 21:09:40 2002 From: scott2237 at yahoo.com (googlePoster) Date: Wed, 13 Mar 2002 02:09:40 GMT Subject: trouble testing for existance of variable References: <4bbaa6d6.0203121352.4358f14@posting.google.com> Message-ID: in the interest of full disclosure, I should have said since I am using python as a gvim scripting tool I must import the gvim variable, colors_name, before I can work with it the following try: curr_color = vim.eval("colors_name") except NameError: curr_color = "none" print "colors_name does not exist" else: print "colorscheme: %s" % curr_color gets the name of the colorscheme just fine when it's defined, but when not, yields E121: Undefined variable: colors_name E15: Invalid expression: colors_name Traceback (most recent call last): File "", line 1, in ? File "testMe.py", line 36, in ? curr_color = vim.eval("colors_name") vim.error: invalid expression grrrrrrrr "Cliff Wells" wrote in message news:mailman.1015972703.8850.python-list at python.org... > On 12 Mar 2002 13:52:01 -0800 > googlePoster wrote: > > > if I want to know if a variable exists before > > testing it, what do I do? > > How about > > try: > colors_name > except NameError: > print "it doesn't exist" > else: > print "it exists" > > -- > Cliff Wells, Software Engineer > Logiplex Corporation (www.logiplex.net) > (503) 978-6726 x308 (800) 735-0555 x308 > From jamie.carl at salientnetworks.com.au Tue Mar 19 20:53:06 2002 From: jamie.carl at salientnetworks.com.au (Jamie Carl) Date: Wed, 20 Mar 2002 01:53:06 GMT Subject: Serial Ports References: <3c96c220$1_1@news.iprimus.com.au> Message-ID: <3c97eb64$1_1@news.iprimus.com.au> Excellent.. Done.. works great (kinda) :-) Exactly what I was after. J "Dietmar Lang" wrote in message news:slrna9f8rk.b4.dietmar at bronko.fh-wedel.de... > Hi! > > Jamie Carl wrote: > > I'm still fairly new to Python so forgive me. I'm hoping someone can > > point in the right direction regarding how I would go about accessing a > > serial com port from Python. I'd like to do it mainly under Linux, but > > hopefully it will work under windows aswell. > > > > Is it possible? Can someone point me to some documentation or code samples? > > Check out the Universal Serial Port Python Library: > > http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html > > Hoping this helps, > > Dietmar > > -- > I haven't lost my mind -- it's backed up on tape somewhere. From jeff at ccvcorp.com Mon Mar 18 15:43:32 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 18 Mar 2002 12:43:32 -0800 Subject: PIL Headaches: Advice Needed References: <4378fa6f.0203161652.7f28e23b@posting.google.com> Message-ID: <3C965173.6DA78CDF@ccvcorp.com> Marc wrote: > I have gone thru all the tutorials and read me's I can find, and I > still can't get PIL to work for me. At no point has it ever been able > to recognize any file that I try to open in all formats (.bmp, .jpg, > .gif, etc). What code are you using? The following should work: import PIL.Image my_image = PIL.Image.Open("sample.jpg") Jeff Shannon Technician/Programmer Credit International From borcis at geneva-link.ch Tue Mar 5 03:29:07 2002 From: borcis at geneva-link.ch (Boris^2) Date: Tue, 05 Mar 2002 09:29:07 +0100 Subject: [ANN] PEP 279 version 1.5 References: Message-ID: <3C8481D3.1000303@geneva-link.ch> Raymond Hettinger wrote: > PEP 279 -- Enhanced Generators has been updated: > http://python.sourceforge.net/peps/pep-0279.html > > Additional comments are solicited before it is sent > to Guido for pronouncement. >> By analogy, consider the quality improvement from GOSUB (which had >> no argument passing mechanism) to modern procedure calls (which can >> pass in arguments and return values). I know it's rhetorical, but I find that the above implies too much for the GOSUB. Elaborate scoping rules and parameter passing mechanisms existed in other languages (witness Lisp, Algol, Fortran, PL/1, Simula) as Basic was being inoculated to innocent victims. That shameful hack passing for a language doesn't deserve the status of ancestor achievement you imply for it. Leave that to Bill Gates. Boris Borcic From alanmk at hotmail.com Fri Mar 1 06:34:10 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 1 Mar 2002 03:34:10 -0800 Subject: Mod-python problem References: Message-ID: bp at sam.localdomain (Bob Parnes) wrote in message > The only trouble is that I had forgotten about my httpd.conf file. The > relevant lines are: > > > AddHandler python-program .py > PythonHandler mod_python.publisher > > > This was the reason I used main() instead of handler(); in the url window I > typed in "test.py/main" and got the table but no response from FieldStorage(). > Are publisher and FieldStorage() incompatible, or am I misusing them? Knowing > what I know now, I can probably get along without publisher, but I am > accustomed to placing several scripts in one directory. Bob, Sorry, I didn't realise you were using the Publisher handler, otherwise I wouldn't have gone and rewritten your code to work with a completely different paradigm. And I was wondering how you were getting results with something that just didn't look like it could work %-) D'oh! Silly me. Warning: I don't use the publisher handler, so I haven't tested any of the stuff below! Looking at the publisher handler documentation, section 6.1.3: Publisher handler: Form data http://www.modpython.org/live/mod_python-2.7.6/doc-html/node74.html which says: "In the process of matching arguments, the Publisher handler creates an instance of FieldStorage class. A reference to this instance is stored in an attribute form of the Request object. Since a FieldStorage can only be instantiated once per request, one must not attept to instantiate FieldStorage when using the Publisher handler and should use Request.form instead." So it would appear to me that you shouldn't be trying to instantiate the util.FieldStorage() class at all. Instead, you should be referring to the already extant req.form attribute. So your main function should change from this def main(req): formDict = util.FieldStorage(req) cl = clTest() return cl.cltest(req, formDict) to this def main(req): cl = clTest() return cl.cltest(req, req.form) As mentioned, I haven't tested any of this! Hope this helps, Al. From fperez528 at yahoo.com Fri Mar 15 11:08:09 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 15 Mar 2002 16:08:09 +0000 Subject: Optimising list comparison References: Message-ID: Graham Ashton wrote: > A friend of mine is using Python in a research project where he needs to > compare each element of two vectors, such that comparing [a, b, c] and > [d, e, f] would involve comparing a with d, b with e and c with f. > Are your vectors 3-d only? If so, I assume you're worried about performance because you have *many* of them. The fastest (super-easy) way to do it is to shove them into two 3xN NumPy matrices and do the comparison there. You can then compare them and will get a _fast_ comparison done by Numeric, with all the necessary information for extracting the differing elements. Just some thoughts, f. From peter at engcorp.com Mon Mar 25 19:29:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 19:29:33 -0500 Subject: Debugging on windows via print statements -- reliable? References: <3C9EA59A.D3F76D2F@engcorp.com> <3C9F0F85.345200F2@spam.nada.kth.se> Message-ID: <3C9FC0ED.EB34041C@engcorp.com> Bj?rn Lindberg wrote: > > Peter Hansen wrote: > > > By the way, how can Python code get "stuck"? Is it a logic flaw, > > or are you talking about the kind of "stuck" that used to happen, > > in the "old days", when we were always writing code in languages > > which would actually crash the computer? > > Which language has ever been known to crash the computer? Perhaps you > are referring to earlier MS operating systems, which were known to crash > themselves? I should perhaps have said "writing code in languages which allowed us to crash the computer". As in, pointers! C, to be even briefer. ;-) -Peter From mhammond at skippinet.com.au Thu Mar 14 17:25:34 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 14 Mar 2002 22:25:34 GMT Subject: Disabling rexec for ActiveScripting in Local Intranet Zone? References: Message-ID: <3C912376.7020902@skippinet.com.au> Gerson Kurz wrote: > When you do Client-Side ActiveScripting in Python, you cannot create > win32com objects. If my understanding is correct, this is caused by rexec() > limiting what you can do, for security reasons. However, over Client-Side > Scripting languages such as JScript and VBScript allow you to create > ActiveX objects, if IEs security settings allow that. Is there some trick > to allow using ActiveX objects (if security is "properly" configured) for > the local zone? > > The situation is this. I have a C++ written ActiveX object for scripting > webpages that controls some kind of hardware. I want to be able to write > test scripts in python, and not in Javascript. Test scripts that are run > from the command line work just fine, only IE scripts don't, because of > said limitations. Currently, I have to stick with Javascript for sample > codes, which is (not surprisingly) a PITA. I have no idea :) I would expect that if IE has set security approriately, then Python would not operate under rexec at all - this is certainly what happens for WScript and ASP. What version of win32all? Mark. From joonas at olen.to Sat Mar 2 05:25:41 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: 2 Mar 2002 02:25:41 -0800 Subject: (Hopefully) simple IDLE question References: Message-ID: <11aed8f9.0203020225.4d8b7922@posting.google.com> "Seth Jones" wrote in message news:... > Hi all, > > Is there any way to set the current working directory for a file being used > in IDLE? I simply want to open a file that is in the same directory as my > script, which I've opened into the > idle window, and I don't want to hard-code the full path of the file. > Failing that, is there any alternative in Windows 95 to the normal command > line? I ask, since the reason I'm using IDLE in the first place is to avoid > calling my script from the horribly unsatisfying DOS prompt. Failing even > that, is there a better way to get error output from a .pyw file than to > catch all exceptions and write them to a file? > > A google search did lead me to an old mailing-list post about adding the > option for setting > current directories in IDLE, but apparently that hasn't been done yet. > > > I hope someone can convey some wisdom to this poor soul who's still stuck on > win95. > Thanks in advance for any advice. IDLEfork should handle the working directory correctly. See http://idlefork.sourceforge.net/ From siegfried.gonzi at kfunigraz.ac.at Mon Mar 4 09:59:32 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Mon, 04 Mar 2002 15:59:32 +0100 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> <3C837DD1.2007DFA0@engcorp.com> Message-ID: <3C838BD4.5A5D9298@kfunigraz.ac.at> Peter Hansen wrote: > > Siegfried Gonzi wrote: > As far as absolute time goes, don't use a tool for that. Just > run the program and ask yourself "was that fast enough for my > needs?". If your program runs once a day, even 70 sec is fast > enough. If you run it every thirty seconds, I guess you have > to go with the Clean version after all. :-) Please: Do not use Clean! It took me (yesterday) 6 hours to re-use my Clean version (only some minor changes due to some different parameters), which I wrote last summer. The type-system and arrays are a horror (it is nearly impossible to work with). Lists are okay; but arrays in Clean will put some pearls on your forehead Clean is very unflexible. Btw. I had expected it. I got some improved Lisp version (1/4 of my code and 30% faster). I am not sure whether it is posted to comp.lang.python; if not I can mail it (with the proper reference to the master which wrote it) to you (drop me a note). Normaly, I do not have any problems with verbose code. Okay, my Lisp (and Clean) code does some extra work (for example: counting the lines in a file for creating the array) which would be not necessary. You can work with lists and copy them to an array (which my Python function -- honestly: by accident -- does). I felt for and believed what computer scientists are preaching: pure functional programming will improve your code and will let you produce re-usable code. But after Clean I am not sure whether I am only just too simple minded to grasp their concepts. S. Gonzi From camh at zip.com.au Mon Mar 11 19:14:20 2002 From: camh at zip.com.au (Cameron Hutchison) Date: Tue, 12 Mar 2002 11:14:20 +1100 Subject: Setting UNIX environment with a Python script References: <3C8D143A.17963385@all.com> Message-ID: On Tue, 12 Mar 2002 08:13:05 +1100, Grant Edwards wrote: > In article <3C8D143A.17963385 at all.com>, Nom de Plume wrote: > >> The only step left is sourcing the ora_env.[name] file from within >> Python in a way such that the environment of the parent shell is >> modified. Anyone have any ideas? I have tried: > > It is not possible under Unix to modify the environment of your parent > process. You can only modify your own environment and then export that > environment to your children. What you need to do instead is have your python program print on stdout the name of the ora_env file to source. Then you invoke your python script from your shell login script like this (bourne style shell assumed): eval "source ora_env.`get_ora_name`" where get_ora_name is your python script. If you're not familiar with shell scripting, look up command substitution or backquote substitution in the manpage for how this works. [To be honest, I can't remember if 'source' is bourne shell or a bash-ism. You can always use the . command, but that doesn't look as clear and may have been harder to explain] From geoff at gerrietts.net Tue Mar 5 18:04:02 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 5 Mar 2002 15:04:02 -0800 Subject: Newbie ?:A more concise way? In-Reply-To: <3C852B7E.2AD1FD64@ccvcorp.com> References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <8fc4b19e.0203040130.17140530@posting.google.com> <8fc4b19e.0203042338.141afe8b@posting.google.com> <3C852B7E.2AD1FD64@ccvcorp.com> Message-ID: <20020305230402.GD11517@isis.gerrietts.net> Quoting Jeff Shannon (jeff at ccvcorp.com): > > I think that I have seen notables in the python community (I would > > name names, but I don't have quotes to reference) have indicated > > regret at the introduction of map() and friends into the language. > > They end up being appropriate only very, very rarely. > > > > The lambda construct doesn't suffer from quite the same stigma, though > > I think some feel that it's overused, and to bad effect. I think Carel has the right of it, actually. Lots of supporting evidence for distate for map() and friends: Thomas Wouters calling them "evil" (in quotes): http://mail.python.org/pipermail/python-dev/2000-August/008266.html Tim Peters defending use of lambda & map interactively (and quoting from Guido, who regrets them all): http://sunsite.bilkent.edu.tr/pub/languages/pub/tim_one/000177.html Tim making special exception for lambda: http://sunsite.bilkent.edu.tr/pub/languages/pub/tim_one/000179.html Tim admitting (4 yrs later) that lambda was maybe not so good: http://groups.google.com/groups?selm=000701bd7caf%24c27f8520%2456472399%40tim And Guido's pronouncement of disgrace upon the constructs in 1994: http://groups.google.com/groups?selm=9405270809.AA02474%3Dguido%40voorn.cwi.nl So now there's some citational evidence. If they haven't changed their minds since, it looks like the whole lot be damned. --G. -- Geoff Gerrietts "I have read your book and much like it." --Moses Hadas From nas at python.ca Mon Mar 25 18:54:30 2002 From: nas at python.ca (Neil Schemenauer) Date: Mon, 25 Mar 2002 15:54:30 -0800 Subject: list comprehension question In-Reply-To: ; from tim.one@comcast.net on Mon, Mar 25, 2002 at 03:15:23PM -0500 References: <20020325113323.A26319@glacier.arctrix.com> Message-ID: <20020325155430.A27495@glacier.arctrix.com> Tim Peters wrote: > there's generally no reason to suppose that len(iterable) wouldn't be > destructive Good point. Neil PS. tell the bot I'm sorry I doubted the correctness of his code From logiplexsoftware at earthlink.net Mon Mar 11 17:15:38 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Mon, 11 Mar 2002 14:15:38 -0800 Subject: wxProgressDialog wonky under Win32 In-Reply-To: References: Message-ID: <20020311141538.525b70f6.logiplexsoftware@earthlink.net> On Mon, 11 Mar 2002 19:15:34 GMT Grant Edwards wrote: > > According to one of the wx mailing list archives, this is a > known bug in the MSW port of wxWindows (the "size" value of a > gauge is treated as a 16-bit number). It's been fixed, but > it's still available only from CVS. The usual trick I use to get around this is to use a gauge with a max of 100 and then update it with the percentage done (n/max) rather than the number of items done (n). This can also help performance as you can avoid updating the gauge as often if you have a large number of items to process. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From sjmachin at lexicon.net Fri Mar 29 16:22:28 2002 From: sjmachin at lexicon.net (John Machin) Date: 29 Mar 2002 13:22:28 -0800 Subject: number of lines in a file References: Message-ID: "Joseph Youssef" wrote in message news:... > hello, I am nwe to Python and I'm trying to write this script but I need > it to check how many lines is in the file and I don't know how so I'm > hoping someone could tell me. > Welcome to Python. Others have suggested approaches which attempt to read the whole file into memory, but may succeed very slowly or not at all in the event that you have files that are larger than your machine's physical memory; here's a slightly more robust approach: num_lines = 0 f = file('path_and_file_name') for line in f: num_lines += 1 f.close() HTH, John From dale at riverhall.NOTHANKS.co.uk Thu Mar 28 12:31:15 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 28 Mar 2002 17:31:15 +0000 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: <37j6auohv35hg3kfol3m5hnrelvd4i4vdk@4ax.com> I like it. You *have* to allow variables in the match list, however, plus objects that evaluate to a suitable value or sequence of values. There's no reason why the compiler couldn't detect and optimise the case where only constants are used. I prefer 'else' to 'any' - a lot. I makes more sense and doesn't need a new keyword. As for the name, 'match'? Given that it would cause problems with the 're' module, how about a name that is invalid syntax at the moment. What about names with spaces? 'match on'? 'switch on'? 'select from'? It would give the syntax analyser something to think about but wouldn't break any code. Such a scheme would allow all sorts of safe expansions. Alternatively, capitalise Java-style: 'matchOn' or 'switchOn' I know I'm supposed to ignore it but I'd also like to support the addition of UNTIL and UNLESS as alternatives for WHILE NOT and IF NOT. I whince every time I have to reverse the logic of a test just to suit the restrictive syntax of the langage. -- Dale Strickland-Clark Riverhall Systems Ltd From max at alcyone.com Sun Mar 31 14:10:40 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 31 Mar 2002 11:10:40 -0800 Subject: PEP 285: Adding a bool type References: Message-ID: <3CA75F2F.198772EB@alcyone.com> Aahz wrote: > But what do you think of changing bool() to truth()? In the new type unification scheme, bool seems a much better name than truth. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From phlip_cpp at yahoo.com Tue Mar 26 19:31:30 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 26 Mar 2002 16:31:30 -0800 Subject: Where is an unbroke version of PyMagick? Message-ID: <63604d2.0203261631.7731b2e7@posting.google.com> Hypo Nt: The version here says it's broken, and does not explain why: http://bel-epa.com/pyapache/Python/PyMagick/ When I build it, it complains about serious errors regarding its opinion of the API found in ImageMagick-devel-5.3.3-5mdk.i586.rpm. Careful consideration of the matter reveals the possibility that the library is broken because it's from last year and that ImageMagick is recent. I don't want to do Magick to my Images thru C or C++. Any tips? -- Phlip From philh at comuno.freeserve.co.uk Thu Mar 28 09:48:28 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 28 Mar 2002 14:48:28 +0000 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: On Wed, 27 Mar 2002 23:02:20 -0500, Peter Hansen wrote: >Jim Dennis wrote: >> >> The core loop is something like: >> >> freq = {} >> for line in file: >> for word in line.split(): >> if word in freq: freq[word] += 1 >> else: freq[word] = 1 >> >> (assuming Python2.2 for file interation and dictionary membership >> support using "in." I *really* like those 2.2 features! They make >> my psuedo-code so executable!) > >Something like freq[word] = freq.get(word, 0) + 1 > >would probably be faster, and it's a little simpler I think, >although I could see an argument that it's less readable. >Also doesn't depend on 2.2. IIRC in Awk you can just say: freq[word] ++ and it works correctly even when there is no pre-existing index of word in freq. IMO it's a pity Python isn't like that. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From sjoerd at acm.org Fri Mar 15 12:03:08 2002 From: sjoerd at acm.org (Sjoerd Mullender) Date: Fri, 15 Mar 2002 18:03:08 +0100 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> Message-ID: <3C92294C.19BCF936@acm.org> When select tells you there is something available to read, it doesn't mean there is a whole line available to read! It is very well possible that there is only one character available, but readline may want to read (a lot) more than that. Rich Cook wrote: > > At 11:09 PM -0600 3/14/02, Skip Montanaro wrote: > > >> selectables = [theProcess.childerr, theProcess.fromchild] > > >> (input, output, exc) = select.select([],selectables, selectables) > > ... > > > > >> It blocks forever waiting for theProcess.childerr.readline(bufsize) > > >> to return. I expect it to block waiting for select.select(); that > > >> would not be a problem. The problem is that select is claiming > > >> there's stuff to be read, then when I try to read it, it's not there! > > >> How can that be? > > > >Based upon the attribute names you are using, I suspect you instantiated > >os.Popen3 to create theProcess. These are file objects, not sockets. I > >believe select only blocks on sockets. See the comments about asynchronous > >file i/o near the bottom of asyncore.py. > > I don't really need select to block. I just want it to be accurate. > If it returns a file object in the list of things which are > available, why should then readline() block on it? > -- > > -Sincerely, Rich Cook 925-784-3077 > ******************************************************************* > Sometimes it is said that man cannot be trusted with the government > of himself. Can he, then, be trusted with the government of others? > Thomas Jefferson > ******************************************************************* > > -- > http://mail.python.org/mailman/listinfo/python-list From gimbo at ftech.net Thu Mar 7 11:11:33 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Thu, 7 Mar 2002 16:11:33 +0000 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <19650FF08A99D511B19E00B0D0F06323060B49@SRM201002> References: <19650FF08A99D511B19E00B0D0F06323060B49@SRM201002> Message-ID: <20020307161133.GD489@andy.tynant.ftech.net> On Thu, Mar 07, 2002 at 09:19:45AM -0600, Gustavo Cordova wrote: > But, what about identical twins, who speak their own language > well before they start speaking their parents? Aren't they > communicating with their peer(s)? It's not just twins - older children sometimes act as "interpreters" for their younger siblings. -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From p.magwene at snet.net Fri Mar 15 22:29:23 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sat, 16 Mar 2002 03:29:23 GMT Subject: Shot in the Dark: Minimum-weight perfect matching algorithm References: Message-ID: On Fri, 15 Mar 2002 22:14:03 -0500, Paul Magwene wrote: > Some more digging did turn up this neat little Java applet: > > http://www.math.sfu.ca/~goddyn/Courseware/Visual_Matching.html > > with source code in the same directory. I may try and translate that to > something Pythonic - it's definitely more inviting than the Blossum4 > code. Well, that's of limited use - it only works for points in the plane. Back to the drawing board.... --Paul From bass at slinkp.com Thu Mar 7 20:34:53 2002 From: bass at slinkp.com (Paul Winkler) Date: 7 Mar 2002 17:34:53 -0800 Subject: [OT] range() for unix shell References: <2adab837.0203071409.76588265@posting.google.com> Message-ID: <2adab837.0203071734.1a3bee80@posting.google.com> Skip Montanaro wrote in message news:... > Paul> Today, struck by the similarity between sh and python's for loops, > Paul> and facing an example which required us to generate a range of > Paul> numbers from boundary parameters, I wrote a sh range function. It > Paul> works just like python's range() function (allowing for syntactic > Paul> differences). > > Why stoop to sh? Here's a range command I've used for years written in > Python. ;-) (snip) Well, of course, that's the quickest way to do it if you know you'll always have python. Which is likely to be true EXCEPT when booting from an emergency floppy... precisely the time I seem to need the largest number of handy little tools... And as Neil pointed out, GNU seq does pretty much the same thing (with a totally different interface). Good to know about that one. But again, I'm not likely to use 16k of rescue floppy space for seq. Thanks for the comments... --PW From fperez528 at yahoo.com Fri Mar 15 11:25:13 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 15 Mar 2002 16:25:13 +0000 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: On Friday 15 March 2002 22:23, you wrote: > [Fernando P?rez wrote] > > > John Roth wrote: > > > Putting something into the start menu is dead easy. Just put a > > > link to the appropriate file into "c:Windows/Start Menu/Programs" > > > Note the blank, and watch your capitalization. Windows is > > > flaky about capitalization. > > > > This is only for win9x. Win2k/xp have per-user Start Menu dirs, and > > their location must be retrieved from the registry (Def. is > > C:\documents and settings\user-name\Start Menu, but it can vary). So to > > have this be reliable, there's no way around diving into the pleasures > > of the registry. > > Not true. There is a win32api call to get these directories. Mind you, > that requires you to have the PyWin32 extensions installed. > [snipped] Ah, thanks for the info. I assume those calls are basically wrappers for clean access to those registry keys which ultimately hold the information, but it's definitely better to read the registry via an api than by mucking with it directly. The bulk of what I had in mind (but didn't clearly express :) remains: you can't just assume C:\Windows\Start Menu, you need to get the actual value of that directory in some form (and your api solution is much better than my registry access). Cheers, f. From wlsonna at attglobal.net Thu Mar 14 19:46:24 2002 From: wlsonna at attglobal.net (William Sonna) Date: 15 Mar 2002 00:46:24 GMT Subject: Good book on Python? References: Message-ID: <0O7zTzsxerl5-pn2-mhhtKwE8MMds@localhost> On Thu, 14 Mar 2002 11:26:01, Antonis C Koutalos wrote: > > Hi there, > I would greatly appreciate information about a good book on python. I > have been programming C for a few years, but I know next to nothing about > python. Therefore, I would appreciate a book that describes the basics of > python as well as the more advanced features of the language. > > Thank you in advance! > > -A. > The Quick Python Book by Harms/McDonald is an excellent book if you want to get up to speed in a hurry. The best way I can think of to describe it is as a "Cliff Notes" for Python. Very terse and well-organized (and consequently VERY easy to browse) - just like Python itself. The book has saved me many, many hours. It focuses primarily on the base language - you won't find much about the more advanced packages, other than a terse, well-organized summary of several of them (and information about where to get more info). If there was a "Quick Java Book" or a "Quick C++ Book" I'd buy them in a heartbeat. From jeff at ccvcorp.com Tue Mar 26 14:03:42 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 11:03:42 -0800 Subject: list element of a class with the for statement References: Message-ID: <3CA0C60E.F1C6F707@ccvcorp.com> Anton Vredegoor wrote: > >because I would like to write something like: > > > >db=CRdb() > >for entry in db: > > print entry > > ....... > class CRdb: > > def __init__(self): > self.__fieldsName= [] > self.__keyname= [] > self.__records = ['first','secnd','third'] > self.__iRecord= 0 > > def __getitem__(self,i): > return self.__records[i] > Of course, if you're going this route, it's probably best to provide a __len__() method as well, and to deal with slices... Another alternative would be to derive your class from UserList.UserList -- this will "automagically" handle list-like behavior (except that your __records attribute will now be called data). Jeff Shannon Technician/Programmer Credit International From erno-news at erno.iki.fi Sun Mar 24 17:39:48 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 25 Mar 2002 00:39:48 +0200 Subject: Memory sizes of python objects? References: <3C9E06A0.EC4D51E3@engcorp.com> <3C9E2BA1.E500BE4A@engcorp.com> Message-ID: In article <3C9E2BA1.E500BE4A at engcorp.com>, Peter Hansen writes: | I don't get that behaviour. On my machine, with Python 2.2, for | all intents and purposes the memory allocated stays constant. | Did I overlook something? hard to say. how did you measure it? with the following program.. import os a = [0] * 1000000 if 0: b = 1 for i in xrange(len(a)): a[i] = b*51 else: b = 2 for i in xrange(len(a)): a[i] = b*51 os.system("ps u %d" % os.getpid()) i get this: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND erno 2664 41.3 3.2 39680 33680 pts/25 S 00:37 0:05 python paa.py changing the "if 0" to "if 1" gets me USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND erno 2691 44.2 0.9 15712 9712 pts/25 S 00:37 0:05 python paa.py the difference is about 24 megabytes, so i'd say an integer object takes up 24 bytes on this platform. -- erno From mertz at gnosis.cx Mon Mar 4 13:50:49 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Mon, 04 Mar 2002 13:50:49 -0500 Subject: Text Search Engine that works with Python In-Reply-To: References: Message-ID: |...text search engine that works with Python? What I'm looking for |specifically is something that will compress the text and still allow |searches and retrievals that can be exact matches or proximity based. |The text I want to compress and search is huge (70 megs) and should |compress down to half, not including any index files that might be |required by the search engine. My indexer.py modules does this (mostly). I wrote an articles discussing the module at: http://gnosis.cx/publish/programming/charming_python_15.txt I have now incorporated it into a package at: http://gnosis.cx/download/Gnosis_XML_Utils-0.9.tar.gz The indexer is sort of an ugly duckling in there, since it doesn't have anything to do with XML, per se. But xml_indexer.py uses indexer.py for support, so I bundled things this way. Anyway, indexer does not allow proximity searches, but does allow searches for multiple words that occur in the same documents. The indexes are quite reasonable sized, and the indexer will operate on gzip'd files happily (it wouldn't be difficult to add support for zip, bzip2, etc). The module itself doesn't perform compressions, but that's what 'gzip' is for. -- 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 brueckd at tbye.com Fri Mar 15 16:08:03 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 15 Mar 2002 13:08:03 -0800 (PST) Subject: Converting relative URLs to absolute In-Reply-To: <23891c90.0203150820.6362868@posting.google.com> Message-ID: On 15 Mar 2002, Paul Boddie wrote: > > This precisely what I'm looking for. As someone else pointed out in > > another post, urllib should have this but, sadly, does not. > > The module I mentioned [1] doesn't attempt to handle more > sophisticated URL types, such as... > > http://user at somesite/somepath > > Indeed, a more generic URL parser really needs to be put into the > standard library whilst retaining the simplicity that one tends to see > in other "path" manipulation APIs (eg. os.path) - the world doesn't > need another overcomplicated Java-like API to do the simplest of > things. I wonder if mxURL might at least provide inspiration. Rather than add a new module, why not add more functionality to the urlparse module in the standard distribution? (what functionality do you need beyond what's already there, anyway?) -Dave From bokr at oz.net Fri Mar 15 20:45:42 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Mar 2002 01:45:42 GMT Subject: Help Required References: Message-ID: On 15 Mar 2002 17:24:33 -0800, surajsub at netscape.net (Surajsub) wrote: >Hi, >I am a newbie to Python and am pretty fascinated by it power and >speed.I am however puzzled in trying to write this script. >The script builds a list of userids to be fed to ldap and it is >supposed to be > >uid1,uid2,uid3....and so on.( Notice there is no space) > >However when i am trying to create the uid list it gives > >uid1, uid2, uid3,...and so on. >how do i get rid of this leading space if u would call it.. >string.lstrip does not work either. > >what am i doing wrong? It would be easier to say if you showed us what you are doing ;-) Where are your uid's coming from in your program? Assuming some function getuid() produces 'uid1' or 'uid2' etc each time, and '' or None when there's no more, #----< UNTESTED! >---------- uids = [] while 1: uid = getuid() if not uid: break uids.append(uid) combined = ','.join(uids) #--------------------------- should give you 'uid1,uid2,uid2' etc. bound to combined. Regards, Bengt Richter From johnroth at ameritech.net Thu Mar 21 19:03:23 2002 From: johnroth at ameritech.net (John Roth) Date: Thu, 21 Mar 2002 19:03:23 -0500 Subject: Develop-test-debug cycle References: Message-ID: "Dale Strickland-Clark" wrote in message news:un2h9ukh13kddcd3ooc9osejapiaf5v6t3 at 4ax.com... > I can't believe I'm doing this this best way. > > I am debugging a large system written in Python with modules spread > over 4 directories. I'm using PythonWin under Win2K to set-up the > environment and run the code. > > Setting up the environment typically involves the following commands: > > import sys > sys.path.append("x:\\whereever") > from wibbleModule import wibble > wibs = wibble(args) > > wibs.methods(args) > > > > At this point, I fix the error. > > Now, I haven't figured out a way of continueing past this point > without quiting and starting from scratch because there appears to be > no way to get Python to reload a module. The reload() function doesn't > do it. > > I've tried stuff like this: > > del wibs > reload(sys.modules['wibbleModule'] > > but I still seem to have the old version loaded. > > I've also tried using PyCrust for this but it suffers from the same > problems. I assume IDLE does too. > > How do others go about interactively debugging large Python OO-based > systems? I don't. I got bit by the XP bug a while back, and now I write all unit tests in advance, using the 'unittest' module. I keep the editor (PythonWin) open, save the module I've just changed, and invoke a script at the command line to run the current test set. Works like a charm, and has the additional advantage that I don't have to worry about breaking things with changes - the unit tests are persistant, so they'll tell me. I don't have to go into the debugger very much to figure out a problem, so reloading the module from scratch isn't a significant issue. John Roth > > Thanks for any pointers. > -- > Dale Strickland-Clark > Riverhall Systems Ltd From cthuang at vex.net Wed Mar 27 19:45:03 2002 From: cthuang at vex.net (Chin Huang) Date: Thu, 28 Mar 2002 00:45:03 GMT Subject: win32 problem interacting with word97 References: Message-ID: In article , Andrew Brown wrote: >I am trying to convert a couple of hundred MS word 97 files to html, and >then reformat them into a template. > >Mostly, this works, but there are some which contain accented letters, >and the Word html converter barfs on these in a peculiarly irritating >way: it puts up a dialogue box with a message saying > >"This document contains characters that are not in the current language >encoding. To preserve them, choose cancel and select the appropriate >language encoding. For multilingual documents, use UTF-8." > >It is possible to press "OK" or "cancel" or any damn thing if you can see >the dialogue box; but my program can't see it, and goes on trying to get >word to process the next file until, after about 30 seconds python >crashes completely. Only then do I see the dialogue box which has caused >the trouble. Try setting the DisplayAlerts property of the Application object to 0. Word will not display any dialog boxes. It will choose the default action and continue the operation. From skip at pobox.com Thu Mar 7 18:06:59 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 17:06:59 -0600 Subject: [OT] range() for unix shell In-Reply-To: <2adab837.0203071409.76588265@posting.google.com> References: <2adab837.0203071409.76588265@posting.google.com> Message-ID: <15495.62099.260328.51487@beluga.mojam.com> Paul> Today, struck by the similarity between sh and python's for loops, Paul> and facing an example which required us to generate a range of Paul> numbers from boundary parameters, I wrote a sh range function. It Paul> works just like python's range() function (allowing for syntactic Paul> differences). Why stoop to sh? Here's a range command I've used for years written in Python. ;-) #!/usr/local/bin/python import sys, string def usage(): print """ usage: range high range high step range low high step In first case, low == 0 is implied If no step size is given, 1 is assumed """ exit low = 0 step = 1 if len(sys.argv) == 2: high = int(sys.argv[1]) elif len(sys.argv) == 3: high = int(sys.argv[1]) step = int(sys.argv[2]) elif len(sys.argv) == 4: low = int(sys.argv[1]) high = int(sys.argv[2]) step = int(sys.argv[3]) else: usage print string.join(map(str, range(low, high, step))) From johnroth at ameritech.net Fri Mar 29 08:00:13 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 29 Mar 2002 08:00:13 -0500 Subject: Program termination problem References: Message-ID: "Garyr" wrote in message news:ua6r509m5uradc at corp.supernews.com... > I have a program that displays a Tkinter Text widget. I would like to be > able to place text in the window via the clipboard. I found the following > clipboard code in a Google post: > > import win32clipboard as clip > ... > clip.OpenClipboard(0) > if clip.IsClipboardFormatAvailable(clip.CF_TEXT): > newText = clip.GetClipboardData(clip.CF_TEXT) > textwidget.insert(END, newText) > clip.CloseClipboard() > > This works but it causes the program to hang on exit. mainloop() returns but > the DOS window is frozen. The problem is associated with the clipboard > functions; i.e., commenting the insert line has no effect. > > I'm using Python 2.1 (Pythonwin 2.1.211) on Win98. > Any suggestions? > > Thanks in advance, > Gary Richardson That's a problem across the board with Tkinter and Windows. If you check sourceforge, you'll find it on the bug list. So far, nobody is quite certain whether the problem is in Windows, Tcl/Tk or Tkinter, and nobody is working on it, as far as I know. It only seems to occur if you are using the command line under Win 9x - it's reported not to be a problem if you invoke the program from an icon without a command window. As far as I can tell, the permanent solution is to use another graphics package. I'm very patiently waiting for anygui to become useful... John Roth > > > > > > > From sandskyfly at hotmail.com Fri Mar 29 09:35:40 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 29 Mar 2002 06:35:40 -0800 Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> Message-ID: Jeremy wrote: > I want to be able to do - have Python start a CGI server, serve a > page, get form data, get data from a database, and display dynamic > content. I don't need anything industrial strength, just something > that can handle a single user. OK. This one has bugged me before even though it's actually quite simple: [1] create the script that will instanciate CGIHTTPServer (server.py) # this is my favorite part (-: from CGIHTTPServer import test as serve if __name__=='__main__': serve() [2] create an html file which is going to call your python cgi script (test.html) CGI Test
    [3] create a folder in the same directory as the two files above (cgi-bin) [4] create the script that will be called by your html file (testcgi.py) #!python import cgi print "Content-Type: text/plain\n\n" form = cgi.FieldStorage() for name in form.keys(): print "Input: " + name + " --> " + form[name].value + "\n" print "Finished!" [5] point your browser to http://localhost:8000/test.html and enjoy. ciao Sandy From maxm at mxm.dk Thu Mar 21 02:30:06 2002 From: maxm at mxm.dk (Max M) Date: Thu, 21 Mar 2002 07:30:06 +0000 Subject: How Python Cornered Milosevic Message-ID: <3C998BFE.3020006@mxm.dk> On page 2 of this article in Wired, Patrick Ball, a 36-year-old "hacktivist," explains that he used Python, among other open source tools, to manage and visualize the data used as evidence against Milosevic. http://www.wired.com/news/politics/0,1283,51106,00.html The world works in mysterious ways sometimes. regards Max M From tim.one at comcast.net Mon Mar 4 02:45:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 04 Mar 2002 02:45:10 -0500 Subject: Apology to Bill Gates (was Re: ASV module, CVS modules) In-Reply-To: Message-ID: [John Machin -- maybe] > my_data.input_from_file("c:\test_data.csv", ASV.CSV(), > File "C:\PYTHON22\ASV.py", line 222, in input_from_file > file = open(input_file, "rb") > IOError: invalid argument: rb > Bill behaving badly: Seems like Bill chucks a wobbly if there is > a_bloody_tab_character in a file name. I could be maligning Bill > unjustly; could be GvR & Co -- I'll have a look at the Python source > in a minute -- but I'd bet a couple of pots of beer that it's down to > Bill. Under Python 2.2 on Win98SE I get this: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> open('c:\test_data.csv', 'rb') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'c:\test_data.csv' >>> Also under 2.1 and 2.0, except under 2.0 the detail reads IOError: [Errno 2] No such file or directory: 'c:\011est_data.csv' instead. From fperez528 at yahoo.com Wed Mar 13 11:38:14 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 13 Mar 2002 16:38:14 +0000 Subject: basic statistics in python References: Message-ID: dsavitsk wrote: > > i found this > http://starship.python.net/crew/hinsen/ScientificPythonManual/ > but it seems to be unix only and i am on win32. as far as standard you can probably get the stuff you want running under win. I'd be very surprised if all of Konrad's code was tied to unix (though I can't tell for sure, I use it under unix). > > There seems to be some stuff in scipy, but i am having trouble geting > through the docs.??also,?do?i?want?to?look?at?numpy? Scipy is early and still a bit rough to install, but fabulous. And yes, you NEED numpy for anything numerical in python above the toy level. Both konrad's libs and scipy are numpy based anyway. cheers, f From peter at engcorp.com Wed Mar 20 09:26:07 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Mar 2002 09:26:07 -0500 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C985678.8010200@pobox.com> Message-ID: <3C989BFF.62E9DA22@engcorp.com> Ahmed Moustafa wrote: > > For example, where I work, we have JRE for OS/390 (by IBM). > Is there a mainframe interpreter for Python? Or, will Jython do? Okay, now you're really getting into areas where you ought to do your own research and come back when you have questions you can't resolve on your own: http://www.google.ca/search?q=python+os%2F390 -Peter From jschmitt at ati.com Thu Mar 21 13:08:19 2002 From: jschmitt at ati.com (John Schmitt) Date: Thu, 21 Mar 2002 10:08:19 -0800 Subject: How Can I Determine the Operating System with Python? Message-ID: I did something mildly cheezy like this to distinguish between different windows flavours: #--------------------------------------------------------------------------- -- class ComputerInfo: OSnames =\ { "Windows 2000" : "Windows2000", "Windows 2002" : "WindowsXP", "4.10.1998" : "Windows98" } #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def __init__( self ): self.infoGet( "net config" ) # this is win98's syntax try: name = self.computername osname = self.OSName except: self.infoGet( "net config workstation" ) # this works for win2k and xp #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def infoGet( self, string ): computername = "Computer name" username = "User name" softwareversion = "Software version" infofile = open( "computerinfo.txt", "wt" ) CmdRun( string, infofile ) infofile.close() for line in fileinput.input( "computerinfo.txt" ): if line.find( computername ) == 0: self.computername = os.path.split( line[len(computername):].strip() )[1] if line.find( username ) == 0: self.username = line[len(username):].strip() if line.find( softwareversion ) == 0: self.softwareversion = line[len(softwareversion):].strip() self.OSName = ComputerInfo.OSnames[self.softwareversion] #--------------------------------------------------------------------------- -- def CmdRun( path, logfile=None ): print "CmdRun: ", time.ctime( time.time() ) print "CmdRun: ", path (instream,outstream) = os.popen4( path ) while 1: line = outstream.readline() if not line: break try: if logfile: logfile.write( line ) except IOError: print "Exception generated on '%s'" % line -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Fri Mar 8 18:37:37 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Mar 2002 23:37:37 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> Message-ID: On Fri, 08 Mar 2002 04:51:39 GMT, "Terry Reedy" wrote: > >"Bengt Richter" wrote in message >news:a6912n$jnt$0 at 216.39.172.122... >> Sorry, I wasn't making clear an unspoken condition I really had in >mind ;-) >> I think (3) does follow (2) using the added explicit condition that >the >> text quotation is to be part of the source text of a program or >module, >> and the quoted text must not need to be changed or restricted to do >it. > >With the added conditions, the logic works much better. > >... >> The simplest practical example is wanting to use a paste operation >> to insert arbitrary text into a program source without having to >inspect >> the text or modify it, yet be able to use it to define a string >> with the exact raw text value. > >As Greg Ewing noted, you still have to scan the text with your method, >so why not scan for triple quotes - which are *extremely* rare in any >text except Python code and *quite* easy to spot (speaking for >myself). One can always use the interpreter to check also. Write >s='''\ > >''' >and run or paste into interpreter. If there is a ''' that one missed, >there will almost certainly be a SyntaxError reported, with the line >number. One could also follow the definition of s with 'print >s[:-100]' to see if entire quotation got included in assignment. > >For myself, I can hardly imagine wanting to incorparate gobs of >someone else's text into my code. If I did, I would want to look at >it and/or isolate it in a separate module where it could be tested as >above. I would also feel free to modify it with escape codes if >necessary. > I'd prefer to have a quick look and choose an easy delimiter and be done, instead of all that testing to see if there were tricky \''' sequences and whatnot, and then fussing with the content, which diff could then no longer see as quivalent to the original. Regards, Bengt Richter From donn at drizzle.com Fri Mar 15 01:24:38 2002 From: donn at drizzle.com (Donn Cave) Date: Fri, 15 Mar 2002 06:24:38 -0000 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> Message-ID: <1016173476.645562@yasure> Quoth grante at visi.com (Grant Edwards): ... | When select returns a file descriptor, that means that read() | won't block. If only a partial line is available, then | readline() will still block. I doubt that this is going to be | an issue, since your output is probably line-oriented. That's a good point. The complementary problem, of course, is that once you have invoked readline(), it will read all the data available on the file descriptor, or a lot of it anyway, and return only the first line. The next time, it will return the next line from its buffer, but you have no way to know that it has another line waiting there. select() can't see it. There are solutions, I think the easiest thing in most cases is to throw away the file object and just use the file descriptor (fileno()) (or sockets in this case.) Donn Cave, donn at drizzle.com From bptonner at yahoo.com Sun Mar 24 18:38:51 2002 From: bptonner at yahoo.com (bptonner at yahoo.com) Date: Sun, 24 Mar 2002 18:38:51 -0500 Subject: Launching Tkinter or wxWindows frames from interpreter Message-ID: <3C9E638B.1260E9DC@yahoo.com> I want to launch frames to plot graphs from the Idle interpreter prompt. The example plotting utilties from wxPython/wxWindows (wxPlotCanvas), and from Scientific Python (TkPlotCanvas)are good starting points (and they both work fine). The problem is that once the windowing "app" is put into the event loop, the interpreter hangs up. In other words, after calling app.MainLoop() (wxWindows) or window.mainloop() (TkPlotCanvas)you can't continue in the interpreter until closing the frame or window. I can work around this by breaking the rules, and putting up frames without event loops (not calling app.MainLoop or window.mainloop). Everything works, except that then the frames cannot be closed. The OnCloseWindow event is still called, but it is apparently queued, waiting to be 'caught' by an event loop that has not been enabled. I need to be able to call a function that will pop open the Tkinter or wxWindow frame, but continue to allow input at the interpreter command line. What's the proper way to do this? -Brian From donn at drizzle.com Sat Mar 9 01:35:09 2002 From: donn at drizzle.com (Donn Cave) Date: Sat, 09 Mar 2002 06:35:09 -0000 Subject: PEP Parade References: Message-ID: <1015655700.378331@yasure> Quoth "A.M. Kuchling" : | In article , Donn Cave wrote: | > but putting us in kind of a backwater. If we sort of collectively | > agree on 2.1.1 (or whatever) for that role, though, that backwater | > could get pretty lively. | | Seems unlikely; if people can't muster enough interest to participate | in handling bugs and patches in the current CVS tree, the likelihood | of taking on the even drier and duller job of backporting fixes seems | an order of magnitude less probable. Unless someone can be found to | pay money for it, of course. Could be just the opposite, though. If you're submitting a fix so that it will turn up in the next release with everyone else's fixes, then people working with 2.1.x have it pretty good (because the next release is a minor one, not 2.3 or whatever comes out of the CVS tree next.) But I really wasn't thinking of fixes so much. If there are lots of people using 2.1.2 and it has a serious bug, then I'm sure someone will come up with a fix sooner or later, but I was thinking more in terms of 3rd party work, so to speak. Packages. Like the phenomenon Roy was describing, but on a more global scale - you find out there's a cool module out there, but alas, you'd need to upgrade to use it, and the upgrade would be more pain than it's worth. Steve Turnbull's solution "So you standardize locally", but applied at this scale - so you standardize globally. 2.1.2 is really a step forward for the Python world as a whole, since there's a massive 1.5.2 contingent out there right now. I don't know, there's been some gnashing of teeth about Redhat's release schedule vs. Python's, maybe they and other platform vendors really need a not-so-current release that's still somewhat active. Donn From weeks at vitus.scs.agilent.com Tue Mar 5 19:02:11 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Wed, 6 Mar 2002 00:02:11 +0000 (UTC) Subject: need to safely spawn subshells from multithreaded server - how? References: <3C84A082.4CB52129@dlr.de> Message-ID: <1015372931.356897@cswreg.cos.agilent.com> Thilo Ernst (Thilo.Ernst at dlr.de) wrote: : Somehow I was much more lucky in digging the web today, so after more : reading up I give a preliminary answer to my own question. Perhaps this : might help other people running into the same problem. It would be nice in : this regard if any thread/fork experts would assess whether the situation : is correctly summarized below. I'm glad you pursued this. In the past few years, I have on three completely independent occasions needed to implement a server process that forks subprocesses and waits for their completion in separate threads. I've had problems, but the code is too natural to give up on. Greg From denro at NSPAMearthlink.net Mon Mar 4 17:32:09 2002 From: denro at NSPAMearthlink.net (Dennis Roark) Date: Mon, 04 Mar 2002 22:32:09 GMT Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <20020227163411.71b4b4d8.alex@netWindows.org> Message-ID: Sheila King wrote in news:a5rfo4.3vsfkqf.1 at kserver.org: > > That's funny. I'm not familiar with the Lippman/Lajoie book, but I > have a LOT of C++ texts here at home. And I learned C++ from the > Deitel and Deitel book, and thought it was pretty good. Later, when I > taught C++ I used it as a reference, although I didn't select it as > the text for my course. Most people I know who are familiar with the > Deitel and Deitel C++ text think it is very good. > We must not know the same people. The Lippman/Lajoie book, as the Lippman book that preceded it, are superb and actually useful for learning and reference, although probably not for a first course. -- Dennis Roark denro at earthlink.net Starting Points: www.home.earthlink.net/~denro From ark at research.att.com Sat Mar 30 10:52:47 2002 From: ark at research.att.com (Andrew Koenig) Date: 30 Mar 2002 10:52:47 -0500 Subject: [Python-Dev] RE: PEP 285: Adding a bool type In-Reply-To: <200203301342.g2UDgTE01572@pcp742651pcs.reston01.va.comcast.net> References: <200203301342.g2UDgTE01572@pcp742651pcs.reston01.va.comcast.net> Message-ID: Guido> You've been staring at standards too much, haven't you? The Guido> difference between MUST and SHOULD isn't as clear-cut as most Guido> standards people use them. In the ISO standards world, ``must'' doesn't mean what you probably think it does: should: encouraged, but not required shall: required must: it is impossible for things to be otherwise So, for example, one can imagine describing a function with a Boolean parameter named x by saying something like: If x is true, the result shall be foo. Otherwise, x must be false, and the result shall be bar. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From philh at comuno.freeserve.co.uk Sat Mar 30 18:05:03 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 23:05:03 +0000 Subject: [ANN] PYNOSPAM 0.1 (and some Embedded-Python-Questions) References: <3ca4b9e8.10558859@news.t-online.de> Message-ID: On Fri, 29 Mar 2002 19:12:46 GMT, Gerson Kurz wrote: >pynospam is a Python-Powered extension for Microsoft Outlook, that >will > >- filter spam mail i.e. tag the subject line with [SPAM!] if it thinks >it is spam. > >- Because the spam detection is based on an at-runtime-interpreted >python-script, you can easily add your own spam detection algorithms >using regexs and whatnot. The fact that you've written this demonstrates that Outlook has a way of enabling user-written filters for incoming email. To your knowledge, does Outlook allow filters for outgoing email too? (The reason I ask is regarding my Herbivore program, which implements zero-effort encryption by filtering all incoming and outgoing email -- at some point I want herbivore to run on Windows email clients). (See for details of herbivore) -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From phr-n2002a at nightsong.com Tue Mar 26 15:39:27 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 26 Mar 2002 12:39:27 -0800 Subject: Primes.... References: Message-ID: <7xadsvm5c0.fsf@ruckus.brouhaha.com> "FREDRIK HULDTGREN" writes: > I am looking for a way(either by finding a module online, or by getting > some helpfull hints on how to write this myself) to generate **large** > prime numbers. All help is appreciated(Id rather write the code myself > since I tend to like understanding the code that I use, but if the math > is too heavy I'll have to use other code...) How large is large? If you're trying to do cryptography, just generate random odd numbers of the size you want, do some trial divisions to eliminate candidates with small divisors, then do a few Fermat or Miller-Rabin tests, til you get a prime. Of course if you have gmpy, just do this: import gmpy,secrand def getprime(nbytes): while 1: p=secrand.getlong(nbytes) | 3 if gmpy.is_prime(p): return p where secrand.py (for unix/linux) is as follows: # Secure random number generator # Copyright 2001 Paul Rubin, Fort GNOX Cryptography # Copying permissions: GNU General Public License version 2. # $Id: secrand.py,v 1.5 2001/09/21 07:10:44 phr Exp phr $ class _secrand: def __init__(self): self.__f = open("/dev/urandom") def getbytes(self,nbytes): return self.__f.read(nbytes) def gethex(self,nbytes): import binascii return binascii.hexlify(self.getbytes(nbytes)) def getlong(self,nbytes): return long(self.gethex(nbytes), 16) secrand = _secrand() If you're trying to break the world record for finding the largest known prime, you'd normally look at special types of numbers (Mersenne numbers) and use some special algorithms for recognizing them and doing the arithmetic. It's not really practical to do that in Python. From zippity_do_dah at growgreen.org Sun Mar 24 16:36:58 2002 From: zippity_do_dah at growgreen.org (Token Bowles) Date: Sun, 24 Mar 2002 21:36:58 GMT Subject: I am TGOS your new ruler References: <07fcd5f6.3ba05335@tgos.org> Message-ID: In article <07fcd5f6.3ba05335 at tgos.org>, TGOS wrote: > That's right you stupid, inbred, shit eating, pathetic, motherfucking, > brain dead, useless cocksuckers! I'm taking over all of Usenet! There > isn't a fucking thing you can do about it either! You're all a bunch > of worthless scumbags, and now you will all answer to me! If you don't > like this fact TOO FUCKING BAD! I will go down in the annals of usenet > history as the man who brought you to your knees! Now get down on your > knees and pay proper tribute to my glorious self! > > I AM THE GUARDIAN OF SAILOR MOON! LORD AND HIGH MASTER OF USENET! > > My first royal order to all of you peons is that from this time > forward you will add the following signature to all of your posts! > > Kewl!! From quinn at barf.ugcs.caltech.edu Wed Mar 13 16:59:18 2002 From: quinn at barf.ugcs.caltech.edu (Quinn Dunkan) Date: 13 Mar 2002 21:59:18 GMT Subject: structseq and keywords? References: Message-ID: On Wed, 13 Mar 2002 15:22:18 GMT, Nick Mathewson wrote: >As the original author of the structseq patch, I should respond. > >In article , Michael Hudson wrote: >> quinn at vomit.ugcs.caltech.edu (Quinn Dunkan) writes: > [...] >> In the current implementation, you're not really expected to create >> structseq objects. Why would you? > >I agree with this. One of the explicit design decisions was that >since it's so easy to create a lookalike class in Python, there's not >a lot of reason to expose structseq as a metatype. Ok, I guess what I really wanted was a DEFSTRUCT-like facility. I'll use Michael's python StructSeq for that. I was originally going to do things that way, but some demon whispered and I decided not to, for whatever reason. Thanks! From James_Althoff at i2.com Tue Mar 12 15:26:36 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 12 Mar 2002 12:26:36 -0800 Subject: PEP 284, Integer for-loops (fwd) Message-ID: [Tim Peters] > I didn't have subclassing in mind; e.g., Got it. Wrapping is better, too, because one generic wrapper can handle all table-like structures (instead of needing multiple subclasses). [snip generously provided sample implementation] > That implements more than the example at the start actually needs; > cut back to taste . Au contraire. Why not forget simplicity and pour on the spices -- heartburn and high blood pressure be damned? With this nice framework I can throw in lots of recent suggestions along with the kitchen sink. def rowIndices() # return iterator of 0,1,...,r-1 (might not need it, but I like it ;-) def colIndices() # similar def indexedRows() # return iterator of index,row pairs (might actually be handy) def indexedCols() # similar Yes, I just might go hog wild. [snip] > I'd try a dict, mapping types to unbound methods, like: > > rowcounter = {JTable: JTable.getRowCount, > DefaultTableModel: DefaultTableModel.getRowCount, > ThirdPartyBozo: ThirdPartyBozo.getNumberOfRows} > > def ri(table): > "Return indices of table rows." > return range(rowcounter[type(table)](table)) > > I don't know whether that works exactly as-is in Jython, but you get > the idea. The JTable.getRowCount part works in Jython, but type(table) doesn't because "type" returns the generic Jython class PyInstance -- kind of like how cPython returns 'instance' for classic-class objects -- so it doesn't differentiate properly. But table.__class__ works so I can use that as an alternative. > Unless you have an unbounded number of classes (a bad Smalltalk > habit you should have given up by now ), Actually, many implementations (due to the use of tagged pointers) have an upper limit of 2 ** 31 classes -- I've rarely had the need to define more than 2 ** 29 (give or take a couple that are often not *strictly* necessary but thrown in for the sake of "purity over practicality") even in large applications. So "unbounded" really is a bit of an unfair characterization. Jim oh yeah, forgot the . From James_Althoff at i2.com Wed Mar 6 14:53:15 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 6 Mar 2002 11:53:15 -0800 Subject: Status of PEP's? Message-ID: [Andy Gimblett] > This just came to me: > > for index in indices(items): > pass > > or maybe better yet: > > for index in items.indices(): > pass Warning: the latter could get you into trouble with the "methods are overrated" crowd . Some folks, indeed, are fond of this suggestion. Two points: 1) PEP 276 doesn't prevent "indices" from being added. 2) The "indices" approach is not general enough to handle the example used in PEP 276. >>># not the real thing, but an incredible simulation >>> >>>for rowindex in indices(mytable): >>> print mytable.getValueAt(rowindex,0) >>>... Traceback (most recent call last): File "", line 1, in ? TypeError: len() of unsized object >>> Jim From zfelleg at telnet.hu Sun Mar 24 17:49:41 2002 From: zfelleg at telnet.hu (Zoltan Felleg) Date: Sun, 24 Mar 2002 23:49:41 +0100 Subject: Installer 5b3 problem Message-ID: <3C9E5805.3060102@telnet.hu> Hello, If this list is not the right place for this stuff, please redirect me to the proper one (and forgive me for bothering you here). I have a problem with the new mcmillan installer, namely the following code freezes at the commands.getstatusoutput() line when its function runs as a thread. The script itself works correctly, the "frozen" executable does not. (It did work with installer 5b2). The system is Red Hat Linux 7.2, with Python 2.2 compiled from source, and the database (for the shelve) is gdbm. (I can use installer 5b2, but if the problem is not in my script, it would be nice to have the next installer version without this glitch). The script is as follows: import time import shelve import thread import commands def main(): db = shelve.open('/tmp/test.db') db.sync() callprogram('main') time.sleep(1) thread.start_new_thread(callprogram, ('thread',)) time.sleep(1) def callprogram(parameter): print 'Starting', parameter rc, output = commands.getstatusoutput('/sbin/ifconfig') print output, rc print 'Ending', parameter if __name__ == '__main__': main() It runs perfectly without opening the shelve, but if it is opened, the thread hangs... Regards, zoltan From mhammond at skippinet.com.au Fri Mar 15 23:20:11 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 16 Mar 2002 04:20:11 GMT Subject: Disabling rexec for ActiveScripting in Local Intranet Zone? References: <3C912376.7020902@skippinet.com.au> <3C92C792.6060406@skippinet.com.au> Message-ID: <3C92C800.6070309@skippinet.com.au> Mark Hammond wrote: Oops - premature send :) > To disable rexec, open pyscript.py and locate the following block: > def RegisterNamedItem(self, item): > if self.rexec_env is None: > if self.safetyOptions: > # Use RExec. > self.rexec_env = AXRExec(self.globalNameSpaceModule) > else: > # DONT use RExec. > self.rexec_env = AXNotRExec(self.globalNameSpaceModule) and modify the code accordingly. Of course, it seems to me that even better would be a fix so that if IE has had the security restrictions lifted, then RExec is not used. I will try and remember to look into this (but feel free to add a new bug in the ActivePython bug database) Mark. From DavidA at ActiveState.com Mon Mar 25 18:12:58 2002 From: DavidA at ActiveState.com (David Ascher) Date: Mon, 25 Mar 2002 15:12:58 -0800 Subject: Is it really so difficult to enable Tkinter? References: Message-ID: <3C9FAEFA.BB2A6A23@activestate.com> Bart Meerdink wrote: > > (Warning: I'm a bit of a Python-newbie) Welcome! > And sadly, the nice ActiveState rpm distribution, which worked out of > the box, seems not to be maintained anymore. Not true! We're a little late, but we're getting there. We'll do a 2.2 release immininently, showcasing a brand new Windows installer, accompanied by an RPM version. We'll follow up with 2.1.2 and 2.2.1 releases soon thereafter. On both Windows and Unix, these ActivePython releases will bundle Tcl/Tk 8.3.4. > One more question: is it on purpose that idle is left out? We forgot to include the Tools directory in previous ActivePython releases, an omission which has been fixed in the upcoming releases. -- David Ascher From bokr at oz.net Sat Mar 23 15:33:52 2002 From: bokr at oz.net (Bengt Richter) Date: 23 Mar 2002 20:33:52 GMT Subject: a website information gathering script References: <3C9B33FA.3D853D65@lmco.com> Message-ID: On Fri, 22 Mar 2002 07:39:06 -0600, Scott Hathaway wrote: >I have a simple python script which gathers information about a website >and produces an html report about what it finds. The way it works is >very clunky and I would appreciate some feedback and help improving it. > >http://www.hcsprogramming.com/downloads/index.html > Unless you know that the format of your files is more restricted than their types require, your criterion for finding a file reference is going to get spurious hits (of course the other side is you can't statically find strings that don't exist until run time either, when it comes to program sources). E.g., for HTML you could do a much better job by using the HTMLParser module. UIAM it also normalizes things to lower case for you, besides letting you skip commented-out references and similar character sequences in the data part. And since the parser makes it easy to get hrefs, you could split and check #-references and definitions too. The other files should really be parsed too, if you want to avoid spurious matches. As Emile pointed out, concatenating strings with '+' is relatively expensive, and one way of doing it more cheaply is to put the pieces in a list and later join them. You can do that in a style that looks similar to what you did, but is a lot more efficient. Note that strings separated by white space are concatenated by the compiler, and in a () or [] context that white space can include EOLs, so you can mix string fragments and expressions e.g., like this: >>> x= '' >>> a = [ ... '123' ... '456' ... '\n', x*2 , '\n' ... 'abc' ... 'def' ... ] >>> a ['123456\n', '', '\nabcdef'] Notice that 'a' wound up a list of _3_ strings here, and note the commas isolating the x*2 expression. >>> print ''.join(a) 123456 abcdef >>> a += ['\nYou can add this way too, for ', x[1:-1], '.'] >>> print ''.join(a) 123456 abcdef You can add this way too, for example. >>> a += [ ... '\nOr' ... ' this' ... ' way' ... '\n(noting that indent is ignored inside () or [].' ] >>> print ''.join(a) 123456 abcdef You can add this way too, for example. Or this way (noting that indent is ignored inside () or []. >>> Of course, you can arrange pieces to suit, but the point is that it needn't be expensive to write a mix of string fragments and expressions in a sequence, and you can lay it out in multiple lines of source without a += 'next string piece' expense at every line (noting that the similar looking a += ['a string ',foo(),' more'] is comparatively cheap). Triple quotes of course are good for defining lines without using '\n', and you can plug in pieces symbolically from a directory: >>> b = """

    %(bigText)s

    ... %(redText)s ... etc... ... """ >>> stuff = {'bigText':'Should be big', 'redText':'Should be red'} >>> b % stuff '

    Should be big

    \nShould be red\netc...\n' >>> print b % stuff

    Should be big

    Should be red etc... You can also use vars() in place of stuff to pick up symbols from the local or other dictionaries. You might also want to consider using dictionaries for some sets of things instead of lists. To enhance the directory walker, you could give it globbing and excluding and optional recursion controls. Perhaps make it a class meant to be subclassed like HTMLParse, feeding it glob strings and having it call convenient methods. BTW, I'd try to avoid useless re-computation, as in putting ".tolower()" on stuff that's already guaranteed lower case by previous code. And file = str(file) looks like a no-op in its context. Also, if you have a series of mutually exclusive if conditions, making the if's after the first into elif's will avoid executing tests after one succeeds. BTW2, all those .endswith() tests would succeed on file names without extensions but having the given suffix. You could fix it, but Emile's version avoids that by splitting on '.' so you gain two ways ;-) That enough for this go ;-) Regards, Bengt Richter From philh at comuno.freeserve.co.uk Wed Mar 6 19:31:57 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Thu, 7 Mar 2002 00:31:57 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 6 Mar 2002 11:37:17 -0700, Bjorn Pettersen wrote: >> From: David Eppstein [mailto:eppstein at ics.uci.edu] >> Subject: PEP 284, Integer for-loops > >Thanks for writing the PEP. > >I see this as a general proposal for a range syntax, and I disagree with >it because: > > - it doesn't handle the general range issues, i.e. step value, > and if we had to add yet another syntax to get general ranges > it would be too confusing. > > - I would like range objects to be first class, ie. I would want > to be able to pass ranges to functions, return them from > functions, and do all the other things one can do with first > class objects. This proposal only adds syntactic sugar to the > for loop. What is wrong with using the existing range() and xrange()? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From teyc at cognoware.com Wed Mar 20 22:12:33 2002 From: teyc at cognoware.com (Chui Tey) Date: 20 Mar 2002 19:12:33 -0800 Subject: win32process.CreateProcess inherit handles not working ? Message-ID: <9364c0c7.0203201912.1ba8fde6@posting.google.com> Hi, I've been trying to get this going for a while and I'd appreciate it if someone can point out what's wrong with the following test? It works fine on Win98 but fails on NT and W2K. I am using Python 2.1 # test.py # def setup(): open("slave.py","w").write(""" import sys while 1: line = sys.stdin.readline() if not line: break sys.stdout.write("read: %s" % line) """) open("slavein.txt","w").write(""" The Quick Brown Fox """) def test(): "Does the equivalent of C:\\python21\\python.exe slave.py < slavein.txt > slaveout.txt" _CreateProcess( \ "C:\\python21\\pythonw.exe", # app ['slave.py'], # args 'slavein.txt', # input file 'slaveout.txt') # output file if open('slaveout.txt','r').read() == "": print "Error: stdout not redirected!" def _CreateProcess(app, args, filein, fileout): """Returns the pid. app = executable name args = list of arguments filein = name of file to redirect to stdin fileout = name of file to redirect the stdout to """ import win32process import win32file import pywintypes import win32security import win32event import win32api u_filein = pywintypes.Unicode(filein) u_fileout = pywintypes.Unicode(fileout) SA_proc = win32security.SECURITY_ATTRIBUTES() SA_thrd = win32security.SECURITY_ATTRIBUTES() SA_proc.bInheritHandle = 1 SA_thrd.bInheritHandle = 1 #SA = None SI = win32process.GetStartupInfo() SI.dwFlags = win32process.STARTF_USESTDHANDLES hStdInput = win32file.CreateFile( u_filein, # filename win32file.GENERIC_READ, # mode win32file.FILE_SHARE_READ, # share SA_proc, # security attributes win32file.OPEN_EXISTING, # creation disposition win32file.FILE_ATTRIBUTE_NORMAL, # flags 0 # hTemplate file ) hStdOutput = win32file.CreateFile( u_fileout, # filename win32file.GENERIC_WRITE, # mode win32file.FILE_SHARE_WRITE, # share SA_proc, # security attributes win32file.CREATE_ALWAYS, # creation disposition win32file.FILE_ATTRIBUTE_NORMAL, # flags 0 # hTemplate file ) SI.hStdInput = SI.hStdInput SI.hStdOutput = SI.hStdOutput SI.hStdError = SI.hStdOutput cmdline = app + " " + " ".join(args) hProcess, hThread, pid, threadid = \ win32process.CreateProcess( app, # lpApplicationName cmdline, # command line SA_proc, # Process security attributes SA_thrd, # Thread security attributes 1, # Inherit handles win32process.DETACHED_PROCESS, # None, None, SI) win32event.WaitForSingleObject(hProcess, win32event.INFINITE) win32file.CloseHandle(hStdInput) win32file.CloseHandle(hStdOutput) return pid if __name__=="__main__": setup() test() From cs1spw at bath.ac.uk Tue Mar 5 08:15:32 2002 From: cs1spw at bath.ac.uk (Simon Willison) Date: Tue, 5 Mar 2002 13:15:32 GMT Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> <3c84c0d4_4@Usenet.com> Message-ID: <3C84C4F3.4090205@bath.ac.uk> marduk wrote: > You're better off using htmllib (and httplib for that matter). I haven't > looked at your examples, but I can tell just by looking at your code that > it will fail, for example, when "" and "" are on seperate > lines in the HTML. Also, I might be mistaken, but it doesn't look like > you are re search is case insensitive. > > Either way, try the htmllib. It takes care of all that stuff for you! I'd love to (mainly to avoid the averhead of running lynx about a hundred times) - unfortunately my University web server doesn't have the socket module properly installed which means nearly all of the web related python modules won't run :/ I'm willing to risk multi line titles not working for the moment (after all they are pretty rare and my script is only being used in a very limited capacity) - thanks for the tips though :) From jjb5 at cornell.edu Mon Mar 25 15:23:43 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Mon, 25 Mar 2002 15:23:43 -0500 Subject: New SIG on logic/CLP programming in Python Message-ID: I so boldly said "counter example" on Friday, and while that may have been misinterpreted as a counter example to forming a Logic-SIG, what I ment was that I had something to kick off a discussion. I propose to add a few keywords, hopefully I'll be using terms consistent with Prolog, but it's been a while, and other comments are welcome. First, add 'goal' to define goals, like functions: goal sibling(X,Y): parent(Z,X) parent(Z,Y) A goal looks like a function call in the code. adam, betsy, clide, dave, edith = range(5) assert(parent(adam, clide)) # needs help... assert(parent(adam, dave)) def test1(): print "Ah!" sibling(clide, dave) print "Yes!" >>> test1() Ah! Yes! Then add 'cut' and 'fail' as statements: def test2(): sibling(clide,X) print X cut print "-cut-" fail >>> test2() 3 -cut- Without the cut statement the output would look like this, because clide is considered a sibling of himself: def test3(): sibling(clide,X) print X fail >>> test3() 3 2 Unlike Python functions, the same goal could be defined more than one way: goal sibling(X,Y): mom(Z,X) mom(Z,Y) goal sibling(X,Y): dad(Z,X) dad(Z,Y) With my limited Python experience I get the impression that the variable '_' is frowned upon, so I would replace it with the keyword 'Any'. goal isachild(X): parent(Any,X) Goals can return values, so they can be used like functions: goal sibling2(X,Y): parent(Z,X) parent(Z,Y) return Z def test4(): p = sibling2(clide,dave) print p >>> test4() 0 Almost every Prolog book has an example of list membership, but while the slicing operation can be done simply in Prolog: member(X,[X|_]). member(X,[_|Y]) :- member(X,Y). The same kind of thing doesn't seem to fit Python: goal member(X,[X|_]): pass So it would have to be done with a some statements: goal member(X,L): if (len(x) == 0): fail if (X != L[0]): fail goal member(X,L): member(X,L[1:]) Comments? Joel From peter at engcorp.com Sun Mar 24 17:37:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 17:37:57 -0500 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> <3C9E2D31.E45278BC@engcorp.com> Message-ID: <3C9E5545.A16972EC@engcorp.com> holger at trillke.net wrote: > > > > Peter Hansen wrote: > > I'm curious what the agent actually does if it doesn't share > > anything. Does it not take input? And produce output? > > No opening files, accessing Queues and such? If it does > > any of those things, wouldn't that make it potentially a > > problem if you killed it? > > Well. my agents share a namespace (named share:-) through which they > can get to one another. So you can guarantee that the way they interact is through carefully controlled interfaces which are still completely safe even in the face of asynchronous and unexpected thread termination? > You don't neccessarily need to brutally kill the thread without > the running code in that thread to notice it. Something like this > would be nice: > > def run(self): # thread's run > try: > while something: > do_something() > except ThreadInterruptException,e: > niceley_free_locked_resources_or_such() Well, if you're willing to do that, things become much easier, perhaps. It sounds like you have your threads talking together or to a management thread in a controlled fashion, through the safe interfaces I mentioned above. If that's the case, why not just have those low-level routines check for a thread termination flag and "raise ThreadInterruptException" if they see it? Technically voluntary on the part of the thread, but then it was supposed to be cooperating, right? I've done this in one system by modifying 'threading' to have a flag in each thread, and in several low-level routines I check for that flag and throw an exception if I see it. Threads have always executed cleanly and cleaned up after themselves. In the cases where threads are actually blocking in operating system calls (reading from serial ports, in my case), I contrived to make sure they always have reasonably short timeouts (several seconds) so they would always check for thread termination often enough. It all depends how much control you have over the environment. -Peter From cliechti at gmx.net Tue Mar 19 15:12:59 2002 From: cliechti at gmx.net (Chris Liechti) Date: 19 Mar 2002 21:12:59 +0100 Subject: Serial Ports References: <3c96c220$1_1@news.iprimus.com.au> Message-ID: "Jamie Carl" wrote in news:3c96c220$1_1 at news.iprimus.com.au: > point in the right direction regarding how I would go about > accessing a serial com port from Python. I'd like to do it mainly > under Linux, but hopefully it will work under windows aswell. i have a lib here: http://pyserial.sf.net chris -- Chris From bokr at oz.net Thu Mar 28 13:50:03 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Mar 2002 18:50:03 GMT Subject: Extending/embedding versus separation References: Message-ID: On Thu, 28 Mar 2002 11:12:09 -0000, "skoria" wrote: >Hi > >Thanks for your help. No, I didn't write the hash tables. I'm writing >a stats program based on webalizer. Webalizer and Analog were the >fastest and least memory hungry of all the programs I know of, and >webalizer is GPL so I was able to use it as a basis for my work, so I >get to make free software at work! The hash tables are already written >there. > >This program is intended to run on all the sites hosted by the company >I work for, and also on sites not hosted by it, hence the memory/disk >space concerns. > >The way I see it, the python side of things will be a python script >that imports the C parts, and can therefore process the logfiles and >turn them into hash tables. These are then fed back to the python >part, which processes them further, and turns them into graphs and html. > >The reason for this is I need to be able to quickly develop and expand >on the reports produced, so we can do complicated things like, say, >visitor paths or percentage increase graphs. > OTTOMH, I would guess that you may need to generate some special representations of visitor paths directly from the logs, unless the webalizer already does that. But if you have to process the raw logs in a new way, it will most likely be easier to get right in Python than by cannibalizing existing C. I'd make sure the raw logs contain the data you actually need for your purposes. Hashes are easy in python. E.g., here is a tiny example counting hits on my little private net (this is done on the server, which is an old P90 with 48mb ram and a slow pio disk, running slackware linux and apache). Then I ran the same thing on NT4 P2 300mhz with 320mb ram, which is not a real screamer these days, but went 10x faster ;-): Also the python on the slackware box is 1.5.2 vs 2.2 on NT, so I used only 1.5.2 features (something to consider). =======< snip >========= ~/misc$ cat hosthits.py #!/usr/bin/python import string, sys, time tstart = time.clock() f = open(sys.argv[1]) d = {} while 1: host = string.split(f.readline(),' ',1)[0] if not host: break if d.has_key(host): d[host] = d[host] + 1 else: d[host] = 1 it = d.items() it.sort() hits = 0 for k,v in it: hits = hits + v print '%6d hits came from %s' % (v,k) print '------\n%6d total hits.' % hits print '\nTotal time: ', time.clock()-tstart ~/misc$ v /var/log/access_log -rw-r--r-- 1 root root 1699460 Mar 28 11:00 /var/log/access_log ~/misc$ python hosthits.py /var/log/access_log 1913 hits came from 192.168.1.100 15240 hits came from 192.168.2.1 6 hits came from 192.168.2.3 ------ 17159 total hits. Total time: 13.83 =======< snip >========= [10:42] C:\pywk\misc>python hosthits.py access_log 1912 hits came from 192.168.1.100 15240 hits came from 192.168.2.1 6 hits came from 192.168.2.3 ------ 17158 total hits. Total time: 1.2641499788 About 10x faster, and about 13,500 log lines/sec. Recent boxes are a good bit faster yet. So if you have any kind of recent computer, you can crunch logs pretty easily. For prototyping, I'd say don't worry about any C advantage in hashing. Python does the actual hash work in C anyway. >As I see it now, the only difference I get if extending python with my >adapted webalizer, is that I save writing a little output to file and >parsing it into python again. > >Is this going to be worthwhile? > A lot depends on what you are fluent in doing. But it may be less work re-doing some parsing/hash-generation in python than capturing some C stuff via extensions -- and then having to do custom processing of the raw logs anyway (if you forsee that). My bet is you'd be better off doing the whole thing in Python, and then worrying about optimizing. IOW, I second John's advice. Regards, Bengt Richter From lac at strakt.com Mon Mar 4 06:48:55 2002 From: lac at strakt.com (Laura Creighton) Date: Mon, 04 Mar 2002 12:48:55 +0100 Subject: Brewster's Factor - was :Trouble running programs In-Reply-To: Message from Bernard Yue of "Sun, 03 Mar 2002 20:33:09 GMT." Message-ID: <200203041148.g24BmttB007592@ratthing-b246.strakt.com> > Bernard Yue's sig is: > > There are three schools of magic. One: State a tautology, then ring > the changes on its corollaries; that's philosophy. Two: Record many > facts. Try to find a pattern. Then make a wrong guess at the next > fact; that's science. Three: Be aware that you live in a malevolent > Universe controlled by Murphy's Law, sometimes offset by Brewster's > Factor; that's engineering. > > So far as I can remember, there is not one word in the Gospels in > praise of intelligence. > -- Bertrand Russell I wanted to know what Brewster's Factor was. I found out that the first part of the quote -- the bit that ends with Engineering should be attributed to Robert A. Heinlein (from The Number of the Beast). But the only Brewster Factors I can find have to do with polarised light, or English Chrisitian Revivalist Victorian political parties, neither of which I suspect is what I am looking for. Any ideas? Laura Creighton From quinn at barf.ugcs.caltech.edu Fri Mar 1 15:51:56 2002 From: quinn at barf.ugcs.caltech.edu (Quinn Dunkan) Date: 1 Mar 2002 20:51:56 GMT Subject: Minor, minor style question References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: On Fri, 1 Mar 2002 11:05:41 -0800, Emile van Sebille wrote: >claird at starbase.neosoft.com (Cameron Laird) writes: > >> Why would I prefer >> string = "" >> string = string + "abc " >> string = string + "def " >> string = string + "xyz" >> over >> string = "abc " + \ >> "def " + \ >> "xyz" >> ? > >Isn't the question about line continuations? I don't use them (except >on rare occasions), preferring to do something more like: > >string = ('abc' + > 'def' + > 'xzy') Or, if they are all string constants: string = ('abc' 'dev' 'xyz') From nas at python.ca Sun Mar 17 17:48:59 2002 From: nas at python.ca (Neil Schemenauer) Date: Sun, 17 Mar 2002 14:48:59 -0800 Subject: Eliminate Spam Now... >g< Python w/DNS/&POP3 In-Reply-To: ; from junkster@rochester.rr.com on Sun, Mar 17, 2002 at 09:56:15PM +0000 References: Message-ID: <20020317144859.B18963@glacier.arctrix.com> You don't need DNSlib. socket.gethostbyname() works fine. Check out my spamhunter script? for example code. Neil ? http://arctrix.com/nas/python/spamhunter.py From peter at engcorp.com Sun Mar 24 23:20:42 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 23:20:42 -0500 Subject: Debugging on windows via print statements -- reliable? References: Message-ID: <3C9EA59A.D3F76D2F@engcorp.com> Nick Arnett wrote: > > As I try to track down why my code is getting stuck (in a situation where it > could take ages to step through in the debugger), I'm using print statements > so that I can see where it's just been before it freezes. Trouble is, I'm > not seeing much consistency in when (how many iterations) or where (in the > code) it stops responding. > > Now I'm wondering if way of creating signposts is reliable. Is it possible > that it's actually hanging up somewhere without actually outputting some of > my print statements, even though they've been processed? Sometimes, I'm > only getting part of the output of a print statement, which seems truly > weird. If I had multiple threads, perhaps I could be clobbering the thread > that's printing my signposts, but I'm not... > > Is there something on Windows (Win2K, to be exact) that I need to do to make > sure that print statements are actually output as soon as the statement is > executed. > > Thanks in advance... I don't recall if print flushes its output after each call, but if you want to be certain it does, try calling sys.stdout.flush() after your print calls. This is a console app, right?, and you aren't redirecting the output to a file? By the way, how can Python code get "stuck"? Is it a logic flaw, or are you talking about the kind of "stuck" that used to happen, in the "old days", when we were always writing code in languages which would actually crash the computer? -Peter From mickey at tm.informatik.uni-frankfurt.de Sat Mar 2 18:45:44 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 3 Mar 2002 01:45:44 +0200 Subject: PEP 234 little bug? Message-ID: <3c817238@nntp.server.uni-frankfurt.de> Just read through some of the already implemented PEPs. PEP 234 (iterators) states: > - It has been proposed that a file object should be its own > iterator, with a next() method returning the next line. This > has certain advantages, and makes it even clearer that this > iterator is destructive. The disadvantage is that this would > make it even more painful to implement the "sticky > StopIteration" feature proposed in the previous bullet. > > Resolution: this has been implemented. I can't see a next() in a file object. Shouldn't it be "Resolution: this has not been implemented." ? Yours, :M: From writeson at earthlink.net Sun Mar 3 18:26:24 2002 From: writeson at earthlink.net (Doug Farrell) Date: Sun, 03 Mar 2002 23:26:24 GMT Subject: Text Search Engine that works with Python Message-ID: Hi all, I'm wondering if anyone knows of a text search engine that works with Python? What I'm looking for specifically is something that will compress the text and still allow searches and retrievals that can be exact matches or proximity based. The text I want to compress and search is huge (70 megs) and should compress down to half, not including any index files that might be required by the search engine. Anyone know of anything like this or any ideas? Thanks, Doug Farrell From offer at sgi.com Mon Mar 25 16:36:39 2002 From: offer at sgi.com (Nhi Vanye) Date: 25 Mar 2002 21:36:39 GMT Subject: Porting a Python app to IRIX -- need help References: Message-ID: $ from hgg9140 at seanet.com -#190195 | sed "1,$s/^/> /" > > >But now that we are moving to n32, we are using gcc (which only knows >n32). gcc is better for some open source libraries and applications. > CC='gcc' The only problem with gcc is: 1) its not as optmised as MIPS Pro 2) its name mangling algorithm is different if you start using C++ libraries. >Harry George >hgg9140 at seanet.com richard. -- Richard Offer Technical Lead, Trust Technology. "Specialization is for insects" __________________________________________http://reality.sgi.com/offer/ From tim.one at comcast.net Mon Mar 11 18:06:19 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 11 Mar 2002 18:06:19 -0500 Subject: Using doctest and executing a process In-Reply-To: <10d46bdc.0203111449.6bd761f5@posting.google.com> Message-ID: [Douglas Garstang] > I'm trying to integrate execution of an external process output into > doctest. > > The following snippet of code: > > def tester3(): > """ > >>> import os > >>> os.system ('/bin/ls') > example.py example.pyc tester.py > 0 > """ > > produces this output: > > (dougg at ultra5-4:)%python example.py > example.py example.pyc tester.py > ***************************************************************** > Failure in example: os.system ('/bin/ls') > from line #2 of example.tester3 > Expected: > example.py example.pyc tester.py > 0 > Got: 0 > ***************************************************************** > 1 items had failures: > 1 of 2 in example.tester3 > ***Test Failed*** 1 failures. > > WHY? doctest captures output written to Python's sys.stdout. /bin/ls doesn't know anything about Python's sys.stdout, and Python's sys.stdout doesn't know anything about /bin/ls . > ... > Where did the other output from the external program go? Probably to your terminal. You may have better luck with, e.g. >>> os.open('/bin/ls').read() That gives Python a chance to capture the output /bin/ls sends to *its* idea of "stdout", and then echoes it back to Python's sys.stdout. From spacedweller at hotmail.com Thu Mar 14 23:05:40 2002 From: spacedweller at hotmail.com (j45729) Date: Fri, 15 Mar 2002 04:05:40 -0000 Subject: hey everyone!! Message-ID: hey everyone!! i don't know what to say...PYTHON ROCKS!! its so much fun it really is a fun language... From greg at cosc.canterbury.ac.nz Sun Mar 3 19:15:41 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 04 Mar 2002 13:15:41 +1300 Subject: Status of PEP's? References: Message-ID: <3C82BCAD.945EEA78@cosc.canterbury.ac.nz> James_Althoff at i2.com wrote: > > if I want to iterate up (smaller up to larger) I need to > write the for-loop as > for smaller <= i <= larger: # can *only* iterate up > but if I want to iterate down (larger down to smaller) I need to write the > for-loop with the reverse relational operators > for larger >= i >= smaller: # can *only* iterate down Sorry, I missed that you wanted the order of iteration to be variable. You're right, but I don't see that as a major disadvantage. The vast majority of all for-loops over integers that I write have a fixed iteration order. In the rare cases that I wanted otherwise, I'd be quite happy to write the loop another way. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From niemeyer at conectiva.com Sun Mar 24 03:44:49 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Sun, 24 Mar 2002 05:44:49 -0300 Subject: [rp] [newbie] embedding python In-Reply-To: References: Message-ID: <20020324054449.A22366@ibook.distro.conectiva> > i have a python script "file.py" which has a function in it which i > need to call from my c code. how can i do this! all my projects have > been postponded becuase i cant do this! please helP! i would be so > grateful!! Hummm.. I'm not sure... how grateful? ;-)) > ultimately im trying to embed some python into my c source in UNIX. > i have absoutely no idea how to do this despite the tutorial on the web at > http://www.python.org/doc/current/ext/building-on-unix.html#building-on-unix I don't think this page will be helpful. You should probably be looking at http://www.python.org/doc/current/ext/embedding.html > it's too general and not step by step enough for a noob like me :( The best way to learn is to look at existent code, and use in your benefit the fact that you have the python source in your hands. Looking at google for "embedding python" will be helpful as well. Here is an URL I got in the first page: http://www.mcmillan-inc.com/embed.html -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From jcromwell at ciena.com Fri Mar 15 15:20:57 2002 From: jcromwell at ciena.com (Cromwell, Jeremy) Date: Fri, 15 Mar 2002 12:20:57 -0800 Subject: unittest.py: what is TestResult.__repr__ ? Message-ID: >From the Python Reference Manual: Section 3.3.1 Basic customization __repr__(self) Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. >From the Python Library Reference: Section 2.1 Built-in Functions repr(object) Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(). -Jeremy Cromwell, today's language lawyer -----Original Message----- From: quadzero at users.sourceforge.net [mailto:quadzero at users.sourceforge.net] Sent: Friday, March 15, 2002 11:41 AM To: python-list at python.org Subject: unittest.py: what is TestResult.__repr__ ? I'm not a Python programmer (at least, not yet ;) I am, however, trying to port the unittest.py framework to another language. Of all the languages that this testing framework has been ported to, I thought that Python would be the easiest for me to decipher. For the most part, it seems pretty straightforward, except for... I'm presently stuck in the TestResult class. Though I've searched for the meaning of "__repr__" in the Python22 documentation, I cannot find it. Please help me understand this this convention of using leading and/or trailing underscores in Python. Thanks in advance... Richard -- http://mail.python.org/mailman/listinfo/python-list From bradley.s.gaspard at saic.com Tue Mar 19 12:17:31 2002 From: bradley.s.gaspard at saic.com (Brad Gaspard) Date: Tue, 19 Mar 2002 12:17:31 -0500 Subject: Returning an element from a C struct Message-ID: <3C9772AB.1691D362@saic.com> I'm trying to wrap a C structure in a Python class definition and have come upon this problem. class foo: __init__(self, dat): self.ptr = gnum_t(dat) # initializes the C struct and returns a pointer __getattr__(self,name): try: return self.__dict__[name] except: if name == 'A': return self.__dict__['ptr'].A elif name == 'B': return self.__dict__['ptr'].B elif name == 'C': return self.__dict__['ptr'].C # And many others } I know there has to be an easier way to do this?? Thanks in advance. Brad From evebill8 at hotmail.com Sun Mar 17 13:10:15 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Sun, 17 Mar 2002 18:10:15 GMT Subject: time out socket References: Message-ID: Thanks Martin, Good info! Billy "Martin von Loewis" wrote in message news:j4pu235b3c.fsf at informatik.hu-berlin.de... > "Billy Ng" writes: > > > Would anybody please tell me how time out the socket.connect() if > > the host does not exists or is unable to connect, thanks! > > The connect call will time out eventually on its own, after the > operating system's timeout has passed. > > If you want to shorten the timeout, and you have a Posixish system, > you can set an alarm using signal.alarm. Make sure you install a > signal handler; it does not need to do anything since the connect will > raise EINTR. > > Regards, > Martin > > From edream at tds.net Sat Mar 2 13:13:40 2002 From: edream at tds.net (Edward K. Ream) Date: Sat, 02 Mar 2002 18:13:40 GMT Subject: C/C++ to Python translater References: <5e8bd451.0203011049.5d12d3a2@posting.google.com> Message-ID: <3C811653.871C5BEF@tds.net> kevin parks wrote: > > Is there a translator to automatically port (rewrite) code snippets > from C or C++ to Python? leo.py contains a script called c2py.py that I have used to translate all my C++ code to Python. It does about 80% of the work and is mostly intended to be run from inside Leo. IIRC there is another entry in c2py.py script to translate "exterior" files and this can be run from idle, say. Munging source to Python is actually remarkably easy to do. You can download leo.py v1.0 at: http://sourceforge.net/project/showfiles.php?group_id=3458 One of these days I'll get around to cleaning it up and making a proper distribution of it. Let me know if you have problems with c2py: it will help me clean up the rough edges. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From andy at reportlab.com Fri Mar 8 11:53:05 2002 From: andy at reportlab.com (Andy Robinson) Date: Fri, 08 Mar 2002 16:53:05 GMT Subject: Autodiscovery of proxy settings from a python script Message-ID: A firm we are working with want to demonstrate some Python web services software, which will connect from a windows desktop to a known server on the internet. It is a safe bet that the demos will be given behind firewalls, but that the customers will be able to browse the web from either IE or Netscape. The problem is that both the guys giving the demos and the potential customers will not be very technical, and saying "what's your proxy server settings" will likely spark fear, paralysis and wasted visits :-) If they have a locked down IE distribution, the settings will just say "auto detect" and the salesman won't be wiser. Ideally I'd like a script that knew where IE and Netscape and a few other packages kept their proxy settings, and also know about the most common auto-discovery protocols. It could try various things in succession until it made a comnnection, or gave up and asked. The salesmen could email a small program to the client and say "try this" ahead of time and would at least know what to expect. We're already committed to installing python and COM so can use just about any tools needed. Has anyone done this before? Any suggestions how to go about it? Best regards, Andy Robinson ReportLab Inc. From tchur at optushome.com.au Tue Mar 12 05:27:25 2002 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 12 Mar 2002 21:27:25 +1100 Subject: Has Mark Hammond attained pariah status yet? References: <31575A892FF6D1118F5800600846864DCBCDD1@intrepid> Message-ID: <3C8DD80D.F682FE0F@optushome.com.au> Simon Brunning wrote: > > > From: Tim Churches [SMTP:tchur at optushome.com.au] > > > > So asks an article on Mark in the IT section of today's Sydney Morning > > Herald - see > > http://www.it.mycareer.com.au/news/2002/03/12/FFXMFP3LOYC.html > > Not with those of us who use the Win32all package which he has so generously > donated to the community, no. Yes, indeed. > > I-know-you-were-joking-but-a--wouldn't-have-been-out-of-place-ly y'rs, Hey, I was only quoting the (somewhat sensationalist) headline from the newspaper story... Tim C > Simon Brunning > sbrunning at fuckmicrosoft.com I suppose we all have to get our jollies somehow... From hfoffani at yahoo.com Sun Mar 24 08:18:26 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Sun, 24 Mar 2002 14:18:26 +0100 Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> <11e94203.0203232201.4dde9883@posting.google.com> Message-ID: <20020324081829.193$iP@news.newsreader.com> "Jose Rivera" escribi? > The URL calculated : > > http://avisos.elnorte.com/casa_venta_result.asp?fotos=0&Order=order+by+colo nia&Precio_i=-1&Presentacion=Tabla&Precio_f=-1&PLANTAS=0&pagina=1&id_inmueb le=3&dia=&RECAMARAS=0&constr_f=-1&COLONIA=0&BANOS=0&Tipo=CASAS&Constr_i=-1& Terreno_i=-1&Terreno_f=-1&zona=0 > > works on my PC, try it, and let's see whats wrong. That page uses DHTML a lot. urlopen works as expected, you get the same result if you use IE with max security for avisos.elnorte.com You want to fix this problem first studying the html source of the page deeply. > Does anyone have an idea of how I can save it to a DataBase? Polish the page with HTML Tidy first, then strip all script code tags, parse the resulting HTML to catch the rows you're interested in and save them into a DB. > Is there a better way? A better way of what? I missed the original post. Regards, -Hernan From theller at python.net Fri Mar 1 07:54:28 2002 From: theller at python.net (Thomas Heller) Date: Fri, 1 Mar 2002 13:54:28 +0100 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7F6765.94A82394@engcorp.com> Message-ID: "Robin Becker" wrote in message news:gS1JDJAdy2f8EwUF at jessikat.demon.co.uk... > In article <3C7F6765.94A82394 at engcorp.com>, Peter Hansen > writes > ..... > > > >I'm pretty sure the last time I checked the PROGRA~1 convention still > >worked on WinNT. Are you sure this doesn't work on Win2K as well? > >They're supposed to be the same thing, no? > > > >-Peter > I'm sure it does and I guess that Program Files will always match as > it's often the first. On the other hand working with a path name > obtained from an execution path there's no guarantee I can always do the > correct conversion by assuming ~1, some end up as ~2 etc. > > Is there a proper way to get the 8.3 name? >>> import win32api >>> win32api.FindFiles(r"c:\Program Files") [(49, , , , 0, 0, 100, 1244528, ' Program Files', 'PROGRA~1')] >>> win32api.FindFiles(r"c:\Program Files")[0][-1] 'PROGRA~1' Thomas From sholden at holdenweb.com Mon Mar 4 10:39:47 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 4 Mar 2002 10:39:47 -0500 Subject: is their any limit on the size of the data passed to a progra m via popen2? References: <3C77AE2E.3020301@student.kun.nl> Message-ID: <1yMg8.308697$n73.10333528@atlpnn01.usenetserver.com> "husam" wrote in message news:3C77AE2E.3020301 at student.kun.nl... > Gustavo Cordova wrote: > > > That doing a read() on pipes hangs, so you have to > > define a timeout or something, so that you can take > > control back. > > > > But I dinnae kno how ta do such a thang. > > > > :-/ > > > > -gus > > > > pd: I *think* it was jeff. > > > > > > Ya, I red that one. But, now the problem is that running the code > succefully really depends on the number of the files passed to the > application in one "popen2" session. I found that the number of the > files must not exceed 250. I worked around this by splitting the 10000 > files into 50 lists each of them contains 200 files and for each list > opening a "popen2" session and close it at the end in a "for" loop. Now > the code works fine. I have searched the internet for informations > related to the size of the pipe and how to modify it, but I found > nothing except "select.select()". At the moment I really don't have time > to implement this. > > any way, thanks for the contribution. > I'm coming in to this conversation a little late, but is there a possibilty that you could actually transmit the contents of multiple files via a single stream, allowing you to feed files into the popen()'d subprocesses as each consumes input? This might save a lot a process- and file-creation overhead if all you really need is the computaional output. You might use a netstring representation, for example. Even if all the above is true, don't be surprised to hit hard limits on other annoying resources like threads-per-process or processes per subgroup. That "250", by they way? Might it be 254 or 255, really? Or possibly (255-number of other command line arguments)? This would be a typical result of some element of the pipeline limiting the length of the argument vector so a byte could be used to select each element. So, you are probably the victim of thoughtless design, or of some historical features of the code you use. Even so there are always limitations, whether it's long arithmetic slowdown or inappropriate representation, and TheOnlyWayForward is to MercilesslyRefactor. Every environment has limits, and sometimes it's a question of learning what limits you can live with. Onward and downward, as the Pascal standardization committee might have declared. wondering-what-happened-to-tony-addyman-ly y'rs - steve -- Consulting, training, speaking: http://www.holdenweb.com/ Author, Python Web Programming: http://pydish.holdenweb.com/pwp/ "This is Python. We don't care much about theory, except where it intersects with useful practice." Aahz Maruch on c.l.py From niemeyer at conectiva.com Wed Mar 20 09:27:50 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Wed, 20 Mar 2002 11:27:50 -0300 Subject: Develop-test-debug cycle In-Reply-To: References: Message-ID: <20020320112750.A1368@ibook.distro.conectiva> Hi Dale! [...] > import sys > sys.path.append("x:\\whereever") > from wibbleModule import wibble > wibs = wibble(args) You could save this in a file and execute it with "python -i file.py". [...] > Now, I haven't figured out a way of continueing past this point > without quiting and starting from scratch because there appears to be > no way to get Python to reload a module. The reload() function doesn't > do it. It seems to work here: [niemeyer at ibook niemeyer]$ echo 'a = 1' > mod.py >>> import mod >>> mod.a 1 [niemeyer at ibook niemeyer]$ echo 'a = 2' > mod.py >>> reload(mod) >>> mod.a 2 > How do others go about interactively debugging large Python OO-based > systems? Have you looked at pdb? -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From thomas at gatsoft.no Fri Mar 15 09:33:19 2002 From: thomas at gatsoft.no (Thomas Weholt) Date: Fri, 15 Mar 2002 14:33:19 GMT Subject: Connecting to a Gnutella-network Message-ID: Hi, I've looked at the Gnutella Protocol, v.0.4, and wondered about trying to create an implementation in python. I'm a newbie when it comes to this sort of thing, but have created several simple to complex server types of applications using SocketServer and its friends like BaseHTTPServer etc. Has anybody tried to do this before? Does anybody have pointers for newbies like me in such a project ( how to start, how to connect to nodes on a gnutella network etc. ) I'll be glad for any pointers you might have. Best regards, Thomas From eppstein at ics.uci.edu Wed Mar 13 12:46:45 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 13 Mar 2002 09:46:45 -0800 Subject: Why I think range is a wart. References: <873cz44ea8.fsf@bunty.ruud.org> Message-ID: In article <873cz44ea8.fsf at bunty.ruud.org>, ruud de rooij <*@spam.ruud.org> wrote: > perhaps lists should support .keys() and .items() for those operations > (analogous to dictionaries). Perhaps we should use for (i,x) in list.iteritems(): ... (analogous to dictionaries) instead of PEP 279's indexed(list). -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From jlh at cox.net Wed Mar 6 23:56:23 2002 From: jlh at cox.net (Jeff Hinrichs) Date: Thu, 07 Mar 2002 04:56:23 GMT Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: "Geoff Gerrietts" wrote in message news:mailman.1015473913.28082.python-list at python.org... [...snip..] > Maybe a slight switch in topic: if the logical constructs are > disorienting, how would we approach instruction? Hello World seems to > go okay, right? (Do we have anything like a consensus from this?) But > then where do we go? More examples? With respect to teaching in python.... After Hello World would be Echo. Echo is simply a single iteration of raw_input then print. Now the student interact with their code. Teaching has always gone from Hello to If/Then the true amazement of computers for pristine newbies is interaction. So Echo.py would be the next step and one that would be built on for a few iterations as control structures and type conversion and formatting were introduced. At every step an example that interacts with the user is presented. Next would be an example This.py. The concept of the If/then statement is presented. Else is ignored for now. The program would echo input that matched the If statement otherwise it would output nothing. and so on... > I'm not sure what my goal is here, but it seems like we started with > an idea on how we could make computer programming more accessible for > everyone, including those whose relationship with logical thought can > only be described as "dysfunctional", but starting with those who are > at least making occassional sallies at the task of learning. > So where do we go next? If not "if", then what? Or do we go ahead with > "if" and "else", but abuse it with lots of examples? > Looking back at the pieces of pedagogical literature I've been exposed > to, I'm led to believe that learning (at least in children) occurs in > response to encountered frustrations with the limits of the current > knowledge base. Can we assemble something that looks like a cooked > series of examples or sample problems that exploit this? I think that we can, if we start by jumping from Hello World to another equally simple example such as Echo. I've suggested a beginning. It should introduce only one or two new things at a time. Always looking to "shy away" from exceptions. The concept of over-generalization that can be refined as the examples progress. Would you be interested in pursuing this further? > --G. > > -- > Geoff Gerrietts > I AM YOUR KING! BOW BEFORE ME, PEASANT! -- Dogbert > From cliechti at gmx.net Sun Mar 31 17:11:50 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Mar 2002 23:11:50 +0100 Subject: Replace high-bit characters in file. References: Message-ID: "Mikke M." wrote in news:M1Kp8.3021$Ow4.4334 at news2.bredband.com: > I need a script that replaces national characters in a (dBase)file. > > The original file is encoded in Latin-1 but I need it to be in CP850 > instead. you can do that with the unicode support: >>> unicode("text to convert","latin-1").encode("cp850") chris -- Chris From phr-n2002a at nightsong.com Mon Mar 4 04:38:18 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 01:38:18 -0800 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: <7xy9h8pt9x.fsf@ruckus.brouhaha.com> Tim Peters writes: > A lot of this speculation should have been cut short by my first msg. > > Yes, something changed in 2.2; follow the referenced link: > > http://sf.net/tracker/?group_id=5470&atid=105470&func=detail&aid=496104 > > For the rest of it, it looks like the "1e-200**2 raises OverflowError" > glitch is unique to platforms using glibc. What isn't clear is whether it's > dependent on which version of glibc, or on whether Python is linked > with -lieee, or both. I get the OverflowError under Red Hat 7.2 with the default Python 2.2 build, which appears to not use -lieee. The configure script's test for __fpu_control in -lieee appears to never be run when you type "configure". I manually put "-lieee" into the LIBS=... line in the makefile and rebuilt. Now I get: [phr at localhost Python-2-2]$ ./python Python 2.2 (#2, Mar 4 2002, 01:31:37) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 so the behavior changes with -lieee. > Unfortunately, the C standard (neither one) isn't a lick of help here -- > error reporting from C math functions is a x-platform crapshoot. That seems to me to be a deficiency in the C standard--IEEE 754 defines these different error modes because they're all important, and any high level language that claims to be good for serious numerics should give precise control over the error modes. From eppstein at ics.uci.edu Mon Mar 4 21:17:03 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 04 Mar 2002 18:17:03 -0800 Subject: Status of PEP's? References: Message-ID: In article , James_Althoff at i2.com wrote: > [David Eppstein] > > The proposal is to extend it to > > also include three-way comparisons. > > And, I assume, you mean three-way comparisons that are restricted to using > certain combinations of "< <= > =>"? Yes. Both comparisons must be in ["<", "<="], or both comparisons must be in [">", ">="]. From jimd at vega.starshine.org Tue Mar 26 02:08:35 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 26 Mar 2002 07:08:35 GMT Subject: Python, CGI and PGP References: <3c9fbf57@peer1.news.newnet.co.uk> Message-ID: In article <3c9fbf57 at peer1.news.newnet.co.uk>, Phil Edwards wrote: > I'm trying to get a CGI app working that is supposed to be able to produce > PGP signed messages. The command line equivalent of what I'm trying to do > in the CGI script would be: > /usr/local/bin/pgp -z mypassphrase -sta -f < /tmp/sometext.txt > > /tmp/sometext.pgp 2>/dev/null > This works fine both at the CLI and in a bash script, and produces a text > file with the '-----BEGIN PGP SIGNED MESSAGE-----' stuff at the top and the > PGP signature stuff at the bottom. > My recent attempts at getting this to work in the CGI script have been to > simply run the same command as above, but using either command.getoutput or > os.system from within Python. Doing this, I get the PGP signature block > that I would normally expect to see at the end of the message, but nothing > else. I suspect that the problem is down to the different execution > environment which PGP sees when it's being run within my CGI script, but > I've not been able to find anything in the PGP docs that has helped. > I've done some research into this on the 'net, but I haven't been able to > find any recent references to PGP usage within Python. Some guys were > prototyping a PGP interface for Python 1.2 back in 1995, but there doesn't > seem to have been any further work done since then. Is there currently a > PGP module available anywhere? If not, can anybody point me in the > direction of a site that is using PGP and Python? > FYI, my version of Python is 2.1, and my PGP version is 2.6.3 (don't ask - > just don't, that's all...you'll just start me thinking about it all over > again, and I'll probably start to hyperventilate...) > Phil Edwards How are you feeding "sometext.txt" into the process in your CGI script? Why now show us the actual fragment of code that you're attempting to use? When it comes to environmental issues (in programming) it's generally pretty easy to replace a target program with a wrapper script like so: mv $ORIGINAL_BINARY $ORGINAL_BINARY.wrapped cat > $ORIGINAL_BINARY < /tmp/$(basename $0).$$ . /some/where/$(basename $0).env exec $0.wrapped "$@" WRAPPER_SCRIPT chmod +x $ORIGINAL_BINARY ... this shell code is relatively terse (as well as concise) so I'll highlight some of it's finer points in english. Rename the original binary (pgp in your case) to add a ".wrapped" extension (or whatever). Put a new shell script in its place. The shell script will print the environment in which it is running into a temporary file (in this case a file named after the original binary with a PID (process ID number) as its extension). Then the script will "source" (read-in and execute, as in the shell's equivalent of #include) another script from "/some/where/", that will have an environment that you've capture from a manual CLI execution, and reformatted slightly as appropriate. Be sure to add "export" commands to each of the shell variables that you have listed in ... whatever.env). Finally you're wrapper script can exec the original (wrapped) binary with the original argument list. Note that "$@" is a magic psuedo-variable in descendents of the Bourne shell (including bash, ksh and zsh) that will include all of the positional argument in such a way that the original argument separation (usually done with quoting and \ escaping) will be preserved). It must be spelled exactly as shown (double-quote, dollar sign, at sign, double-quote) in order to have these properties. Note also that the $(...) command substitution syntax might not be recognized by some ancient versions of the Bourne shell; Heck! the "$@" might not work in some very old versions of sh --- though they both work in ash, which is about the most minimal modern Bourne shell). It should be obvious that you can do other almost arbitrary debugging work in this script. For example you could cat your input to a temp file (from a CGI POST) and end your script with an exec that would redirect from that input file; or you could have your script do a "while ! [ -f "/tmp/pauseflag.$$" ]; do sleep 1; done to allow you to set up an strace (Linux system call tracer) to watch it (with the -p PID option). (Basically it would allow you to have the program "pause" until you could attach a trace utility to it; then you'd touch the flag file and see what it was doing afterwards). Alternatively you might exec an strace -o .... program If you are reasonably persistent and a little clever you should be able to track down any problem that could be in your process environment using these techniques. Other factors, especially permissions issues, can be harder to isolate and resolve; but these troubleshooting technique can still help with many of those. As hinted, I find that strace and ltrace can be particularly informative under a Linux environment. Of course you can also find quite a bit of help in your system logging facilities (syslog) and your web server's logs. With Apache it's also possible run a single, non-forking, instance of your web server process (httpd) using the -X option. Using that with strace's -f (follow) it's possible to examine how your CGI script is getting spawned by the web daemon. This could also reveal some things that might not be evident from your wrapper script (though those are unlikely to interfere with your target's operations). From nospam at [127.0.0.1] Fri Mar 15 13:37:53 2002 From: nospam at [127.0.0.1] (Chris) Date: Fri, 15 Mar 2002 18:37:53 +0000 Subject: Good book on Python? References: Message-ID: In article , Kaklis Antonis writes >1) "Learning Python" --Mark Lutz & David Ascher > Little old (covers Python1.5.2), but excellent for a begginer >2) "Core Python Programming" --Wesley J.Chun > Details the core Python fundamentals and much more >3) And of course the Python tutorial > http://www.python.org/doc/current/tut/ >4)"How to think like a computer scientist in Python > http://www.ibiblio.org/obp/thinkCSpy/ Thank you. I downloaded number 4. However, it is in a strange form (Tex) for a windows user. Is it any use to me in that form? And can it be obtained in any other form? (It does look good.) -- Chris From MaximilianScherr at T-Online.de Sun Mar 24 07:07:04 2002 From: MaximilianScherr at T-Online.de (maximilianscherr) Date: Sun, 24 Mar 2002 12:07:04 -0000 Subject: Client/Server Tutorial? Message-ID: hi, Is there any good tutorial for creating advanced client/server apps (like online games) out there? i tried to make one 2 times, and both did not really work well, the first try had problems with communcications between the client threads, the second one had problems with connecting at all!!! thanks, Max From fperez528 at yahoo.com Sat Mar 23 21:51:29 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 23 Mar 2002 19:51:29 -0700 Subject: yenc encoding? References: <3c9b8743.23437968@news.t-online.de> Message-ID: Gerson Kurz wrote: > Does someone work on a yenc-encoder/decoder for python? Both "base64" > and "binascii" are there in the python standard library, after all. > > Just wondering: Should an implementation for a new encoding follow the > base64-model (that is, have four funcs encode, encodes, decode, > decodes) or the binascii-modell (a2b_yenc,b2a_yenc) or something > totally different altogether? You might want to take a look at http://www.exit109.com/~jeremy/news/yenc.html The guy seems to make very valid points. Cheers, f From m.faassen at vet.uu.nl Thu Mar 14 06:52:47 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 14 Mar 2002 11:52:47 GMT Subject: PEP 2, Procedure for Adding New Modules References: Message-ID: Aahz Maruch wrote: > In article , > Martijn Faassen wrote: >>Aahz Maruch wrote: >>> >>> The maintainers also possess primary responsibility for determining >>> whether bugfixes should be backported to previous Python releases as >>> discussed in PEP 6. >> >>Thanks; I'm adding some phrases on this to PEP 2. PEP 6 claims it's a >>'draft' PEP by the way, what is its status? > Looking at the status of other PEPs, it should be "Active", I think. I'm > cc'ing Barry on this to get his opinion. Mine's in there now though, which is set to 'draft'; I mean, it shouldn't become active just because it's in the list. But I assume it was discussed and approved. Which is good as my PEP refers to yours. Now I only need to go advocate for it on python-dev. :) Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From dale at riverhall.NOTHANKS.co.uk Sat Mar 23 16:57:29 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 23 Mar 2002 21:57:29 +0000 Subject: Replacing excel: but with what ? References: <3C9CCF6C.F1099089@vip.fi> Message-ID: I would still recommend wxPython. It is a top bit of software. Get youself on the mailing list and if you experience problems I am confident that it will get sorted there. -- Dale Strickland-Clark Riverhall Systems Ltd From peter at engcorp.com Tue Mar 26 22:33:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 26 Mar 2002 22:33:57 -0500 Subject: list comprehension question References: <20020325113323.A26319@glacier.arctrix.com> <3C9FC8AD.CD82FEA0@engcorp.com> Message-ID: <3CA13DA5.DF1C3C7C@engcorp.com> Laura Creighton wrote: > > >Peter Hansen: > > > Neil > > > > > > PS. tell the bot I'm sorry I doubted the correctness of his code > > > > If it's a bot, you don't have to apologize. Bots feel no emotion. > > > > And you're safe, too -- remember the First Law. > > > > -objectifying-tim-ly yr's, > > Peter > > Tisk tisk. Only half of the apologising you do for the other person. > The other half you do for yourself. Not sure I understand the sentiment, but perhaps it would have helped you if I included an explicit smiley? That _was_ a joke. Happily, I think from Tim's reply he understood and took it that way. (The reference to Asimov might be obscure to some. Sorry.) Thanks for the gentle advice though. :) -Peter From sjmachin at lexicon.net Mon Mar 11 22:07:24 2002 From: sjmachin at lexicon.net (John Machin) Date: 11 Mar 2002 19:07:24 -0800 Subject: NormalDate 1.2 released References: Message-ID: Jeff Bauer wrote in message news:... > NormalDate 1.2 is available from: > > http://starship.python.net/crew/jbauer/normaldate/ > I was curious to find the magic number 1582 in the source code, in a method where it is testing for a valid date: if year == 1582 and month == 10 and day > 4 and day < 15: return 0 # special case of 10 days dropped: Oct 5-14, 1582 To make some sense of reported historical dates, one needs to guess based on the location, origin and mind-set of the reporter. The introduction of the Gregorian calendar was spread over 1582-1587 in Roman-Catholic-influenced regions, 1700-1701 in some Protestant-influenced regions and 1752-1753 in others (including England and its then colonies) -- and that's just some of Europe. Greece didn't change until 1924. Germany, the Netherlands, and Switzerland split along religious lines into the 1582+ group and the 1700+ group. Alaska changed in 1867 upon purchase from Russia -- the then USSR changed in 1918; make your own deductions about other states like Louisiana and Texas. There's even a story that the date of introduction in Sweden varied by parish! Not all the countries that changed in 1582 omitted the same range of dates. The warp in the calendar that is used by the above code is only correct (under some limited definition of "correct") for the areas then defined as part of Rome, Italy, Portugal, Spain & Poland. From sholden at holdenweb.com Fri Mar 29 08:51:53 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 08:51:53 -0500 Subject: Standalone CGI Server - Question for Group References: <67abb823.0203281729.3b1b4db7@posting.google.com> <3CA3D86A.7080806@yahoo.com> <67abb823.0203290500.3a3a7da1@posting.google.com> Message-ID: "Sloth" wrote in message news:67abb823.0203290500.3a3a7da1 at posting.google.com... > Thanks for the feedback re. Apache. I appreciate it! > > The reason that I'd like to find a native Python script is as follows: > I started to build a proof of concept Web app for a company that > queried a customer database and generated search results. The company > loved it and wanted to have me create a few "pilots" for salespeople. > If I can simply have them install Python and install an additional > module or two, it would be easier than asking non-technical sales > folks to also install Apache. > > I agree, Apache is very painless. On the other hand, less is more in > this scenario and, frankly, now I'm just being stubborn and trying to > get Python to act as its own CGI server. Has anyone had luck making > this work in a Window 9x > environment? > CGIHTTPServer worked fine for me once the standard distribution included the option of using spawn() rather than fork() to start the CGIs. Are you using an older version of Python? If you are looking for pure-Python web server code, there's oodles of it in the download at http://pydish.holdenweb.com/pwp - this is the code from "Python Web Programming", all of which has run on Win 98. regards Steve From wurmy at earthlink.net Mon Mar 11 00:50:14 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Mon, 11 Mar 2002 05:50:14 GMT Subject: python name spaces References: Message-ID: <3C8C45F2.E0F6D9EC@earthlink.net> Daniel Ortmann wrote: > I must admit I am frustrated by Python's seeming lack of powerful name > space support. For example, in Perl I can do something like this, > > our $b = "...b"; > > { > my $a = "...a"; > our $f = sub { print $a, "\n" }; > our $g = sub { $a = "foo" } > } > > $f->() > $g->() > > # prints ...a, followed by foo. > # the "$a" variable is ONLY seen by the unnamed $f and $g > # subroutines. I don't know much about Perl, but this seems a bit like a closure like Lisp and Scheme have them. Python namespaces don't work like this. If you want a variable to be only visible by a few functions, and shared by those functions, the Pythonic solution would be, writing a class. HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From peter at engcorp.com Mon Mar 25 19:34:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 19:34:57 -0500 Subject: syntax to search ascii text file for unknown duplicate phone numbers ([2LJ2Ud5JyrXK+luOVRQpl References: Message-ID: <3C9FC231.564437C9@engcorp.com> Generic Poster wrote: > > vdWl+CWxdAtPuqZiM2EYPotKH? > one The following script should print out everything that it can about unknown duplicate phone numbers. Usage is: python checkdup.py The program will automatically adapt to all known input formats. ------------cut--here---------------------------- # checkdup.py: Copyright 2002 Peter Hansen, All Rights Reserved print "I don't know if there are duplicate phone numbers in that file" ------------------------------------------------- If you want a program that actually knows what the duplicates are and displays them, it will cost a little more... -Peter From sjmachin at lexicon.net Mon Mar 11 02:10:51 2002 From: sjmachin at lexicon.net (John Machin) Date: 10 Mar 2002 23:10:51 -0800 Subject: Regular expressions newbie: something for templates References: Message-ID: Skip Montanaro wrote in message news:... > Thomas> "This is the test $var1$ and this is $var2$" > Thomas> and turn it into > Thomas> "This is the test %(var1)s and this is %(var2)s" > > Give this a try: > > >>> import re > >>> s = "This is the test $var1$ and this is $var2$" > >>> re.sub(r"\$([a-zA-Z_0-9]+)\$", r"%(\1)s", s) > 'This is the test %(var1)s and this is %(var2)s' The truly paranoid may prefer this: re.sub(r"\$([a-zA-Z_][a-zA-Z_0-9]*)\$", r"%(\1)s", s) From shalehperry at attbi.com Sat Mar 30 03:09:53 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 30 Mar 2002 00:09:53 -0800 (PST) Subject: Data type ideas In-Reply-To: <004701c1d7b2$dbbf9180$a2a1d6d1@x9k7y2> Message-ID: > > So what next? Any ideas that I can use? > look into pickles. Act like dictionaries but live on the hard drive. From zeitlin at seth.lpthe.jussieu.fr Mon Mar 25 15:40:42 2002 From: zeitlin at seth.lpthe.jussieu.fr (Vadim Zeitlin) Date: Mon, 25 Mar 2002 20:40:42 +0000 (UTC) Subject: wxPython install problems on linux References: Message-ID: On 24 Mar 2002 21:26:00 -0800, hejduk wrote: > Hi, I'm having a problem installing wxPython on linux (Slak 8). I have > all the necesarry prerequisites (wxGTK, python etc). You need the GTK+ [headers] as well. HTH, 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 nixdisciplenews at hotmail.com Wed Mar 20 23:13:18 2002 From: nixdisciplenews at hotmail.com (Felix) Date: Wed, 20 Mar 2002 23:13:18 -0500 Subject: Python & IRC Message-ID: Greetings everyone, My question is this i like python and i want to start out and learn most of the basics before proceeding into more complex scripts. Now i love chatting learning new things in irc but it is hard as hell to find a irc client that is windows compatiable well windows 2000 professional compatiable irc client that will allow me to use python as a scripting language. If anyone has experience in scripting in irc and would like to point me in the right direction besides pointing toward dircchat.com or linux your help would be greatly appreciated. The only reason why i am looking for a stable fully functional client is because i would like to use python as a language in windows and linux because soon i will be adding red hat 7.2 to my new system. From gh_pythonlist at gmx.de Sun Mar 31 21:56:52 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 04:56:52 +0200 Subject: long integers In-Reply-To: References: Message-ID: <20020401025652.GG333@lilith.hqd-internal> * Michael Hall [2002-03-31 21:38 +0930]: > I'm using Python 1.5.2 and am having trouble with long integers when I > pull data out of a MySQL database using MySQLdb. When I retrieve a > numeric value from a field with an `int' data type, the value has an `L' > stuck on the end. What you experience is that if you print a Python long, an 'L' is added to the number to show that it is really a long. AFAIK you get the 'L' added for str and repr in 1.5.2, while it only gets added for repr in later versions. > In one script, I worked around this by stripping the L off with: > > var = numeric_id # ("2L") > var = var[:-1] > print var > >> 2 > > In this case, numeric_id was passed through a hidden field in an HTML > form. But this doesn't work in another script for some reason, where > the value is passed straight from a database query. Ok, maybe this transcript will show what's really going on here: lilith# mysql gerhard mysql> describe test; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | | PRI | NULL | auto_increment | | name | varchar(20) | YES | | NULL | | | age | int(11) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ 3 rows in set (0.01 sec) mysql> select * from test; +----+------+------+ | id | name | age | +----+------+------+ | 1 | Joe | 27 | +----+------+------+ 1 row in set (0.00 sec) mysql> Bye lilith# python1.5 Python 1.5.2 (#11, Apr 1 2002, 04:40:28) [GCC 2.95.3 20010315 (release) [FreeBSD on freebsd4 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import MySQLdb >>> db = MySQL.db.connect(db="gerhard") >>> cursor = db.cursor() >>> cursor.execute("select * from test") 1L >>> result = cursor.fetchone() >>> result (1L, 'Joe', 27L) >>> map(type, result) # Show the types for each item in the tuple [, , ] >>> id, name, age = result >>> age # will invoke repr 27L >>> str(age) '27L' >>> repr(age) '27L' >>> def numbertostring(i): ... # will work for int *and* long ... s = str(i) ... if s[-1:] == 'L': ... s = s[:-1] ... return s ... >>> numbertostring(age) '27' > I tried converting the data type from number to string, but that doesn't work > either: > > var = result[0] # ("2L") type(var) is long here. str and repr return "2L". > var = 'var[:-1]' You're binding the literal string 'var[:-1]' to the name var here, no conversion going on. To convert a long to a string in Python 2.x, simply use str, in 1.5.2, a function like my "numbertostring" will work. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.2 ?C Wind: 1.3 m/s From mcherm at destiny.com Mon Mar 25 17:42:19 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 25 Mar 2002 17:42:19 -0500 Subject: Indentation problem Message-ID: <3C9FA7CB.8000509@destiny.com> > Why I would like to put [end-of-block markers] in [the Python language]? > 1/ Because it's almost impossible to paste python code with ident = n > spaces to another code with indent = m spaces > This kind of examples occurs more and more and you can indent the code > by hand when it's 10 lines of codes, but not 1000 code lines. > It prevents the re-use of code pieces. Actually, copying and pasting 1000 lines of code prevents re-use of code. Even if it's just 10 lines that you're copying and pasting, I recommend trying to Refactor so that both places where the code is needed can share the same subroutine or helper class. -- Michael Chermside From sholden at holdenweb.com Thu Mar 7 20:00:42 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 7 Mar 2002 20:00:42 -0500 Subject: marcos and .pyc References: Message-ID: "dskhdskf dsfhs" wrote in message news:mailman.1015542734.19085.python-list at python.org... > > > Is there a feature in the basic python for doing inline marcos (similar to > the ones found in C and C++)? Also is there a way to specify where .pyc > files are to be deposited? > > Chris > Imelda Macros was the one with all those shoes, right? regards Steve From ozren_lasic at yahoo.com Wed Mar 6 13:30:35 2002 From: ozren_lasic at yahoo.com (Ozren Lasic) Date: 6 Mar 2002 10:30:35 -0800 Subject: Why KeyError ??? References: <7dee885c.0203051843.36efa5c2@posting.google.com> <7xvgcabcti.fsf@ruckus.brouhaha.com> Message-ID: <7dee885c.0203061030.5626d5e@posting.google.com> Sorry, but I didn't get it. Maybe you can explain me on another example?? a = ['abcde', '\xe7\xd0\x9f\x86\xa7'] b = map(lambda x: unicode(x, 'cp1250'), a) c = {} c[a[0]] = 0 # string c[b[0]] # unicode 0 c[a[1]] = 1 # string c[b[1]] # unicode KeyError c[b[0]] = 2 # string c[b[1]] = 3 # unicode c.keys() # no u'abcde' !! why ?? [u'\u0161\u0111\u010d\u0107\u017e', 'abcde', '\xe7\xd0\x9f\x86\xa7'] c.vaules() [3, 2, 1] Thanks !! From fperez528 at yahoo.com Fri Mar 1 02:17:33 2002 From: fperez528 at yahoo.com (Fernando Pérez) Date: Fri, 1 Mar 2002 00:17:33 -0700 Subject: sorting References: <3c7e3d12_7@news.teranews.com> Message-ID: "Jeff McComas" wrote > As a newbie i find the python scripting language very interesting and useful. > I am trying to write a script that will search a .txt file and have the script > tell me how many of the same numbers are in the .txt file. I know you can do > it with the f.count command but my problem is how can you do an input that > makes the numbers strings? Or puts double quotes and a comma around a number? You've received a number of perfectly good suggestions so far, and they illustrate nice and useful python programming techniques which you'll benefit from learning. If you need to do this for production code though, I suggest you look into Numerical python for handling large data arrays, and you may want to use a convenient histogram builder from the Scientific python family: http://starship.python.net/crew/hinsen/ Konrad's code is very good and well tested. With it, building a histogram for a large data file is one line of code. There's nothing wrong with your approach while you learn, I just wanted to point you in the direction of production-quality resources for when you need them. Enjoy python! f. From beppu at ax9.org Mon Mar 11 13:21:50 2002 From: beppu at ax9.org (John Beppu) Date: Mon, 11 Mar 2002 10:21:50 -0800 Subject: Python Equivalent of Perl's Safe module? In-Reply-To: References: Message-ID: <20020311182150.GA30978@Ax9.org> [ date ] 2002/03/11 | Monday | 12:30 AM [ author ] Sheila King > http://www.python.org/doc/current/lib/module-Bastion.html > http://www.python.org/doc/current/lib/module-rexec.html Thanks Jason && Sheila! From jeff at ccvcorp.com Mon Mar 4 19:09:05 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 04 Mar 2002 16:09:05 -0800 Subject: Windows GUI - which way? References: <3C7EC855.5844B19F@engcorp.com> <3C83D003.411FEE3F@ccvcorp.com> Message-ID: <3C840CA1.5A879360@ccvcorp.com> Spencer Ernest Doidge wrote: > Thank you, Jeff. > It happens that I want to do all this with scripts that are all under my > control, so there is a lot of good news here in your answer. > One further question: Should the two processes communicate with each other > via mmap? If you're controlling the scripts yourself, then you're probably better off using threads rather than subprocesses. In that case, there's no need to use mmap -- Queue.Queue will likely do everything that you need, and it's very easy to use. Each thread gets handed an input queue and an output queue when it's created. It can periodically check the input queue for any messages from the main thread, and can put output messages in the output queue (which the main thread then retrieves and handles appropriately). What constitutes a "message" is entirely up to you -- it can be any Python object. For simple cases, it could be a string or an integer, which the thread maps to some particular action (like aborting). For more complex cases, it would likely be an instance object, whose attributes carry whatever information you want to convey. (In my latest use of queues, the message object has a "command" attribute, which is essentially the name of a method to call, and other attributes of the object map to parameters for that method.) Jeff Shannon Technician/Programmer Credit International From bokr at oz.net Thu Mar 7 05:14:13 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Mar 2002 10:14:13 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> Message-ID: On Tue, 05 Mar 2002 12:00:56 -0800, Jeff Shannon wrote: > > >Bengt Richter wrote: > >> >Making Python as gibberish as Perl is. And all that only to >> >have Windows path be written without double-\ >> Not 'only'. I said 'also' ;-) Perhaps my choice of '|' delimiter triggered >> your 'gibberish as Perl' detector? >> >> I could have written >> >> q'###'c:\foo\bar\### >> or >> q'[quoting delimiter]'c:\foo\bar\[quoting delimiter] >> >> just as well for this one. > >I still don't like it. It's very difficult for me to see at a glance, what's part of >the string and what is part of the delimiter, especially with the leading delimiter >being quoted and the trailing one not quoted. It looks unbalanced, it looks ungainly, >and, to me, it just plain looks ugly. I'd expect the above example to be equivalent to >"'c:\\foo\\bar\\", with a leading mismatched single-quote... Your earlier example of I understand the reaction, and I had considered defining the delimiter with the quotes included. Whould you prefer the following? q'###'c:\foo\bar\'###' or q'__quoting delimiter (incl quotes)__'c:\foo\bar\'__quoting delimiter (incl quotes)__' But then I had to wonder whether using alternative quotes should imply the identical usage at both ends w.r.t. the quote marks. I.e., q'###'c:\foo\bar\'###' q"###"c:\foo\bar\"###" q'''###'''c:\foo\bar\'''###''' q"""###"""c:\foo\bar\"""###""" All that is very cluttered and ugly. The major use of q' would probably actually be in the Q' variation, and you could do the above pretty cleanly as: s = Q' ###' c:\foo\bar\ ### Note that the delimiter is '\n###\n' in the above, so there is no \n in the quoted string. I think this would bean easy pattern to use. To quote large unknown things, you just choose something safe in place of ###, and if you don't want to clip off the last \n, use Q'###' with no \n in front of the ###. Note that you could use Q'"""' in place of the leading """ in existing code, to allow you to put the first line of quoted text on the next line, without getting a leading \n. I.e., s = Q'"""' First line. ... Last line. """ # this comment immediately follows the quoting delimiter is equivalent (assuming """ quotes ok) to s = r"""First line ... Last line. """# this comment immediately follows the quoting delimiter (i.e., you have to account for the delimiter actually being '"""\n' -- cf. M' below) >cutting & pasting left me totally confused until I spent a minute sorting through it. > A minute seems not too bad ;-) I.e., you wouldn't have to re-think it to use it as a pattern for arbitrary quoting, I don't think. I only used the example text because it was a heavy mix of quoting that you could not quote with triple or double quotes. I thought q' and Q' to be pretty straight forward, once the syntax is grasped. Can you think of a better way to quote an arbitrary sequence of characters within a program text? >At least to me, this seems totally unclear and totally nonintuitive. It vastly How does it seem if you go along the steps I took?: 1. You have an arbitrary sequence of characters that are to be the value of a string. 2. The sequence may contain both ''' and """ and may even end with \ and it must be unchanged. 3. (2) Means you need a different delimiter than " or ' or """ or '''. 4. Using a string as a delimiter (like MIME or < won't do. 5. Python has a way to define a string, but not a way to indicate that it should be used as a delimiter. 6. (5) suggests using a Python string to define the delimiter string 7. (5) suggests that the string-as-delimiter needs to be distinguished from others 8. raw and unicode strings use a quote prefix to distinguish themselves from others 9. (5)+(8) suggests using an alternate prefix to define string-as-delimiter: I chose q and Q for quote 10. The actual content string must start somewhere after the delimiter string is defined 11. The obvious place for (10) is the next character after the final quote of the _delimiter_ string. 12. Using an otherwise ordinary python raw string as a delimiter, means the quotes are not included 13. (12) means the postfixed delimiter does not have quotes around it, unless you alter the delimiter string definition rules to include them. 14. There is an ugliness in using triple quotes to quote multiple lines of text with no leading empty line, since = """the text of the first line doesn't line up with the text of the following lines. """ 15. I thought of Q' to allow lining up all quoted text lines in a block by using the first character following Q'xxx' as the last character of the delimiter (thus using it up and allowing the real quoted text to start on the next line). Alternatively, we could replace the second ' after Q and delimit the delimiter-string with ' on the front and \n at the end, including neither. Perhaps that would be cleaner for ordinary multiline quotes (and change the prefix to M)? E.g., print M'XXX First line. Second line. XXX This would let you do the ugly windows path string even more cleanly: s = M' ### c:\foo\bar\ ### It's getting cleaner looking, don't you think? (The delimiter is '\n###' above, from source "M'\n###\n\n###" ). (delim-string delimiters)--> ^ ^^ >multiplies the possibilities for writing hard-to-read code, while providing a real I don't buy this, unless someone is being perverse in using it, or hasn't thought of really clean examples yet ;-). The point is to make the few places where it IS needed simple and clean. The point of posting it for discussion is to tease out better alternatives and/or usage patterns that really address the problem(s) without declaring it/them a/() non-problem(s). C'mon, how is the print M'XXX example above hard to digest? ;-) M'""" This could be a doc-string with no leading \n and looking as a block the way it would print. """ >benefit in relatively few situations. Considering how often triple-quotes appear in >text files, I can only imagine this being needed when trying to programmatically >generate Python code, which doesn't seem to be a terribly common task. I'd prefer to >find an alternate solution for the specific case of that task, which doesn't require >changing the core language and creating so much potential for ugly code in every other I don't see where an added capability, which does not alter interpretation of existing code, has "potential for ugly code" -- unless someone is abusing the capability. >task that can be done with Python. > How would you handle the problem as stated (cf. 1-15 above)? I appreciate the comments. I think they have led me to better examples, and possible variations on the original idea. If someone has better variations or alternative better solutions, I'd like to hear them. Thank you. Regards, Bengt Richter From cd.cd at wanadoo.fr Fri Mar 29 13:44:45 2002 From: cd.cd at wanadoo.fr (Cyr) Date: Fri, 29 Mar 2002 19:44:45 +0100 Subject: Problem with Tkinter Message-ID: Hi, I'm using python 2.2a4 installed in the directory : "/opt/tools/predim/python/" on a SGI IRIX 6.4 station. I've got a problem with Tkinter ; here is the message I get when launching the script zozo.py : (import Tkinter print "ok") srv0023-cyrille-~/> python zozo.py Traceback (most recent call last): File "zozo.py", line 1, in ? import Tkinter File "/opt/tools/predim/python/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: 1277322:/opt/tools/predim/python/bin/python: rld: Fatal Error:Cannot Successfully map soname 'libtk8.3.so' under any of the filenames /usr/local/lib/libtk8.3.so:/usr/lib32/libtk8.3.so:/usr/lib32/internal/libtk8 .3.so:/lib32/libtk8.3.so:/opt/lib32/libtk8.3.so Python has been installed on another station in a common directory and Tkinter works great on the other station. But the Tk library isn't in a common directory. On this station (srv0023), I only have Tcl/Tk 8.0 (and no library in the directories mentioned in the error message). Is there any way I can configure python so that it would use Tk 8.0 library on the station but continue to use Tk 8.3 on the other station ? In fact, I wonder how I can change the path search for the Tk library within python. If anyone could help, I would greatly appreciate, Regards, Cyrille DUMORTIER PS : forgive me for my broken english ;) From stojek at part-gmbh.de Mon Mar 25 15:32:39 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Mon, 25 Mar 2002 20:32:39 GMT Subject: avoid gui being blocked Message-ID: <3c9f7f9f.40054515@news.easynews.net> Hi, let's say I have a Dialog (using wxPython) with a button. This button starts a function thats takes some time to return. During this time the GUI is not responding to any action of the user. How can I keep the GUI alive? I tried starting "go" in a thread, but the only way I can check for the thread being finished is either thread.join() or: while thread.isAlive(): pass In both cases the GUI still doesn't respond. Is there something like a thread-exit event I could use. And how? This should be an all day problem, but I don't find a hint. Thanks in advance, Marcus #------------------------------------------------------------------- from wxPython.wx import * import time class Frame(wxFrame): def __init__(self,parent): ID_Button=wxNewId() wxFrame.__init__(self,parent,-1,"title") d=wxDialog(self,-1,"Dialog") wxButton(d,ID_Button,"Do it",wxDefaultPosition, wxDefaultSize) EVT_BUTTON(d,ID_Button,self.go) d.ShowModal() def go(self,event): time.sleep(10) return 1 class Main(wxApp): def OnInit(self): frame=Frame(NULL) return 1 app = Main(0) app.MainLoop() From woodsplitter at rocketmail.com Mon Mar 18 11:37:06 2002 From: woodsplitter at rocketmail.com (David Rushby) Date: 18 Mar 2002 08:37:06 -0800 Subject: Still same bug even with email ver. 1.2 References: Message-ID: <7876a8ea.0203180837.4aaa1542@posting.google.com> Sheila King wrote > OK, I got the latest email module from the CVS. I installed it. I ran the > tests for the module. Everything tested out fine. > > I now eagerly get out my code from last night, that was causing the > 'int' has no attribute .lower > error, and run it, hoping for different results. > > No good. Same results. :( > > File "E:\PYTHON\PYTHON22\Lib\site-packages\email\Message.py", line 285, > in get > name = name.lower() > AttributeError: 'int' object has no attribute 'lower' Here's the solution: http://mail.python.org/pipermail/python-list/2002-March/090448.html And here's SourceForge bug #491612 (closed now), which was filed to report this very bug: http://sourceforge.net/tracker/index.php?func=detail&aid=491612&group_id=25568&atid=384678 Unfortunately, contrary to Oleg's assertion in c.l.py and Barry's in his message added to the SF bug report, the CVS version of has *not* been fixed. It appears to me that this is a mere administrative glitch. The bug is a showstopper for the email package (it stopped my show, at least), but the fix is quite simple. Could we get it fixed before the final release of Python 2.2.1? Should someone resubmit the bug to mimelib's SourceForge bug tracker, or will this message be enough? From ajeru at gmx.net Sun Mar 3 19:02:46 2002 From: ajeru at gmx.net (Alexander Jerusalem) Date: Mon, 04 Mar 2002 01:02:46 +0100 Subject: mx odbc result strings with special characters? In-Reply-To: References: <24c39b2c.0203032114.3df9e523@posting.google.com> Message-ID: <5.1.0.14.0.20020304005913.029e0bf8@pop.gmx.net> Thanks a lot, now it works and even better I think I understand what's going on :-) I was aware of the fact that control characters like \n are represented in binary as a single number. What I missed is that I was printing the repr() of a tuple object instead of a list of strings. And this actually converts the strings back to Python source code as you point out. Thanks, Alexander At 00:06 04.03.2002 -0600, Jason Orendorff wrote: > > Hmm, ok, can you tell me how I can convert such a string back to the > > ISO8859-1 character set so that I can write it to a text file? > >It appears that it already *is* in the right character set. >Unfortunately, you seem to be converting it to a different >representation sometimes, quite unintentionally, when you >output it. > >Try this and see how it works. > > import mx.ODBC.Windows as odbc > > outfile = open("myfile.txt", 'w') > > con = odbc.connect(...) > c = con.cursor() > c.execute(...) > > record = c.fetchone() # record is a tuple > my_string = c[1] > print my_string # print the string, not the tuple > outfile.write(my_string + '\n') # write the string, not the tuple > > c.close() > con.close() > outfile.close() > > > The strange thing is, that when I read umlauts from a textfile and > > print them to standard out, they remain intact. Only when they come > > from the database driver are they converted to this hex > > representation. > >It's not the database or mxODBC that's doing it. > >The "hex representation" is just Python source code. >Nothing too weird about it; that's how Python programmers put >strings into programs. > >Suppose you type this. > > >>> x = '123\n\txyz\n' > >Now in memory there's a string that has 9 characters in it, >not 12. Your '\n' has been converted to a single byte, >with the value 10 (a newline character). The '\t' has been >converted to a single byte with the value 9 (a tab character). > > >>> print len(x) > 9 > >>> print ord(x[3]) # the value of the '\n' character > 10 > >>> print ord(x[4]) # the value of the '\t' character > 9 > >Now, suppose we print this string two different ways. > > >>> print x > 123 > xyz > > >>> print repr(x) > '123\n\txyz\n' > >See the difference? When you do "print x", Python dumps those >characters to your console. The newline characters, which you >entered as '\n', are now displayed as line breaks, and the tab >character, which you entered as '\t', is displayed as an >indentation. Likewise, depending on your console, the >character you could enter as '\xd6' might be displayed as a >Latin capital letter O with diaeresis (aka umlaut). > >When you do "print repr(x)", Python converts x *back* into >Python-source-code form and displays the result. > >Which of these is the true internal representation of x? >Neither. The internal representation is 9 bytes of data-- >a bunch of numbers, really, not characters or pixels or >source code. > >When you print a tuple, it tries to display itself in >Python-source-code format. This means, basically, calling >repr() on its contents. Not what you want. > >In order to display a string usefully, you must print the >string itself, not the tuple that contains it. > >Sorry to write at such length... :( > >## Jason Orendorff http://www.jorendorff.com/ From erno-news at erno.iki.fi Sun Mar 31 11:59:04 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 31 Mar 2002 19:59:04 +0300 Subject: PEP 285: Adding a bool type References: Message-ID: In article , Guido van Rossum writes: [...] | 1) Should this PEP be accepted at all. no. [...] | Rationale | Most languages eventually grow a Boolean type; even C99 (the new | and improved C standard, not yet widely adopted) has one. i don't agree wit this argument. | Many programmers apparently feel the need for a Boolean type; most | Python documentation contains a bit of an apology for the absence | of a Boolean type. I've seen lots of modules that defined | constants "False=0" and "True=1" (or similar) at the top and used | those. The problem with this is that everybody does it | differently. For example, should you use "FALSE", "false", | "False", "F" or even "f"? And should false be the value zero or | None, or perhaps a truth value of a different type that will print | as "true" or "false"? Adding a standard bool type to the language | resolves those issues. clearly you should not use constants, but use 0 and 1. i've personally not seen any code that uses constants like that. i'm sure you could find many other questionable practices used by many modules. i don't agree with this argument either. | Some external libraries (like databases and RPC packages) need to | be able to distinguish between Boolean and integral values, and | while it's usually possible to craft a solution, it would be | easier if the language offered a standard Boolean type. this is true, but not very significant. | The standard bool type can also serve as a way to force a value to | be interpreted as a Boolean, which can be used to normalize | Boolean values. Writing bool(x) is much clearer than "not not x" | and much more concise than | if x: | return 1 | else: | return 0 i say add a bool() builtin that returns 0 or 1, if it makes you feel better. | Here are some arguments derived from teaching Python. [...] in my experience, even absolute beginners naturally understand that 0 means false and 1 means true. the fact that other objects are interpreted as true or false can be slightly confusing, but in my opinion this is not enough of a problem to warrant the addition to language basics. keep python clean! ;) -- erno From jkraska at san.rr.com Tue Mar 19 02:22:29 2002 From: jkraska at san.rr.com (Courageous) Date: Tue, 19 Mar 2002 07:22:29 GMT Subject: psyco, jython, and python speed tests References: <83hendkou7.fsf@panacea.canonical.org> Message-ID: >This is unjustifiably glib. Lots of programs don't need to run fast. >Some programs do need to run fast. Some programs justify significant >work to get them to run fast. Accelerating Python is a good thing not >because of "so-called 'performance issues", but because in some cases, >there really *are* performance issues that rule Python out. Indeed; and believe it or not, there are even some environments where writing external C doesn't solve the problem either. C// From martin at v.loewis.de Tue Mar 26 18:47:36 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 27 Mar 2002 00:47:36 +0100 Subject: xml config file to python object References: Message-ID: Thomas Guettler writes: > I would like to parse > > 2 > sun > moon > > > to this: > obj={'myconfig': [ > { 'foo' : '2' } > { 'bar' : ['sun', 'moon']} > ] > } > > I did it this weekend with a sax parser. If this is the precise structure required, a SAX parser is probably as good as any other approach. Most automatic toolkits would either build obj={'myconfig': [ { 'foo' : ['2'] } { 'bar' : ['sun', 'moon']} ] } or obj={'myconfig': [ { 'foo' : '2' } { 'bar' : 'moon'} ] } > Is there a way to pickle (serialize) any python object > to xml and back? If you are interested in "basic" objects, the xmlrpc module of Python 2.2 will already marshal them in a cross-language way. Likewise, the PyXML xml.marshal package supports both WDDX support, and a customizable marshaller. For full pickling support, you can chose between xml_pickle, from http://www-106.ibm.com/developerworks/xml/library/x-matters11.html and the Zope xml pickle format ("ppml"). Regards, Martin From andymac at bullseye.apana.org.au Fri Mar 8 04:02:46 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 8 Mar 2002 20:02:46 +1100 (EDT) Subject: Getting stdout and stderr from popen In-Reply-To: Message-ID: On 6 Mar 2002, Stefan Heimann wrote: > >|> If I write > >|> > >|> pin, pout, perr = os.popen3('cvs status') > >|> > >|> I get the output of stderr and stdout but not in the right order. > >| > >| What do you mean in the right order? Do you mean that it is returning in, > >| err, out or that err and out are spitting out stuff simultaneously? > > the latter one. os.popen4() should give you a combined stdout/stderr pipe. Wouldn't rely on it to get the order correct though, especially on Windows. > > > > Probably not simultaneous, because the C I/O library probably has > > thread interlocks that prevent it, but if you want a single time > > ordered stream, you'd need time stamps to reassemble it out of > > two. For example, suppose you record the output of "make", which > > will be both output and error streams. If you read them separately, > > you won't be able to tell which compiler errors belong to which > > make commands. > > That's what I need! Is it really so complicated? I think it should be > common that someone needs to read stdout and stderr ordered by time. Its somewhat more complicated than appears on the surface for sure, because you get a whole heap of interactions involving:- - scheduling of the processes at either end of the pipe(s); - buffering (if any) of pipe data by the OS; - buffering (if any) of pipe data by the C runtime library, to mention some obvious issues. Because Unix was designed with the intent of using pipes to implement complex processes from simpler building blocks, using pipes on Unix usually works in a relatively sane way, although ptys are probably more appropriate/effective when bidirectional data transfer is required. The concept of pipes is definitely an afterthought in the Windows world (yes I know [MP]C-DOS 2 supported them, but it did so by writing actual temporary files, and I don't think its improved much). I am fairly sure you won't find a satisfactory way of getting stdout/stderr output synchronised to your liking on Windows - be nice to be proved wrong though. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From dale at riverhall.NOTHANKS.co.uk Tue Mar 19 08:31:05 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Tue, 19 Mar 2002 13:31:05 +0000 Subject: Dictionary Comprehension References: <3mbe9usoufc2f5ppjmk7lh6ks71pgb45f9@4ax.com> Message-ID: <88fe9u8nfu7mhii673iktejm0dbc6aru76@4ax.com> Michael Hudson wrote: > >It got made into a PEP: > > http://python.sourceforge.net/peps/pep-0274.html > >The "Parade of the PEPs" says: > > PEP 274 - Dict Comprehensions - Warsaw > > If we were to adopt dict comprehensions, this PEP says everything > that needs to be said. But I don't even want to think about this > for Python 2.3; I think it's way too minor a feature. > > This would be a lot easier to adopt if there was a working > implementation in patch form. > > Sometimes it would be nice if things like this could be defined > using hygienic macros or some other kind of preprocessor or > whatever, and imported from a module, rather than requiring major > hacking in the parser, the bytecode compiler, and the virtual > machine. > >Cheers, >M. Neat. I really must have a nose around the PEPs sometime. There could be all sorts of things I should be getting excited about. It doesn't look like they're barging each other out of the way to get to code it, though, does it? :-( Oh well. -- Dale Strickland-Clark Riverhall Systems Ltd From mikle at tomsk.net Wed Mar 6 06:11:17 2002 From: mikle at tomsk.net (Mikhail Astafiev) Date: Wed, 6 Mar 2002 18:11:17 +0700 Subject: Passing Unicode strings to Database Message-ID: <77188782494.20020306181117@tomsk.net> [Env: Win2k, Python 1.5.2] Hi people! I have a string in Japanese encoded in UTF8. I need to put it into database in Unicode form. import dbi, odbc o=odbc.odbc(self.ODBC_name+"/"+self.ODBC_sql_username+"/"+self.ODBC_sql_password) c=o.cursor() runes = UTF82Runes(string.replace(self.pr_table[row]["description"],"'","''")) operator="""INSERT INTO %s VALUES('%s','%s');"""%(self.ODBC_table, int(self.pr_table[row]["pr_no"]), runes.tostring()) c.execute(operator) # update database I'm getting the following error trace: Traceback (innermost last): File "C:\dev\Products\MRATES~1\server.py", line 34, in ? PR.sync_all() File "C:\dev\Products\MRATES~1\PRML\code\prml.py", line 2837, in sync_all self.__sync_with_sql__(i) File "C:\dev\Products\MRATES~1\PRML\code\prml.py", line 2797, in __sync_with_sql__ c.execute(operator) # update database TypeError: argument 1: expected string without null bytes, string found runes is array.array('H') containing Unicode string. Database string field has "ntext" type. How can I overcome this problem? Thanks in advance, Mick. From borcis at geneva-link.ch Thu Mar 21 02:46:38 2002 From: borcis at geneva-link.ch (Boris^2) Date: Thu, 21 Mar 2002 08:46:38 +0100 Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: <3C998FDE.5080204@geneva-link.ch> Nick Arnett wrote: > > I'm trying to figure out what the Internet is thinking today. What the internet is thinking, what the market is thinking... sounds to me like attempts to pass epidemics for thought processes. Regards, Boris Borcic -- Python >>> filter(lambda W : W not in "ILLITERATE","BULLSHIT") From p.magwene at snet.net Wed Mar 27 20:58:06 2002 From: p.magwene at snet.net (Paul M) Date: Thu, 28 Mar 2002 01:58:06 GMT Subject: new style classes and an IDLE "grump" Message-ID: There is a minor (but somewhat unfortunate) difference in the way the IDLE interpretter's "call tips" interact with "new" classes (i.e. classes derived from object) and "classic" classes. To see the difference try the following: >>> class Old: """An old style class (with sig).""" def __init__(self, x, y, z): pass >>> class New(object): """A new style class (without sig).""" def __init__(self, x, y, z): pass Now try instantiating an object of each of these classes while working in IDLE. For the classic class (Old) the idle prompt gives you a nice method signature - "(x,y,z)" in this case, along with the doc string for the class. The new style class doesn't give the same signature - only the doc string. The method signature is a very nice feature when working with python interactively - particularly for scientific computing. The solution seems to be simply changing line 115 in CallTips.py (in the Tools/Idle/ directory) as folows: < if type(ob)==types.ClassType: --- > if type(ob)==types.ClassType or type(ob) == types.TypeType: This seems to "solve" the problem. However, is this the right solution - i.e. is it only classes which are objects of type TypeType? From my reading of the "what's new" document I think this is the case, but it's late and my brain is feeling a bit fuzzy. Can somebody more up to date confirm or correct me on this matter? Cheers, Paul From eppstein at ics.uci.edu Mon Mar 18 19:43:03 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 18 Mar 2002 16:43:03 -0800 Subject: Declare list of large size References: Message-ID: In article , "Delaney, Timothy" wrote: > > list = [0]*100 > > But note that this is only safe for immutable elements. You will obtain a > reference to the *same* object as each element. > > This normally bites people when they try to make multi-dimensional arrays > ... > > list = [[0] * 2] * 2 > print list > list[0][0] = 1 > print list > > [[0, 0], [0, 0]] > [[1, 0], [1, 0]] > > As you can see, the first element of each sub-list has been changed - this > is because each sub-list is in fact the same list! I got bitten by that, once. It took very little time to learn not to do that. So, is it considered more Pythonic to create a multidimensional array by list = [[0]*100 for i in range(100)] and then access it by ...list[i][j]... or is it more typical to just use dictionaries? list = {} ...list[i,j]... ? I can see advantages either way -- the dictionary method is simpler, more space-efficient if you don't intend to fill the whole thing, and makes it easy to pass around and use tuples representing indexes into the array. But the list-of-lists more explicitly states what you're doing, may be slightly faster (I haven't checked), gives you bounds checking,and more generally doesn't let you index by anything but a tuple of integers. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From Scott.Daniels at Acm.Org Thu Mar 7 16:55:10 2002 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 07 Mar 2002 21:55:10 GMT Subject: A Date-Time format stored as Days Message-ID: <1103_1015538110@news.dsl-only.net> While many Linux / Unix systems represent time as a number of seconds since a base time. One big problem with this format is that, while differences are easy to calculate, it does not incorporate "leap seconds" gracefully at all. A representation of a Date-Time as Days and seconds within day is better, but differences are tougher to calculate, and naive code breaks badly in the presence of leap seconds. A representation as A Day / fixed point fraction of a day should work much better. In a system that ignores leap seconds, this is simple. The low word (fixed point day fraction) can simply be multiplied by a constant to convert it to seconds. If there _are_ leap second records, they affect the day fractions of certain days. This is usually reflected as a scaling providing an extra second on a particular day. In rare cases, certain days have _two_ leap seconds, so there are three scale factors converting day parts to seconds: normal days, leap-second days, and double-leap-second days. The differences between the factor for double- leap-second days and normal days is 2 seconds in 24*60*60 or 1 part in 43200. This "error" is spread smoothly across the day, so that naive difference of two date-times is quite close to the leap-second aware difference. By calculating in units of days, we can do quite well in avoiding running into the leap-second problem. With 64-bit hardware, we can quite nicely use the high order 32 bits for a day and the low order 32 bits to get a very high-precision day part, and simply use integer math to do most calculations. -Scott David Daniels Scott.Daniels at Acm.Org From hfoffani at yahoo.com Tue Mar 5 09:03:51 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Tue, 5 Mar 2002 15:03:51 +0100 Subject: Status of PEP's? References: <7xwuwrofhk.fsf@ruckus.brouhaha.com> Message-ID: <20020305090407.625$U4@news.newsreader.com> [regarding Naturals include or not Zero] ... > At Uni, my two maths profs disagreed, too. > I was learnt that Naturals do not include zero. Then in math we defined "Naturals plus Zero" set as: N+ = N U { 0 } # the '+' is superscripted Afterwards we used N+ whenever we need the zero to be part of the Dominium. Once the set was specified in later colloquially references the name "Naturals plus zero" was shortened as just Naturals. We never had to forget the little '+' though in our homeworks or tests, though. -Hernan From peter at engcorp.com Sun Mar 10 00:24:25 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 00:24:25 -0500 Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> Message-ID: <3C8AEE09.5B2431FD@engcorp.com> Grant Edwards wrote: > > >> Optimally, it would be a single "exe" file that doesn't > >> require any installation procedure. > > > > That's too much to ask for even a native Windows app in most > > cases these days. > > That's kind of sad, but I figured as much. The only real > stand-alone Win32 app I've seen in a long while is puTTY. Are > statically linked apps just not possible under Win32, or just > not practical? Just as possible and practical as under Linux, really. Which is to say not highly desirable in many cases, at least for serious (read, largish) applications. For smaller utility type programs, definitely possible but, unfortunately, less of an option in your case trying to do it with Python tools. But you really don't want to statically link an 800K interpreter and a 2MB windowing framework into your little utility, do you? :) > > Use py2exe and you'll get a directory with the Python DLL, the > > wxPython DLL, your EXE, and a few other DLLs as needed (e.g. > > the native regular expression stuff if you use it). > > I don't know diddly about DLLs, so pardon the ignorant > question: Can my DLLs be put in a private directory where my > EXE can find them? I'd rather not put anything in any public > system directories. Yes, definitely. Not entirely advisable if you're delivering more than one program in the same manner, since you'd be duplicating piles of files, but you can do it. And I suppose there's the fact you'd be avoiding much of the grief caused by dynamically linked apps and "DLL version hell" by doing that, if you can spare the hard drive space (and most users probably can these days). -Peter From tim at zope.com Fri Mar 8 01:04:44 2002 From: tim at zope.com (Tim Peters) Date: Fri, 8 Mar 2002 01:04:44 -0500 Subject: PEP Parade Message-ID: Quoting Guido's new "Parade of the PEPs" essay at http://www.python.org/doc/essays/pepparade.html """ To start off Developer's Day at the Python10 conference I gave a keynote ending in what I dubbed "the parade of the PEPs". It was a brief overview of all open PEPs, where I gave my highly personal and subjective opinion for each PEP. Later, I realized that this might have been of interest to other developers. I didn't take notes at the conference, so below is a different set of comments that I created from scratch during a single two-hour sitting on March 7, 2002. """ Since Guido's "highly personal and subjective opinions" are nevertheless destined to circumscribe every waking moment of your Python life, everyone interested in Python development should give it a good read. It's also linked to from the PEP Index page at SourceForge: http://python.sf.net/peps/ Note that Guido wants to keep 2.3 free of new core language features. You can deduce that from reading the essay, or-- like me --you can just believe it because it's true . There's a huge backlog of good ideas for improving the internals and libraries, and I wouldn't be surprised to see the focus remain there for 2.4 too. From duncan at NOSPAMrcp.co.uk Thu Mar 14 11:48:08 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 14 Mar 2002 16:48:08 +0000 (UTC) Subject: does Python support some kind of "casting" References: Message-ID: Tino Lange wrote in news:a6q6hu$1c6$1 at crusher.de.colt.net: > So the best solution is to transport an object like > return list(newlist) > > But I guess this makes a temporary copy of my MaxSizedList just for the > XML-RPC-transport, or? So it's horrible inefficient? > > Yes, that will make a copy. But copying a list is a pretty efficient operation, so no, it isn't really horribly inefficient. Have you tried it and identified this as a bottleneck? How long are your lists anyway? One way to do this that avoids the copying is to aggregate a list object into your class instead of trying to subclass the list type. Then you can simply return the internal list object if you want. However, from your description I would be much more worried about the throwing away elements from the front of the list every time you append to the end of the list. I do hope you are batching these up into large chunks to be discarded, not throwing them away one or two at a time. -- 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 giles_brown at hotmail.com Mon Mar 25 15:18:44 2002 From: giles_brown at hotmail.com (Giles Brown) Date: 25 Mar 2002 12:18:44 -0800 Subject: communication with a java applet References: <3C9F100D.BAB4F24D@hotmail.com> Message-ID: <57de9986.0203251218.6e42a9ab@posting.google.com> Looping wrote in message news:<3C9F100D.BAB4F24D at hotmail.com>... > Hi all, > > I am trying to make a real-time system communicate with a java applet > under IE 5.5. I only have a pyd file (Python 1.5.2) to get the floats > calculated on the platform and I wonder how to make the platform > communicate with my java applet : TCP/IP, CORBA, shared memory, > others... ? > > Thanks in advance for any advices, Its relatively straightforward to get Python and Java to talk over sockets. If you want to send data in a binary format then on the Python side of things there is the "xdrlib" (I'm assuming this was present in Python 1.5.2 as I don't have 1.5.2 installed anymore). On the Java side you'd want to get hold of a DataInputStream (or DataOutputStream). Something like: DataInputStream dis = new DataInputStream(mySocket.getInputStream()) ; double nextValue = dis.readDouble() ; Good luck, Giles From theller at python.net Mon Mar 25 11:06:45 2002 From: theller at python.net (Thomas Heller) Date: Mon, 25 Mar 2002 17:06:45 +0100 Subject: PEP262 - database of installed packages References: Message-ID: > >> * XXX do we need to store permissions? The owner/group? > >> + THE: no, not on windows. > > > > Really? Even on Windows, couldn't files be potentially owned by > > Administrator or some other user. We should definitely have > > permissions and owner/group on Unix; can you tell me what Windows > > needs here? (I assume MacOS X would be the same as Unix, and earlier > > MacOS versions aren't multi-user, so they don't need anything.) > > On Windows systems all files on an NTFS partition have an owner and access > control lists. The command "DIR /Q" displays the owner of each file, or you > can add a column to the explorer view. By default I think each file is > owned by the owner of the directory in which they are created > (BUILTIN\Administrators for just about everything). My laptop also has a > FAT partition. It seems that files on that are owned by 'Everyone'. :-( All true. On the other hand, Python has no possibility to display or change the owner and access control lists (except if you do some hardcore win32 programming). Thomas From shalehperry at attbi.com Wed Mar 6 17:48:27 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 06 Mar 2002 14:48:27 -0800 (PST) Subject: The language vs. the environment In-Reply-To: <15494.39790.135887.255289@beluga.mojam.com> Message-ID: On 06-Mar-2002 Skip Montanaro wrote: > > Sean> On 06-Mar-2002 Steve Lamb wrote: > >> On Wed, 06 Mar 2002 13:21:35 -0800 (PST), Sean 'Shaleh' Perry > >> wrote: > >>> help release more python modules so perl mongers will quite wagging > >>> CPAN in front of our faces. > >> > >> Quality over Quantity. :) > > Sean> not to disagree, however there are FAR more interesting perl > Sean> modules out there than python ones. > > Correct, which is why a better solution than CPAN or VoP might include some > sort of module rating system. However, this discussion probably belongs on > the catalog-sig. (my first bullet. hint, hint... ;-) > oh, so that is what the catalog-sig is (-: From peter at engcorp.com Fri Mar 22 22:56:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 22 Mar 2002 22:56:33 -0500 Subject: circular imports (don't yell!) References: Message-ID: <3C9BFCF1.3CF03E1C@engcorp.com> jimh wrote: > > We have a scenario where we have (and need) circular imports, that is, A > imports B imports C imports A. Now I know there are ways around this, but > we have external dependencies that make it very difficult to use an > alternative, so don't be yelling at me about the design ;) I can't criticize external dependencies that are outside of your control, but be careful ignoring suggestions that you shouldn't have to find a way to handle circular imports. You'll have to work harder to convince many of us that there isn't a fairly straight-forward, if non-obvious, way to get what you want without a true circular import. > I have whittled the problem down to 3 files: Thanks for that! :) Try this instead, and if it isn't acceptable, my suggestion would be to explain more about the real situation and let _us_ conclude that you really do, in fact, have to stick with your circular imports. a.py ------ consta = 3 if __name__ == "__main__": from b import * # other modules don't run these from c import * print consta print constb print constc > Any ideas? I didn't bother trying to figure why it works the one way you had it but doesn't the other way. You really don't want to be relying on some obscure phenomenon that takes that much effort to investigate, even if you can get it working. Also, do you realize that "from X import *" is a bad idea in general? I'll assume that was just something you did to try to reproduce the problem in a small sample program... -Peter From anton at vredegoor.doge.nl Mon Mar 4 16:50:38 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 04 Mar 2002 22:50:38 +0100 Subject: Brewster's Factor - was :Trouble running programs References: Message-ID: On Mon, 04 Mar 2002 12:48:55 +0100, Laura Creighton wrote: >the only Brewster Factors I can find have to do with polarised light, >or English Chrisitian Revivalist Victorian political parties, neither >of which I suspect is what I am looking for. Any ideas? Sorry, I can't help you here, but having read a book about Murphy's law I have an intuition about what Brewster Factors might be. Suppose someone is looking for something (like Brewster Factors for example), then most of the time the place where someone will find them will be the last place this person looks for them, like in the following code example: a = 5 r = range(10) for i in r: if i == a: break print i Now I have the idea that Brewster Factors are influencing i to be equal to 5 after the for loop in the example code for just enough times to make someone completely rely on this feature. After that of course i is undefined. Anton. From jrchaff at mcn.net Sun Mar 10 21:54:02 2002 From: jrchaff at mcn.net (jrc) Date: Mon, 11 Mar 2002 02:54:02 GMT Subject: Help newbie w/Numpy Install ?? Message-ID: <3C8C1C4F.7770642A@mcn.net> Hi there, I'm brand new to Python - tho experienced somewhat with programming, compiling, etc. I just downloaded Python v2.2 but have yet to install. I'm going to run it on Windows ME. (I have MSVC 6.0 but not installed, hopefully don't need all that.) I can't seem to understand, on sourceforge / numpy pages, the following two issues: a) Exactly which files do I need to download to make NumPy work with Python 2.2 - or is that even possible? b) Will I need my c-compiler to get NumPy to work? Thanks in advance, J.R. Chaffer From arturs at iidea.pl Fri Mar 22 03:19:11 2002 From: arturs at iidea.pl (Artur Skura) Date: Fri, 22 Mar 2002 08:19:11 +0000 (UTC) Subject: Sorting distionary by value Message-ID: Is there an idiom in Python as to sorting dictionary by value, not keys? I came up with some solutions which are so inefficient that I'm sure there must be a simple way. Regards, Artur -- http://www.wolneprogramy.org http://mf.gnome.pl From cqxiao at charter.net Sun Mar 3 10:35:31 2002 From: cqxiao at charter.net (chongqing xiao) Date: Sun, 3 Mar 2002 09:35:31 -0600 Subject: question about Generator Message-ID: Hi, Suppose if I have a generator (func) which will return [2,4,6,8] Is any way I can just get the first item (instead of using for x in func() to get the first item) or stop before I get the last item in the Generator. Also, any comments on what the following code will do. (I don't have 2.2 installed so I can't try it myself) for x in func(): for y in func(): print x,y Thanks a lot Chong From xonda-m at xonda.net Sun Mar 3 20:36:41 2002 From: xonda-m at xonda.net (=?euc-kr?B?vfC02bPd?=) Date: Mon, 4 Mar 2002 10:36:41 +0900 Subject: =?euc-kr?B?W7GksO1dua7A2rjevcPB9iC067euILnfvNsgudcgsO2wtCCw/LiuIA==?= =?euc-kr?B?x8G3zrHXt6UovfC02b+lKQ==?= Message-ID: ?? ????? ???? ?? ?? ???? ??? ??? ??(??? ???? ??) ??, ????? ? 365? ???????? ??? ????? ??? ???? ??? ??? ?? ?????? ???? ????? ???? ?????? ???, DM? ?? ???? ???? 2? ???? (PC? ? ?? ????) 1000?? ?????, ??? ??? ?? [ Xonda-M Ver 1.5 ????? ???? ] - ????? 10? ???? ?? - ??? ?? ????? ?? ? ???? ?? ????!! ???? ??? ? ?????. ????? ??? ??? ??? ? ? ???. ???? CEO / ????? / ???? / ???? ?? / ????? ?? ?? ? ? ?? ?? ?? ??? Xonda-M(???)??? ?????. ???? : Xonda-M??? 02) 723-7927 xonda-m at xonda.net , http://biz.xonda.net/ ? ??? ????? ???? ?? ? 50?? ???? [??] ???? ??????. ??? ?? ??? ????? ?? ???? ???? ??? ??? ???, ???? ???? ??? ??? ??? ?? ????. ? ??? ? 1?? ?????. ?? ?? ?? ???? ?? ???? ????? ??? ??? ????. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Arnaud.De_La_Fortelle at inria.fr Tue Mar 19 08:48:51 2002 From: Arnaud.De_La_Fortelle at inria.fr (Arnaud de La Fortelle) Date: 19 Mar 2002 14:48:51 +0100 Subject: [wxPython 2.3.1] what's going on? References: Message-ID: > Has anybody met this problem, or it's just my 'private reslult' :) No problem for me. (Linux RedHat 7.1, python 2.2, wxPython-2.3.2.1) Arnaud Python 2.2 (#1, Feb 6 2002, 12:33:27) [GCC 2.95.2 19991024 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> 4*math.exp(-0.5)/math.sqrt(2.0) 1.7155277699214135 >>> from wxPython.wx import * >>> 4*math.exp(-0.5)/math.sqrt(2.0) 1.7155277699214135 From michael at stroeder.com Thu Mar 28 14:22:53 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 28 Mar 2002 20:22:53 +0100 Subject: Simple threaded web-server based on BaseHTTPServer? References: <3C59295E.3080900@skippinet.com.au> <3C5976D0.A3A63A46@stroeder.com> Message-ID: <3CA36D8D.1080204@stroeder.com> Aahz Maruch wrote: > In article <3C5976D0.A3A63A46 at stroeder.com>, > Michael =?iso-8859-1?Q?Str=F6der?= wrote: > >>In my case (http://web2ldap.de) I'm using threaded BaseHTTPServer >>but I'm not really happy with it. Especially since I have to use a >>module-wide lock to serialize calls into python-ldap module because >>the underlying OpenLDAP libs are not thread-safe. This can block the >>whole thing and killing threads on e.g. Linux is not possible. >>Having a single-process asyncore design would probably make things >>easier. > > Add another thread to serialize things instead of using a module-wide > lock. I really wonder how this helps if the call into the underlying module really blocks. BTW: In opposite to my original statement an asyncore design would also not help since the underlying OpenLDAP lib is not designed that way. Ciao, Michael. From bokr at oz.net Sat Mar 23 16:06:09 2002 From: bokr at oz.net (Bengt Richter) Date: 23 Mar 2002 21:06:09 GMT Subject: Begginers Guide - Exrcise. Help me, plz! References: <3C9B7A1E.451453BA@ccvcorp.com> Message-ID: On 22 Mar 2002 23:15:24 GMT, bokr at oz.net (Bengt Richter) wrote: [...] > print "That's not a integer. Try again!" print "That's not an integer. Try again!" That was too jarring to leave be ;-) Regards, Bengt Richter From xx758 at cam.ac.uk Mon Mar 4 08:58:03 2002 From: xx758 at cam.ac.uk (Xiao-Qin Xia) Date: Mon, 04 Mar 2002 13:58:03 +0000 Subject: Response to resizing window Message-ID: Hi, everybody, I draw a chart (some lines and text message) on a canvas in a Toplevel window. I want to redraw the chart whenever the window is resized. Anybody can show me how to do it? (I guess I need something like WM_DELETE_WINDOW) Regards, Xiao-Qin From aahz at pythoncraft.com Sun Mar 24 10:03:27 2002 From: aahz at pythoncraft.com (Aahz) Date: 24 Mar 2002 10:03:27 -0500 Subject: Stopping threads from the outside References: Message-ID: In article , wrote: > >maybe a simple question: > >how could you stop a running threading.Thread from the *outside*? of >course i could introduce some kind of flag into the event loop of the >Thread.run-method, but i really would prefer to have a non-instrusive >way for several reasons. > >Any way to do this? Not really. Why do you want to do it? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From sholden at holdenweb.com Fri Mar 29 17:37:57 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 17:37:57 -0500 Subject: [XP] Code Complete: Things were Scary Back Then References: <3CA4E5F5.70B5A7E5@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3CA4E5F5.70B5A7E5 at engcorp.com... > David Brady wrote: > > > > > -----Original Message----- > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > > > I don't remember any of the BASICs that I used, > > > whether Apple II, PET, C-64, MS, or other having modules > > > I did this a lot. There was no enforcement of > > "modules" in BASIC, but you could still do modular > > programming. You only had the one big program to work > > with, but you mentally divided it up into sections. > > Well, I used reserved blocks of line numbers in the same > way, but I'd hardly deign to call that "making a module". > I went as far as producing a programming system called BLINK which treated non-numbered BASIC code pretty much like assembly language, assigning line numbers dynamically as it processed the code. For those of you that can remember PDP-11 assembly language, I even had PSECTs so you could have several different sections of your program "assembled" into several different ranges of line numbers. Back in those days (1978) most Basic Plus programmers had only got as far as standard that said "subroutines should have line numbers between 20,000 and 29,999", which meant that they often had to resolve line number clashes and renumber the code. I even wrote this up for a DECUS conference but I doubt if that paper is available now. > And I didn't call the use of GOTO "sending a method to > another object" either. ;-) > Tired old cynic that you are ;-) regards Steve From jason at jorendorff.com Sat Mar 9 21:10:49 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sat, 9 Mar 2002 20:10:49 -0600 Subject: Threading help? In-Reply-To: <3C85ABDB.6090606@Lindbergs.org> Message-ID: VanL wrote: > I can do each of the individual parts, but I don't know how to combine > them all so that each is running in a different thread, so that process > 2 doesn't make the other two lose their timing. # NOTE: The code below ignores synchronization issues. This is actually # okay for this situation, I think, because assigning or accessing the # value of an attribute is guaranteed atomic. But in general you would # want to protect all access to data that's common across threads, # using e.g. threading.RLock. # # Your requirements ask for the data processing to occur every 0.1 sec. # This doesn't exactly do that, but you can delete the time delay if # this really needs to run *constantly*. # # It would be more typical to fetch the data on demand, then cache # it in case another response comes in at about the same time. # Then you wouldn't need threads at all. import threading, time, urllib, BaseHTTPServer # First, start a processing thread. class ProcessingThread(threading.Thread): """ Thread for fetching and formatting data. Attribute: self.result - a tuple with (timestamp, data). """ def __init__(self): self.result = (0, '') self.done = 0 def run(self): while not self.done: data = self.fetch_new_data() output = self.process(data) self.result = (time.time(), output) time.sleep(0.1) def fetch_new_data(self): ... use urllib to get new data ... def process(self, data): ... do something with the data ... ... format it for output ... return result processing_thread = ProcessingThread() processing_thread.start() # In your main thread, do your server stuff. # This is of course example code. class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): timestamp, output = processing_thread.result self.wfile.write("HTTP/1.0 200 OK\r\n" ... ... your headers here ... ... "Date: " + format(timestamp) + "\r\n" "Connection: close\r\n" "Content-type: text/html;charset=US-ASCII\r\n" "Content-length: " + str(len(output)) + "\r\n" "\r\n") self.wfile.write(result) server = BaseHTTPServer.HTTPServer(('', 8000), MyHTTPRequestHandler) server.serve_forever() ## Jason Orendorff http://www.jorendorff.com/ From stevewilliams at wwc.com Mon Mar 18 19:38:47 2002 From: stevewilliams at wwc.com (Steve Williams) Date: Tue, 19 Mar 2002 00:38:47 GMT Subject: Python-DB2 module and DB2 Connect References: <3C90A125.4020208@stroeder.com> <3C90BF28.8080301@stroeder.com> <3C932F02.259AD2A1@wwc.com> <3C933DD5.4090804@stroeder.com> Message-ID: <3C968A66.707@wwc.com> Michael Str?der wrote: > Steve Williams wrote: > >> =?ISO-8859-15?Q?Michael_Str=F6der?= wrote: >> >>> Michael Str?der wrote: >>> >>>> Anyone here which had success with using DB2-Python-0.991 (see >>>> ftp://people.linuxkorea.co.kr/pub/DB2/) build against DB2 Connect? >>> [snip] >> cursor.execute("insert into X(Y,Z) values ?, ?",('123.45','10')) >> >> fails with SQL0408N, SQLSTATE=42821, type mismatch. >> >> However, >> >> cursor.execute("insert into X(Y,X) values cast(? as >> decimal(5,2)),cast(? as integer)",('123.45','10')) >> >> succeeds. >> >> The failing insert succeeds on Windows 2000 with mxODBC and ODBC >> connected to the same database. The Windows CLI/ODBC settings don't >> seem to show any particular magic. > > > Does the SQL statement also work in the commad-line tool db2? > > Well, I finally succeded after setting PATCH1=0 and PATCH2=0 in > db2cli.ini and using SQL statements valid for DB2 OS/390. > > Though I have to admit that I'm a RDBMS newbie just starting to get > involved with DB2 for a rather simple project. > > Ciao, Michael. > Well, clearly, the error message is correct. The execute command should fail, and the INSERT does indeed fail in the command line tool. My point here is to be careful moving from ODBC to the API, because ODBC may do some extra [helpful] things. The DB2 API works for me. Steve From aut at c2i.net Wed Mar 27 05:30:00 2002 From: aut at c2i.net (Audun Tonnesen) Date: Wed, 27 Mar 2002 10:30:00 GMT Subject: Python Web Programming Book? References: Message-ID: <1103_1017224999@news1.c2i.net> Couple of days ago, I spent half an hour in the book store leafing through this one. There's also an interview with the author on the publisher's website. http://www.amazon.com/exec/obidos/ASIN/0735710902/qid=1017224740/sr=1-13/ref=sr_1_13/103-7891501-7655015 Audun On Thu, 28 Mar 2002 04:19:04 +0930 (CST), Michael Hall wrote: > > I'm wondering if anyone can suggest the best (or a selection of the > best) books available covering the use of Python in a web and database > environment? It's OK if the book deals with other stuff, as long as its > treatment of web programming and database integration is good. > > Is a book that also deals with Zope, Cheetah and Albatross or > related topics (embedded Python, I suppose) asking just too > much? > > A good text will certainly cut down my newbie questions to this list. > So far I have Mark Lutz' "Python Programming" and Andre Lessa's "Python > Developer's Handbook" on my shortlist. > > Mick > > From aahz at panix.com Sat Mar 9 06:33:08 2002 From: aahz at panix.com (Aahz Maruch) Date: 9 Mar 2002 03:33:08 -0800 Subject: Is current integer for-loop syntax a wart? References: Message-ID: In article , Cromwell, Jeremy wrote: >PEP 276 (Simple Iterator for ints) and PEP 284 (Integer for-loops), among >others, are written from the perspective that the current integer for-loop >syntax > > for i in range(10): > >is a wart. Is this true? That is, where does the Python community stand on >this issue? Wart? It's somewhat awkward for heavy-duty manipulation of sequence indexes, but the proposals that suggest adding a new function or two to handle that are best IMO. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From cwazir at yahoo.com Tue Mar 12 21:04:19 2002 From: cwazir at yahoo.com (Chirag Wazir) Date: 12 Mar 2002 18:04:19 -0800 Subject: english thesaurus and dictionary References: Message-ID: <79c178a9.0203121804.49f3e780@posting.google.com> Take a look at http://pywordnet.sourceforge.net It's excellent, though it may be overkill for your application :-) Chirag bobnotbob at byu.edu (Bob Roberts) wrote in message news:... > I want to incorporate an english thesaurus and dictionary into my > application. Does anybody know of freely available thesauri and > dictionaries that I could use? From jlh at cox.net Fri Mar 1 20:18:01 2002 From: jlh at cox.net (Jeff Hinrichs) Date: Sat, 02 Mar 2002 01:18:01 GMT Subject: Status of PEP's? References: Message-ID: wrote in message news:mailman.1015021205.11416.python-list at python.org... [...snip...] > There's no requirement to think about number theory or to view integers as > collections here. All that is suggested is a slightly-less cluttered (than > current) way to iterate the indices of an indexed-collection. If you are > happy with range/xrange, so be it. What you are asking everyone to agree with is: 5 = [0,1,2,3,4] I would fall in the camp that does not favor this. If you were to restate the above as: f(5)=[0,1,2,3,4] Then, I believe, that you wouldn't have any problem convincing a large majority that it is possible for f() to produce such an output. That being said, I would find that the argument favors the use of range/xrange over the concept of iterable integers. -Jeff Hinrichs From Gabe.Newcomb at noetix.com Tue Mar 19 17:36:41 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Tue, 19 Mar 2002 14:36:41 -0800 Subject: arrays help Message-ID: <0C7CA8D8DF75494EB09AB6016990107F011B1819@NOXMAIL.noetixad.com> if l = [['a','b'],'dog','cat'], then l[0][1] = 'b'. Is that what you meant? Gabe -----Original Message----- From: Umesh Persad [mailto:upersad at tstt.net.tt] Sent: Tuesday, March 19, 2002 6:24 PM To: python-list at python.org Subject: arrays help Hi, I am just getting started with Python from a c/c++ and Java background. I am programming a game and I wanted to represent a gameboard by a double subscripted array. How do I do this in Python? Thanks, Umesh -- http://mail.python.org/mailman/listinfo/python-list From jgardn at alumni.washington.edu Thu Mar 7 06:46:14 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Thu, 07 Mar 2002 20:46:14 +0900 Subject: fork and thread and signal... oooooops References: <87550ef1.0203050846.2166835e@posting.google.com> Message-ID: Gerhard H?ring scribbled with his keyboard: > Le 06/03/02 ? 23:41, Jonathan Gardner ?crivit: >> [...] >> Your init.d script will be written in sh, not python. It would be a >> horrible idea to write an init.d script in python. > > I can't see why writing an init script in Python would be a bad idea. > Care to explain? > Let me put it another way. What language would you choose to write a program that works with a lot of text? You'd probably choose perl to do that because perl makes it really easy to work with text and such. What if you just wanted to do a simple substition? You'd go with awk, because that is what awk is good for. Shell is really good for writing things like init scripts. All the other init scripts are written with shell. Python just doesn't compare to shell when all you want to do is start or stop or send signals to a process. That's what shell was built for. Writing an init script in Python makes about as much sense as writing your init script in Tcl or C++. And think of the sysadmins... Jonathan From sandskyfly at hotmail.com Thu Mar 7 13:13:00 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 7 Mar 2002 10:13:00 -0800 Subject: CGIHTTPServer windoze hair-loss program Message-ID: Hi folks, I've been trying without some success to get CGIHTTPServer working with windows XP (or win2k) and Python 2.2 Simply put, I can't get the POST method to work as desired in CGIHTTPServer. Or maybe my code is buggy... The following is true of my particular situation: - The script is run correctly when executed (1)directly from the browser address bar or (2) from the commandline. (1) So after running cgiserve, if I manually type "http://localhost:8000/cgi-bin/testcgi.py?a=1" into the browser I get the correct output which is: -output---------------------------------------------------------------- Input: a --> 1 Finished! ----------------------------------------------------------------------- (2) Equally if I run the testcgi.py script from the commandline e.g. "python testcgi.py a=1" I also get correct output. - However, when I click on the submit button on the html form while running CGIHTTPServer the interpreter doesn't execute the script, nor does it pass values, and all I get is a "The page cannot be displayed" error. Subsequently hitting refresh on the browser then runs the script correctly, albeit without any values passed. Here is the test code: cgiserve.py -------------------------------------------------------------------------- from CGIHTTPServer import test as serve if __name__=='__main__': serve() -------------------------------------------------------------------------- test.html -------------------------------------------------------------------------- CGI Test
    -------------------------------------------------------------------------- cgi-bin\testcgi.py -------------------------------------------------------------------------- #!python import cgi print "Content-Type: text/plain\n\n" form = cgi.FieldStorage() for name in form.keys(): print "Input: " + name + " --> " + form[name].value + "\n" print "Finished!" -------------------------------------------------------------------------- Log output while running cgiserve.py -------------------------------------------------------------------------- C:\src\tst\>cgiserve Serving HTTP on 0.0.0.0 port 8000 ... localhost - - [07/Mar/2002 20:17:38] "GET /test.html HTTP/1.1" 200 - localhost - - [07/Mar/2002 20:17:47] "POST /cgi-bin/testcgi.py HTTP/1.1" 200 - localhost - - [07/Mar/2002 20:17:47] command: C:\Engines\Python22\python.exe -u C:\src\tst\cgi-bin\testcgi.py "" localhost - - [07/Mar/2002 20:17:47] CGI script exited OK -------------------------------------------------------------------------- Now is there something in particular that I'm doing wrong here. I'm kinda pulling my hair out by now. )-; Any help would be greatly appreciated. Many Thanks, Sandy From logiplexsoftware at earthlink.net Fri Mar 15 13:09:58 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 15 Mar 2002 10:09:58 -0800 Subject: Windows Installation In-Reply-To: References: <7gdk8.277$ID.1679@news.hananet.net> <3C917E97.E615E316@engcorp.com> Message-ID: <20020315100958.639888ba.logiplexsoftware@earthlink.net> On 15 Mar 2002 05:35:15 GMT Gerhard H?ring wrote: > The best solution to this problem is to give in and get a damn Windows > box. Even a virtual one with VMWare or Bochs will do. AFAIK Bochs can > run at least Windows 95 and it even runs on non-x86 hardware. I use VMware 2.0 at work and 3.0 at home and found it to be excellent. I've had some stability problems with 3.0 (although this may be the result of other factors - later Linux kernel versions, Athlon CPU, keyboard/chair interface, etc). At work, VMware 2.0 has never crashed on me and performance is excellent on a PIII 800 running Win2k, and it's far preferable to having a dual-boot system. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From guido at python.org Sat Mar 30 13:09:54 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 18:09:54 GMT Subject: PEP 285: Adding a bool type References: Message-ID: <3CA60068.FF38A83D@python.org> [me] > > Tim must be missing something. The obvious way to turn a bool b into > > an int is int(b). Having to import the obscure 'operator' module for > > this purpose is backwards. (IMO there's almost *never* a reason to > > import that module anyway.) [Ralph] > I thought Tim was trying to map a range of integer values onto just 0 > and 1 as ints, not False and True, where as you're suggesting he just > wants to get an int from a boolean. I think he has an expression like > day_of_month, e.g. 30, and wants a 0 or 1 from it. I should've said int(bool(x)) for any expression x. When I wrote int(b) I meant b to be a value that was already a bool. --Guido van Rossum (home page: http://www.python.org/~guido/) From gcordova at hebmex.com Wed Mar 27 16:00:08 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 27 Mar 2002 15:00:08 -0600 Subject: The Python Way Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689E9@SRM201002> > Thinking of automatic locking concepts, has there been a PEP for > synchronized objects like Java? > > class Snorf: > def __init__(self): > self.lock = lock.lock() > > def doSomething(self,x) synchronize(self.lock): > code > > It would be nice if the synchronize parameter could be an instance, > class or module lock. Hmmm... I believe this would be easy to do using metaclasses, but since I'm no meta-wizard, I'll leave it to one of the great bots to illuminate us with a simple proof of concept. -gustavo From thomas at gatsoft.no Fri Mar 1 02:55:18 2002 From: thomas at gatsoft.no (Thomas Weholt) Date: Fri, 01 Mar 2002 07:55:18 GMT Subject: Simple threading thing References: Message-ID: I was calling the maintanence-thread's run()-method, not its start()-method. Thanks to Cliff Wells for helping me with that. Here's the code in question for later use : import time, threading class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while 1: time.sleep(10) print "Doing something" class t: def __init__(self): self.worker = MyThread() def serve(self): self.worker.start() # was self.worker.run() while 1: time.sleep(5) print "Main class serving ..." x = t() x.serve() Now it works just great! Thanks for all your help, interest and input. Best regards, Thomas Weholt "Martin v. Loewis" wrote in message news:m3u1s19qhu.fsf at mira.informatik.hu-berlin.de... > "Thomas Weholt" writes: > > > I need a thread, no forking. Should run in Linux and Win32. I need a thread > > that functions in the background, running beside the main server, with a > > reference to the main server so it can maintain states etc. in it. The > > purpose of the process is to mainly remove expired sessions ( remember this > > is a webserver ), log certain values and monitor the server, and work as > > sort of a janitor. > > > > Does that make it any clearer? > > Not really. The main process starts. What happens next? I interpret > your posting as > > - creates a new thread, to observe the main thread > - the main thread should continue to run, but doesn't > > Is that correct? How do you know it does not run? > > If this are all the fact, it is really hard to believe. There must be > details that you've omitted. > > Regards, > Martin From t.kloppenburg at billiton.de Tue Mar 26 08:41:44 2002 From: t.kloppenburg at billiton.de (Tjabo Kloppenburg) Date: Tue, 26 Mar 2002 14:41:44 +0100 Subject: list element of a class with the for statement In-Reply-To: References: Message-ID: or, in python 2.2 syntax: > def __getitem__(self,i): > return self.__records[i] def __iter__(self): self.ptr = 0 return self def next(self): if self.ptr < (len(self.__records) - 1): self.ptr = self.ptr + 1 return self.__records[self.ptr] else: raise StopIteration tk. From rjones at ekit-inc.com Fri Mar 29 18:42:22 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sat, 30 Mar 2002 10:42:22 +1100 Subject: Anyone need a program written? In-Reply-To: <20020329162758.GA1370@blackscarab> References: <3ca43ef4.3666136@news.tudelft.nl> <20020329162758.GA1370@blackscarab> Message-ID: <200203292342.XAA17883@crown.off.ekorp.com> On Sat, 30 Mar 2002 03:27, cruciatuz wrote: > On Fri, Mar 29, 2002 at 10:20:33AM +0000, Fused wrote: > > Can anyone think of a program that I could build that would actually > > have use to someone (you?)? I'm trained in Delphi, know some Java and > > rudimentary C, so the programs don't need to be newbie-easy ( I like a > > challenge: the greater the challenge, the faster I'll learn ;-) ). > > a programming game like realtimebattle, written entirely in python, > would be very cool. See http://www.pythonpros.com/gstein/war/ Richard From SWidney at ci.las-vegas.nv.us Wed Mar 27 22:51:02 2002 From: SWidney at ci.las-vegas.nv.us (Scott Widney) Date: Wed, 27 Mar 2002 19:51:02 -0800 Subject: list comprehension question Message-ID: Jumping in a little late, and moving backwards in time, but... > From "I, Robot" and others, the Three Laws of Robotics. (I > just happen to have been rereading this on the weekend, > so I guess the thought stuck.) > > First Law was "A robot may not injure a human being or, through > inaction, allow a human to come to harm". > > Second: "A robot must obey the orders given it by human beings > except where such orders would conflict with the First Law". > > Third: "A robot must protect its own existence as long as such > protection does not conflict with the First or Second Law". > > * * * Actually, it's Four Laws: you've forgotten the Zeroth Law. Roughly paraphrased (it's been something like 10 years since I read it), mankind precedes men. Something like, "A robot may not injure humankind or, through inaction, allow humankind to come to harm". The needs of the many outweigh the needs of the few (or the one). In light of that... > > PS. tell the bot I'm sorry I doubted the correctness of his code > > If it's a bot, you don't have to apologize. Bots feel no emotion. > > And you're safe, too -- remember the First Law. > > -objectifying-tim-ly yr's, > Peter ...might want to reconsider the advice. If the bot tho't that the list would be better off without certain noxious comments, or the innocuous for that matter.... Hmm... Scott From sab at NOSPAM.freeuk.com Wed Mar 20 19:28:28 2002 From: sab at NOSPAM.freeuk.com (G. Willoughby) Date: Thu, 21 Mar 2002 00:28:28 -0000 Subject: tkinter menuitem question References: Message-ID: I've just done this tonight with this code: [snip] class GenericCallback: def __init__(self, callback, *firstArgs): self.__callback = callback self.__firstArgs = firstArgs def __call__(self, *lastArgs): apply(self.__callback, self.__firstArgs + lastArgs) [/snip] [snip] self.zone=Zones("D:\DAoC") self.zonemenu = Menu(self.menubar, tearoff=0) self.albionmenu=Menu(self.menubar, tearoff=0) self.midgardmenu=Menu(self.menubar, tearoff=0) self.hibernianmenu=Menu(self.menubar, tearoff=0) for x in range(len(self.zone.locations)): menuName=self.zone.locations[x][0]+" : "+self.zone.locations[x][1] zoneNumber=int(self.zone.locations[x][0]) if zoneNumber<100: self.albionmenu.add_command(label=menuName, command=GenericCallback(self.zoneSelected, zoneNumber)) elif zoneNumber>100 and zoneNumber<200: self.hibernianmenu.add_command(label=menuName, command=GenericCallback(self.zoneSelected, zoneNumber)) elif zoneNumber>200 and zoneNumber<300: self.midgardmenu.add_command(label=menuName, command=GenericCallback(self.zoneSelected, zoneNumber)) self.zonemenu.add_cascade(label="Albion", menu=self.albionmenu) self.zonemenu.add_cascade(label="Midgard", menu=self.midgardmenu) self.zonemenu.add_cascade(label="Hibernia", menu=self.hibernianmenu) self.menubar.add_cascade(label="Zone", menu=self.zonemenu) [/snip] [snip] # Zone menu commands def zoneSelected(self, zone): print zone [/snip] make sense? G. Willoughby "Ken Guest" wrote in message news:mailman.1016634429.30440.python-list at python.org... > ok, I might be way off here but is there a way with a collection of > Tkinter menuitems that all have their callbacks set to be the one > function to determine which menuitem was clicked on? > > for example, given the snippet: > > > menubar1=Pmw.MenuBar(vbox1) > menubar1.addmenu('TopLvlMenu','this is a tooltip') > menubar1.addcascademenu('TopLvlMenu', 'Item#6','tool tip for > item 6') > menubar1.addmenuitem('Item#6', 'command', '', > label="item#7",underline=0, command=menu_item_selected) > menubar1.addmenuitem('Item#6', 'command', 'oct', label="item#8", > underline=0, command=menu_item_selected) > menubar1.addmenuitem('TopLvlMenu', 'command', 'naoi', > label="item#9", underline=0, command=menu_item_selected) > menubar1.addmenuitem('TopLvlMenu', 'separator', '') > menubar1.addmenuitem('TopLvlMenu', 'command', '', > label="item10", underline=0, command=menu_item_selected) > menubar1.pack(expand=NO, side=TOP) > > > Is it possible to give these menuitems the one handler function/callback > function that can determine which item was clicked on? > The reason for asking is that I have a dynamically generated cascading > popup menu and need to know which menuitem has been selected. > > I have thought of displaying a very small dialog box which would only > contain a combobox and nothing else. the dialog box would be unloaded > once the user selects an item from the combobox but this wouldn't really > work as there need to be cascaded entries. > > any ideas? > > k. > > > From joonas at olen.to Wed Mar 6 12:29:13 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Wed, 06 Mar 2002 19:29:13 +0200 Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> <3C84E363.6020106@olen.to> <3C84EBED.8090607@bath.ac.uk> Message-ID: <3C8651E9.493CDA64@olen.to> Simon Willison wrote: > > Joonas Paalasmaa wrote: > > Simon Willison wrote: > > > >> I've written a simple Python script to scan a bunch of URLs for "live" > >> sites and grab the title of those pages. It works by using popen() to > >> call lynx and analyse the HTTP response: > >> > >> ----------------------------------------------------------------- > >> > >> command = "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~"+user+"/" > > > > > > Use: > > > > command=["/opt/bin/lynx","-mime_header","http://www.bath.ac.uk/~"+user+"/"] > > > > for better security. > > I'm a Python newbie :) How does that makes things more secure? If you pass a string to os.popen as the first argument, the process is envoiked by by running the argument in shell. That can cause problems if the string is composed from non-safe variables. Imagine situation where variable 'user' is "; rm -fR ~/; echo ". That causes command "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~; rm -fR ~/; echo /" to be run in shell. But if a list is passed to os.popen, os.popen will run a program named in the first item of the list with the rest of the list as arguments. - Joonas From evebill8 at hotmail.com Thu Mar 21 17:24:09 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Thu, 21 Mar 2002 22:24:09 GMT Subject: Telnet References: Message-ID: Thanks! "\r\n" is the key. It works after I added into the write(). functon Okay, now I have 2 more questions. 1) How can I save the returned data into a list? I tried to use the read_all() function, but it just stops there. tn.read_until("ending line") lines = [] lines = tn.read_all() 2) I was also trying to do this, tn.read_until("beginnig line to grap") lines = [] lines = tn.read_until("ending line") for line in lines print line But it prints one character in each line Any input will helps,. thanks! Billy Ng "Chris Liechti" wrote in message news:Xns91D8D7543A398cliechtigmxnet at 62.2.16.82... > "Billy Ng" wrote in news:yAqm8.1723$Tk.98335 > @newsread1.prod.itd.earthlink.net: > > I am trying to write a telnet client program. Here is the code: > > > > ID = "123445" > > PASSWORD = "333" > > > > try: > > tn = telnetlib.Telnet() > > tn.read_until("Please enter your id? ") > > tn.write(ID+"\n") > > tn.read_until("Enter your password? ") > > tn.write(PASSWORD+"\n") > > print tn.read_all() > > tn.close() > > except: > > tn.close() > > print 'connection failed' > > tn.close() > > > > It stops after the ID was written. If I use the actual telnet > > client, it returns "Enter your password? " after my ID is > > submitted. why does not tn.read_until() find the "Enter your > > password? " string ? Is there any other way to handle the password > > prompt? > > don't write the entire prompt in read_all. insteand use > read_all("word?") > this way you circumwent problems with additional spaces, case atc. > > and make sure that your server works with just a "\n", maybe it needs > a "\r\n". > > HTH chris > > -- > Chris > > From dsavitsk at e-coli.net Wed Mar 27 00:08:26 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 27 Mar 2002 05:08:26 GMT Subject: python, cvs, win32 -- slightly ot Message-ID: i have registered and had approved a project on sourceforge. never having used cvs before, i am looking for some help on how to use cvs with python files on win2k. any links on where to look? project-to-be-anounced-as-as-soon-as-possible ly 'yrs doug From mcherm at destiny.com Fri Mar 22 13:11:55 2002 From: mcherm at destiny.com (Michael Chermside) Date: Fri, 22 Mar 2002 13:11:55 -0500 Subject: Popular style document? Message-ID: <3C9B73EB.8020803@destiny.com> >> IMO the requirement to say self everywhere in methods is the worst >> feature of python. > > How come Python doesn't have an "automatic" this-variable, like C++ or > Java? The short answer is quite simple: that's how Guido likes it. A much better answer would be to point out that LOTS of people like it. Also there are others who DISLIKE it, and probably a few who don't really care (although for some reason they never seem to get into these debates ;-)), but if you accept that there are some advantages to "automatic" access to instance variables like C++/Java and other advantages to "explicit" access like Python, then it shouldn't come as a surprise that there are some languages of each time. Python just happens to fall into the category that requires you to be explicit. To really appreciate this, of course, you'd like to hear what some of the advantages of each approach are... here's my brief attempt to summarize a few important points: Advantages of "Automatic" access to instance variables: * Less typing. * Somewhat more convenient to use objects (because you don't have to type "self." in front of instance variable accesses. Mostly about there being less typing.) Advantages of "Explicit" access to instance variables * You never get confused about where a variable came from. A simple search through the text of the file will identify where it was defined. With "automatic" access, it could be an instance variable of a superclass defined elsewhere. * It's easy to tell instance variables apart from local variables (usually not a big deal, but sometimes (eg: while worrying about multi-threaded behavior) it can be). * Functions and Methods have a VERY simple relationship... methods are just functions that take an instance as their first parameter. This allows you to do things like "myObject.getFoo = myGetFooFunc", to create a new method. I'm not expecting this list of advantages to convince anyone, but if you understand where other people are coming from, you can better understand why this feature/misfeature would be found in a language. -- Michael Chermside From BgPorter at NOartlogicSPAM.com Wed Mar 20 10:41:37 2002 From: BgPorter at NOartlogicSPAM.com (Brett g Porter) Date: Wed, 20 Mar 2002 15:41:37 GMT Subject: Java and Python References: Message-ID: wrote in message news:mailman.1016636073.1372.python-list at python.org... > On Wed, 20 Mar 2002, Peter Hansen wrote: > > > The problem I have with someone learning lots of languages is that most of > what I have seen is that they never go beyond a surface level > understanding of the language. So you end up seeing people that can > essentially write C in any language or java etc. However in order to be > really productive you need to know a language and know it very well. I > would rather see someone that can demonstrate higher level mastery with > one language then a surface level with many. You can't get to more > advanced features until you understand all of the basic features. However > once you learn those features you are in a better position to apply them > in another language. The way that a former boss described one of my co-workers was that his code looked like he sneezed, and C++ tokens came out on the screen. The thing that you have to get used to is that you aren't going to get hired for jobs that require knowledge and experience outside of programming that you lack. If you don't have a solid math background, you are not going to get hired to do heavy DSP programming, or develop 3d graphics engines. I don't have a database background, so I know that I'm not going to get jobs that require that (that one is intentional). Figure out what kind of work you want to do and put yourself in a position to be able to do it. Don't worry about how long it will take -- you'll be 4 years older in 4 years whether you spend that time learning things or not. Developing a skill set because someone told you that it was a path to a 'good job' is setting you up to be like people I knew in college who studied business (or law or medicine, or...) because some counselor had told them it was the path to the good life, not because they were interested in the field. They hated 4 years of college (except for the girls and drinking) and I can't imagine what kind of hollow, miserable, time-to-make-the-donuts kind of life they have now. From sholden at holdenweb.com Thu Mar 28 08:33:06 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 28 Mar 2002 08:33:06 -0500 Subject: problems with circular references References: Message-ID: "jimh" wrote in message news:a7tgkv$t3m$1 at web1.cup.hp.com... > > [...] > > I will have to think about that one. When a class accesses the > MessageCatalog, it may be requesting message text from _other_ classes' > errors. Also, these are often called from cgi scripts, so they are run as a > one-shot deal. Also(!), the case of an error is (theoretically) uncommon > and the MessageCatalog is only instantiated if an error occurs. That way, > if no error occurs, there is no overhead with importing the MessageCatalog. > Bear in mind that the import will only cause the module to be executed once no matter how many times it is imported. So importing it may not be as much of an ovberhead as you imagine (especially since you seem to be happy to import fifty other modules to make up your program). regards Steve From mrlee at davesupply.com Tue Mar 5 16:40:34 2002 From: mrlee at davesupply.com (Mr.Lee) Date: Tue, 05 Mar 2002 21:40:34 GMT Subject: Updating Python...Newbie alert! References: Message-ID: How new am I? I am this new: when I typed 'make install' went into it's proper place! I didn't quite finish the proper procedures. Ya lern sumthin' new ev'ryday. Thanks, Lee Chris Liechti wrote: > "Mr.Lee" wrote in news:n3ah8.112697 > $Hu6.28510292 at typhoon.neo.rr.com: >> Hi all, >> Being quite new to Linux, I am having a bit of a problem >> when it comes to updating my installed version of Python(1.5.2) to >> the version that I have now(2.2). >> My problem is that I compiled Python in the directory that >> I downloaded and now I don't know where to put all of the files >> that were generated! It works, I ran the tests and it all came out >> fine, but I just don't know where to put the files for maximum >> efficiency. > > usualy one does "./configure;make;make install" and the "make > install" places the files where they belong (in subdirectories of > /usr/local/ usualy) > > chris > -- ------------------------------------- Dave Supply Company Industrial Diesel Power & Generators (330) 798-0215 Phone www.davesupply.com From r.salz at verizon.net Wed Mar 20 23:31:39 2002 From: r.salz at verizon.net (Rich Salz) Date: Thu, 21 Mar 2002 04:31:39 GMT Subject: Java and Python References: Message-ID: <3C996234.9090506@verizon.net> Cameron Laird wrote: > I'm still looking for a way to get this point across: the > answer to many questions is, "There's no such thing." No > one plays the role for Python that Sun plays for Java. Hmm.. Both provide a reference implementation, both provide a community process for suggesting improvements (but still retain the right to do what they think best)... what's missing? /r$ From p.magwene at snet.net Sat Mar 9 17:13:29 2002 From: p.magwene at snet.net (Paul M) Date: Sat, 09 Mar 2002 22:13:29 GMT Subject: ANN: disipyl - a 2D and 3D Python plotting library Message-ID: DESCRIPTION: ----------- disipyl is an object-oriented wrapper around the DISLIN plotting library. DISLIN is a powerful and flexible multiplatform (Win32, Unix, Linux, etc.) library designed for displaying scientific data. DISLIN's author, Helmut Michels, has made available a DISLIN plotting extension for the Python programming language (see http://www.linmpi.mpg.de/dislin/ for more details). disipyl provides a set of classes which represent various aspects of DISLIN plots, as well as providing some easy to use classes for creating commonly used plot formats (e.g. scatter plots, histograms, 3-D surface plots). A major goal in designing the library was to facilitate interactive data exploration and plot creation. Documentation, a tutorial, and a demo program are included. The library has been tested on Win32, Linux, and FreeBSD, but I anticipate that it should work on any platform which can make use of Python, NumPy, and the DISLIN python extensions. Feedback, comments, and critique are gladly accepted (email: paul.magwene at yale.edu). VERSION: ------- This is release 0.5 of disipyl. HISTORY: ------- disipyl is a complete re-write of an earlier plotting library called pxDislin. While similar in spirit, disipyl is much more flexible and much more easier to use than pxDislin. URL: ---- You can find disipyl at: http://pantheon.yale.edu/~pmm34/disipyl.html From skip at pobox.com Mon Mar 18 16:07:06 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 18 Mar 2002 15:07:06 -0600 Subject: dealing with paths, multiple OS versions, cgi's In-Reply-To: <20020318192717.6A92617E88@juniper.its.swarthmore.edu> References: <20020318192717.6A92617E88@juniper.its.swarthmore.edu> Message-ID: <15510.22266.778563.888982@beluga.mojam.com> Glenn> What I need is some method for stripping off the basename Glenn> regardless of the browser OS. How about something like: >>> import re >>> re.sub(r".*[\\/:]", "", r"c:\temp\file.doc") 'file.doc' >>> re.sub(r".*[\\/:]", "", r"/home/user/file.doc") 'file.doc' (":" should catch mac paths I think.) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From daniel.dittmar at sap.com Thu Mar 14 12:53:32 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 14 Mar 2002 18:53:32 +0100 Subject: Why I think range is a wart References: Message-ID: > for item1, item2 in list1, list2 > # lots of code here class ZipOnTheFly: def __init__ (self, *lists): self.lists = lists self.elementSize = len (lists) def __getitem__ (self, index): result = [None] * self.elementSize for i in range (self.elementSize): result [i] = self.lists [i] [index] return result for elem0, elem1 in ZipOnTheFly (list0, list1): This at least avoids some memory overhead if list0 and list1 are large. Actually, the iterator based version looks cleaner (and doesn't iterate over the indicees, which was the start of this thread) def __init__ (self, *lists): self.iters = map (iter, lists) def next (self): return [elem.next () for elem in self.iters] Daniel From s.ernst at web.de Fri Mar 15 10:49:58 2002 From: s.ernst at web.de (Sascha Ernst) Date: Fri, 15 Mar 2002 16:49:58 +0100 Subject: further infos References: Message-ID: please have a look at my posting one line below sorry for the misunderstanding, again "Michael Stenner" schrieb im Newsbeitrag news:mailman.1016198905.10172.python-list at python.org... > On Fri, Mar 15, 2002 at 02:11:43PM +0100, Sascha Ernst wrote: > > 1. "command not found" is the error message. how can I get more detailed > > infos? > > 2. the dev tools are ok, I compiled Ruby some days ago successfully > > whaaa? > > 1) this is a python list... not a ruby list... > > 2) I'll try and employ my ESP anyway: > > "command not found" is a common shell error. Are you running > (python or ruby, whatever) under unix? If so, do you have the > proper shebang? > > For example, your files should probably start with > > #!/usr/bin/env python > > If this isn't there, the file will usually be interpreted as a > shell script and almost certainly throw errors. This can be > unpleasant if the first non-comment is an import :) > > 3) you get more detailed infos when you give us more detailed infos :) > > -Michael > -- > Michael Stenner Office Phone: 919-660-2513 > Duke University, Dept. of Physics mstenner at phy.duke.edu > Box 90305, Durham N.C. 27708-0305 > From emile at fenx.com Sat Mar 30 11:33:52 2002 From: emile at fenx.com (Emile van Sebille) Date: Sat, 30 Mar 2002 16:33:52 GMT Subject: [Python-Dev] RE: PEP 285: Adding a bool type References: Message-ID: [is this an April fool's joke? I hate it when I get caught in one of these! Here's my reply anyway, just in case...] -1*0 With my memory not reaching as far back as others, I thought I'd look into prior discussions on this. I started at http://groups.google.com/groups?q=boolean+type+%22not+not%22+group:comp. lang.python expecting that the conjunction of asking about 'boolean' and 'type', with the expected reply to use the pydiom 'not not' would land me right in the thick of things. I got a single page. There isn't a history of need here. I then scanned the 2.2 standard library (thinking of it as the standard bearer for python code) for true/false usage, as Guido cited standardization of usage as a primary objective. I found a _false, a reference in ConfigParser to states, and a Boolean class in xmlrpclib. Anyone can today import boolean, True and False from xlmrpclib and have this functionality and standardization. Enforcing it's use, in light of the backwards-compatibility allowances included in the PEP, is no different than enforcing the use of True or False in code as long as 0 and 1 suffice. On the down side, this PEP breaks code by changing the outcome of virtually *all* comparisons. Hopefully in non-code-breaking fashion. And that the change is restricted to the 28 identified built-ins. And that the mods to them do not introduce bugs or unforeseen incompatibilities. Tall order for what had been expected to be a clean-up release. -- Emile van Sebille emile at fenx.com --------- From ira at quasarlabs.com Mon Mar 11 08:19:27 2002 From: ira at quasarlabs.com (Ira Voitashevskaya) Date: Mon, 11 Mar 2002 15:19:27 +0200 Subject: rpm-python question Message-ID: <3C8CAEDF.697CEA3F@quasarlabs.com> Hi! I need to use rmp module (rpm-python-4.0.1-0.20). Where can I get docmentation for it? Thank you. Best regards. Ira Voitashevskaya. From paul at boddie.net Mon Mar 18 05:59:49 2002 From: paul at boddie.net (Paul Boddie) Date: 18 Mar 2002 02:59:49 -0800 Subject: Converting relative URLs to absolute References: Message-ID: <23891c90.0203180259.26e87496@posting.google.com> wrote in message news:... > > Rather than add a new module, why not add more functionality to the > urlparse module in the standard distribution? (what functionality do you > need beyond what's already there, anyway?) I wouldn't want to add a new module - it's most interesting to tidy up what's already there, adding better "split" functions to urllib (and urllib2), and adding some "join" functions too. I certainly wouldn't advocate adding a huge dependency on some other library, even though some interesting candidates exist. Such improvements are applicable to other Internet modules in the standard library, too - nntplib might be a good low-level vehicle for accessing news servers, but just about anyone who is likely to be using NNTP is going to be wrapping calls to that module inside meaningful abstractions. Paul From James_Althoff at i2.com Wed Mar 6 14:41:13 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 6 Mar 2002 11:41:13 -0800 Subject: Pep 276 - if 6 were 9 Message-ID: An interesting observation. Plus I really like the Hendrix reference . Jim ===================================== If, in the beginning, Guido opted to call 'in' 'of', would there be a question of iterating over an integer? For example, for each of range(6): for each of mylist: for each of 6: I'm not advocating a change here, but just wondering how thinking in terms of 'in' vs 'of' might influence the debate. Or am I too far on the supporting side to appreciate that this has no bearing on it what-so-ever-thank-you-very-much? ;-) -- Emile van Sebille From ljohnson at resgen.com Wed Mar 6 10:50:16 2002 From: ljohnson at resgen.com (Lyle Johnson) Date: Wed, 6 Mar 2002 09:50:16 -0600 Subject: output file name for *.py References: Message-ID: > swig -python -c++ -shadow -o path/interface_wrap.cxx interface.i > > This creates two files: > > path/interface_wrap.cxx > > and interface.py in the *local* directory. > > How can I specify a different output directory for interface.py? Which version of SWIG is this? The current development version of SWIG (from CVS) places the *.py file in the same output directory as the *.cxx file. > According to Lutz, Programming Python, 2nd edition, p. 1139, > also a third file interface_wrap.doc should be created. > Why is this file not created? Do I need an additional option? The old documentation system from SWIG 1.1 has been disabled/removed for SWIG 1.3. It may reappear at some point. From tim.one at comcast.net Fri Mar 1 01:23:59 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 01 Mar 2002 01:23:59 -0500 Subject: Can somebody kill getpathp for me? In-Reply-To: <00bb01c1c0e1$d9045940$0101010a@local> Message-ID: [Chris Gonnerman] > In the PC subdir of the Python-2.1.2 build directory is a module > called getpathp.c, which sets up the initial sys.path value. It > is well known by Python programmers on Windows that the sys.path > initialization includes directories plucked from special registry > keys... unless you are using the PythonWare version. Or the PythonLabs distribution: while the core installer does set up a registry entry containing "the usual" Python path, it *normally* never uses it. Read the long comment block at the start of getpathp.c, and this time believe that it means what it says . Note that the core installer never sets up what the comment block calls "'application paths' - that is, sub-keys under the main PythonPath registry key". If there aren't any application paths, then, as the rest of the comment block says, the main PythonPath key is ignored, unless a "Python Home" isn't given by a PYTHONHOME envar and can't be guessed from the python.exe path. > I thought, great, I can use this (the PythonWare version) to create > Python runnables on CD-ROM; but now I discover a fly in the ointment. > If the computer already has an installed Python interpreter, the > paths set in the registry are added, and BEFORE the paths from the > PythonWare PYROOT variable are added. AFAIK PythonWare doesn't ship with a custom getpathp.c, and neither does ActiveState, so AFAIK the comment block applies to all Python installations. The "PythonWare PYROOT variable" is news to me, google hasn't heard of it either, and I find no mention of PYROOT in my PythonWare PY21 installation. Setting a PYROOT envar has no visible effect on sys.path when I run under PY21 either. That's a long-winded way of saying I think you must be confused . Have you tried setting PYTHONHOME? If, e.g., I set PYTHONHOME to \Python22, then execute python while *in* my \Python21 directory (these both referring to PythonLabs distros), then Python 2.1.2 comes up with sys.path pointing entirely at Python 2.2 directories. This is insane, but shows that PYTHONHOME works the way getpathp.c says it works. > Gah. > > What I want is a version of either python.exe or python21.dll > (whichever contains the offending getpathp.c module) with the > registry-probing code disabled. If that's what you really want, you'll have to edit getpathp.c and compile your own Python. > Ideally it should still apply the paths from PYROOT (basically in this > case it must). Python doesn't look at any such envar on any platform. Maybe that's why setting PYROOT isn't doing you any good . Try PYTHONHOME. From r.weisser at att.net Thu Mar 28 17:30:46 2002 From: r.weisser at att.net (Robert Weisser) Date: Thu, 28 Mar 2002 22:30:46 GMT Subject: Newbie Question about os.removedirs() Message-ID: Hello: A am new to Python and to newsgroups. In fact this is my first post. Since my backup batch file from my Win98 computer would not work on my new Win2000 computer (no more deltree), I wrote the following backup Python script (my first not totally trivial Python program). I wanted to make it as Pythonesque as possible, but I had a problem with the os.removedirs function. It would not delete a directory tree if the tree contained a read only file. Actually it may have deleted part of the tree before failing. I should have checked but didn't. I assume os.removedirs is calling os.remove. At the interactive prompt I tried os.remove on an individual read-only file, which also failed. The error is OSError: [Errno 13] Permission denied: filename. If I have to, I will write a recursive function which uses os.remove in a try block. If os.remove fails I will change the mode of the file. I assume Python supports the equivalent of unix chmod (haven't checked yet). However, it would be nicer if there is an option to os.removedirs so that I won't have to do this. Because I am new to Python (although not to programming) comments on the code would also be appreciated. I apologize for its length. IMPORTANT (to me, anyway) NEWBIE QUESTION: What does Debian mean? Here is my code with sample input files following. The problem statement is 16 lines from the end. # BackupToZip.py """ Backup selected directories or files to the zip drive, normally e: Files and directories used: COMPFILE - contains name of computer being backup up DIRFILE - contains list of dirs to backup FILEFILE - contains list of files to backup DRIVEFILE - contains letter of zip drive (target drive) INDICATOR - a file on the backup desk which confirms that the disk is a backup up disk for this computer. For example, if the computer is named bentley, there should do a file named bentley_backup_disk on the backup disk. If it is not there, the program warns the user and then offers to create the indicator file for the next time. SCRIPTDIR - directory containing this program and the three files above """ # improvements needed: # use os.removedirs(dirName) instead of # os.system('rmdir /s/q ' + quoteit(dirName)) # make the directory listing for the user portable # make it possible to exclude files and directories from # the backup # the commented out print statements were used for debugging import glob, os, sys, string, shutil COMPFILENAME = 'CompName.txt' # this file contains name of computer, # e.g. bentley DIRFILENAME = 'DirList.txt' # this file contains the list of # directories to be backed up FILEFILENAME = 'FileList.txt' # this file contains the list of # individual files to be backup up # (may contain wild cards) DRIVEFILENAME = 'ZipLetter.txt' # this file contains the drive letter # of the zip drive SCRIPTDIR = sys.path[0] # directory containing this script INDICATORSUFFIX = '_backup_disk' # used to construct indicator # file name, e. g. # bentley_backup_disk LINE = '-' * 70 def getListFromFile(fileName): """ read a list from a file. ignore comments and blank lines. """ lines = open(fileName).readlines() return cleanLines(lines) def getLetterFromFile(fileName): """ get one letter from a file. ignore comments and blank lines. """ lines = open(fileName).readlines() lines = cleanLines(lines) return lines[0][:1] def getFirstLineFromFile(fileName): """ get a name from a file. ignore comments and blank lines. """ lines = open(fileName).readlines() lines = cleanLines(lines) return lines[0] def cleanLines(lines): """ remove newlines, comments, and blank lines from a list of lines """ res = [] for line in lines: line = removeComment(line).strip() # remove comments and white space if line: # ignore zero length lines res.append(line) return res def removeComment(line): """ remove comments from lines. a comment starts with a '#' and continues to the end of the line. """ try: i = line.index('#') line = line[:i] except ValueError: pass return line def caseInsensitiveCompare(arg1, arg2): "case insensitive compare for use with filter and sort" return cmp(string.lower(arg1), string.lower(arg2)) def getAns(msg, *values): """ Prompts using msg and the items in values. Reads in an answer until the user enters one of the items in values. Returns the answer. Example: when called as getAns("junk", "y", "n"), the prompt is "junk (y/n)? ". The items should be single characters. Only the first letter of the response is used. """ valString = string.join(values, '/') ans = None while ans not in values: ans = string.lower(raw_input(msg + ' (' + valString + ')? ')[0]) return ans def backupDir(dirName, driveRoot): """ copies the dirName directory to the root directory of the target drive. """ print LINE if not os.path.isdir(dirName): print 'can not backup: ', dirName, '(not found or is not a directory)' return targetName = driveRoot[0:2] + dirName[2:] targetDir = os.path.dirname(targetName) createDir(targetDir) print 'backing up: ', dirName print ' to: ', targetName shutil.copytree(dirName, targetName) # the non-Python method which I used at first: # xcopyCmd = 'xcopy /s/e ' + quoteit(dirName) + ' ' + quoteit(targetName) # print xcopyCmd # rc = os.system(xcopyCmd) # print 'Return code from xcopy: ', rc def backupFile(fileName, driveRoot): """ first run glob on the fileName to get all files whose names match the fileName pattern, then copy them to the backup drive. """ print LINE fileList = glob.glob(fileName) if not fileList: print 'can not backup: ', fileName, '(not found)' return targetPattern = driveRoot[0:2] + fileName[2:] targetDir = os.path.dirname(targetPattern) createDir(targetDir) print 'backing up: ', fileName print ' to: ', targetPattern for filen in fileList: if os.path.isfile(filen): targetFile = driveRoot[0:2] + filen[2:] print filen print ' -->', targetFile shutil.copy2(filen, targetFile) else: print 'can not backup: ', filen, '(not a regular file)' def createDir(dirName): "create a directory if it does not exist" if dirName != driveRoot and not os.path.exists(dirName): print 'creating', dirName print os.makedirs(dirName) def quoteit(str): "put quotes around a string" return '"' + str + '"' # this function is not used in this program, # although I originally planned to use it. def rmtreeError(func, path, excinfo): "error handler for shutil.rmtree" print `func`, 'error: ', path print excinfo # ----- start of processing ----- # important variables: # delDirList: directories on target drive which will be deleted # delFileList: files on target drive which will be deleted # dirList: directories to back up # fileList: files to back up # read the configuration files print print "Starting backup" os.chdir(SCRIPTDIR) # print 'starting dir:', os.getcwd() backupDrive = getLetterFromFile(DRIVEFILENAME) # drive letter print 'Backup will take place on Drive', backupDrive driveRoot = backupDrive + ':\\' compName = getFirstLineFromFile(COMPFILENAME) # name of this computer print 'Computer name: ', compName dirList = getListFromFile(DIRFILENAME) # directories to back up dirList.sort(caseInsensitiveCompare) # print 'Directories to back up: ', dirList fileList = getListFromFile(FILEFILENAME) # files (patterns) # to back up fileList.sort(caseInsensitiveCompare) # print 'Files to backup up: ', fileList # change directory to the backup drive rc = os.chdir(driveRoot) # I used the Windows dir command here because I wanted # the output to be the familiar Windows dir command output. # I may make this more portable if I start using it elsewhere. print rc = os.system('dir /o') delFileList = os.listdir('.') delFileList.sort(caseInsensitiveCompare) delDirList = filter(os.path.isdir, delFileList) # dirs on target drive # print 'delDirList:', delDirList # which will be deleted delFileList = filter(os.path.isfile, delFileList) # files on target drive # print 'delFileList:', delFileList # which will be deleted indicatorFileName = compName + INDICATORSUFFIX if indicatorFileName in delFileList: delFileList.remove(indicatorFileName) else: print print 'Indicator file', indicatorFileName, 'not found in', driveRoot print 'Are you sure this is a', compName, 'backup disk?' ans = getAns('Do you want to continue?', 'y', 'n') if ans == 'y': print print 'creating file', indicatorFileName indFile = open(indicatorFileName, 'w') # create the indicator file indFile.close() # as an empty file else: print 'Backup cancelled' raw_input('Press to continue:') sys.exit('Program terminated by user request') print print 'WARNING: all files and directories on drive ' + backupDrive + ': except' print ' the file', indicatorFileName, ' will be deleted.' ans = getAns(' Continue', 'y', 'n') if ans == 'n': print 'Backup cancelled' raw_input('Press to continue:') sys.exit('Program terminated by user request') # remove the directories on the backup drive for fileName in delFileList: print 'Removing', fileName os.remove(fileName) # remove the files on the backup drive for dirName in delDirList: print 'Removing directory', dirName rmCmd = 'rmdir /s/q ' + quoteit(dirName) # I had to use non-portable os.system call (see note on os.removedirs line) # print 'rmCmd:', rmCmd os.system(rmCmd) # os.removedirs(dirName) # would not remove a directory # tree with a readonly file in it # finally, do the backup. # first copy the complete directories: for dirName in dirList: backupDir(dirName, driveRoot) # now do the files: for fileName in fileList: backupFile(fileName, driveRoot) print LINE print 'Backup has been completed' raw_input('Press to continue:') ---------------- end of code ------------------- Contents of CompName.txt: # The name of the computer being backed up. # The program checks for a file called compname_backup_disk # on the backup disk and prints a warning if it is not found. bentley ------------------------------------------------ Contents of DirList.txt: # List of Directories which will be copied to the zip drive # The drive letters must be included in the directory names C:\Documents and Settings\Robert Paul Weisser\My Documents C:\My Installations C:\RPW C:\Junk\Stuff C:\Documents and Settings\Robert Paul Weisser\Application Data ------------------------------------------------ Contents of FileList.txt: # Files to backed up. # File name metacharacters are allowed. # The drive letters must be included in the file names C:\Appl1\*.cpp C:\Appl1\*.xls C:\Appl2\*.cpp C:\Appl2\*.xls ------------------------------------------------ Contents of ZipLetter.txt: # The drive letter of the backup drive (normally a zip drive). # Everything after the first character is ignored. E ------------------------------------------------ Thanks, Robert Weisser (r.xweisser at att.net) (take out the x - I see other people doing this so I guess it's a good idea) From bokr at oz.net Tue Mar 19 16:58:42 2002 From: bokr at oz.net (Bengt Richter) Date: 19 Mar 2002 21:58:42 GMT Subject: How to count pixels of a color in an image? References: <6b7cc392.0203191233.26760fc2@posting.google.com> Message-ID: On 19 Mar 2002 12:33:36 -0800, jjv5 at yahoo.com (jjv5) wrote: >A simple question perhaps. Any help is appreciated. >I need to count the number of pixels that are purple or blue-green in >a large image. I can do this with the Image module easily enough, >but it is painfully slow. I do something like this: > >green=0 >purple=0 >dat = im.getdata() >for i in range(len(dat)): > r,g,b = dat[i][0],dat[i][1],dat[i][2] I suspect python will do the unpacking for you, assuming rgb pixels, and you don't seem to be doing anything with i other than indexing. > green = green + (( b>r) and (g>r)) > purple = purple + ((r>g) and (b>g)) These would seem to compute and add a lot of zeroes. Also r>g amd g>r can't be true for both green and purple, so I'd reorder and get some advantage from shortcut evaluation, e.g., combining the above, I'd try: # (untested) green=o purple=0 dat = im.getdata() for r,g,b in dat: if g>r and b>r: green += 1 elif r>g and b>g: purple += 1 After that maybe psyco, or maybe something in the histogram feature can be hooked? >The slow part is the for loop over the image data. Even if the loop >body is empty it still takes about 15 seconds on a fast computer. the >getdata function takes about 3 seconds. Surely there is a better way. >The image >is about 3800 by 3000 pixels. Any suggestions? > > HTH, Regards, Bengt Richter From usenet at thinkspot.net Sun Mar 17 21:32:05 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 18:32:05 -0800 Subject: bug reporting References: Message-ID: On Sun, 17 Mar 2002 19:41:22 -0500, "Arthur Siegel" wrote in comp.lang.python in article : > In thread "Still same bug even with email ver. 1.2" > > Martin writes - > >If you think you found a bug, submit a bug report. > > It could waste time of the developers to have to > weed through false alarm bug reports. One of the > roles of this list is to vet some of these issues. Yes, that is sort of what I am hoping for, when I post stuff here. I've gotten a lot of "submit it as a bug report" responses, more recently. Anyhow, the one in the thread you continued this from...I have now submitted it as a bug report. However, as I continue to work on this problem (sort of trying to see if I can fix it or at least see if I can understand what's causing it), I'm not so sure it will end up to be a bug report after all. It may end up to be a problem in my own code. :/ -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From mlh at vier.idi.ntnu.no Sun Mar 31 19:03:09 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Mon, 1 Apr 2002 00:03:09 +0000 (UTC) Subject: [Python-Dev] RE: PEP 285: Adding a bool type References: <200203301342.g2UDgTE01572@pcp742651pcs.reston01.va.comcast.net> Message-ID: In article , Fred L. Drake, Jr. wrote: > >Guido van Rossum writes: > > You've been staring at standards too much, haven't you? The > > difference between MUST and SHOULD isn't as clear-cut as most > > standards people use them. > >Most standards define MUST and SHOULD very specifically, and then use >them according to those definitions. There's an IETF RFC >specifically for use in writing RFCs, allowing those terms to be >defined by reference. A number of W3C specs seems to be using this >definition-by-reference as well, with the same RFC providing the >actual definitions. > >I think we'd do well to accept a specific definition of these terms >and use them consistently, simply to make our documentation >(including docstrings) easier to understand. > How about defining a new deontic type with the values Must and Should...? Hm. Doesn't make much sense, I guess :) > > -Fred -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From pereira at cis.upenn.edu Fri Mar 8 08:13:19 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Fri, 08 Mar 2002 08:13:19 -0500 Subject: why is python slow? References: Message-ID: On 3/8/02 7:29 AM, in article u8hbcgr35p4f4 at news.supernews.com, "John Roth" wrote: > Part of the speedup was relentless optimization by the various Java > licencees, and part was "just in time" compilation. So far, nobody has > worked on a JIT engine for Python. There's a vast difference in the > amount > of effort expended on Java as opposed to Python. Another reason is that a JIT compiler may not help Python as much as Java, because every Python object must have a type tag, and those tags must be checked by every operation, while type-tag checks are only needed in a few places in Java (eg casts), and never for primitive types. Because of type tag checks, there would be no long, easily optimizable straightline instruction sequences, which is one of the things what makes JITC worth it for Java. The other thing is inlining, which would be rather hard to do given Python's dynamic nature. -- F From cliechti at gmx.net Sat Mar 23 11:31:32 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Mar 2002 17:31:32 +0100 Subject: IOstreams/pipes, newbie question, capturing console info form another script? References: Message-ID: "G. Willoughby" wrote in news:a7i9kq$ujm$1 at news7.svr.pol.co.uk: ... > os.system("python mapper.py -settings mappergui.ini -scale %s -out > latest_render.jpg -zone %s" % (self.imageSize, self.currentZone)) > [/snip] > now i was wondering because this 'mapper.py' script and an > included 'zone.py' writes alot of info to the console using > 'sys.stdout.write()' > can i intercept this using my first Tkinter prgram so i can display > this info in another freshly created window. basically i am writing > a gui for a cmdline script! if so has anyone got any examples of > code for me to look at that would be great! have a look at os.popen. it returns a file-like object where you can read the output from the programm you started. chris (PS: the NOSPAM will not help much, but its an inconvenience for people that want to anwser you. some months ago we had a discussion aout that on this group.) -- Chris From python at rcn.com Sun Mar 3 23:34:42 2002 From: python at rcn.com (Raymond Hettinger) Date: Sun, 3 Mar 2002 23:34:42 -0500 Subject: Status of PEP's? References: <1cef615e.0203021254.6bf3658@posting.google.com> <3C82C91C.A60B3242@cosc.canterbury.ac.nz> Message-ID: "Greg Ewing" wrote in message news:3C82C91C.A60B3242 at cosc.canterbury.ac.nz... > "Hernan M. Foffani" wrote: > > > > But I fail to see how to apply this solution naturally on sets that have > > several different main 'walking' directions like arrays or like the sample > > in the PEP. If the 'table' object has symmetry between two (or more) axes, > > then > > indici(table) > > is ambiguous. > > An optional second argument indicating which dimension > you want the indices for. > > for i in indices(myarray, 0): > for j in indices(myarray, 1): > ... No, please. Even for symmetric tables, a default direction should be assigned (say, row-major). Then, the normal pythonic approach to nested lists or tuples can be used. For the most common case of rectangular tables (all rows have the same length and all columns have the same length), forget the new notation, save the repeated calls to len(), and use just one sample len() from each dimension (then loop row-major or column-major as you please): rowcnt, colcnt = len(arr), len(arr[0]) for i in range(rowcnt): for j in range(colcnt): someOp( arr[i][j] ) For the less common case of irregular tables, the proposed dimension argument does weird things. Given a ragged right, what would looping over columns do with: 10 20 30 40 50 60 70 80 90 11 12 13 Let's use the optional argument for something different: indices( anIterable, [start, [stop]] ) Now, you can make friends with people who number their arrays starting at one instead of zero ;) Also, indices() and indexed() should return a generator instead of a fully evaluated list. Why eat-up memory unnecessarily. One final note, if indexed() is available, why would indices() ever be needed? I can't think of any useful examples where the index is useful but the index reference is never fetched. This contrasts with dictionaries where there are examples of needing keys but not needing the values. Raymond Hettinger From jason at jorendorff.com Wed Mar 13 00:04:19 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Tue, 12 Mar 2002 23:04:19 -0600 Subject: Question about scientific calculations in Python In-Reply-To: Message-ID: Martin Kaufmann wrote: > This is the first raw version without histograms. s_vector is an array > with all the scattering parameters, f_s_vector the respective > scattering factors, and r_vector an array with all the distances > between the atoms. The equation is the Debye equation, so no fancy > integrals... > > for s in s_vector[1:]: > sum = 0 > for r in r_vector[1:]: > x = 2 * pi * r * s > sum = sum + (2 * (sin(x))/x) > intensity = atoms * pow(f_s_vector[n], 2) * (1 + sum / atoms) > i_vector.append(intensity) > n = n + 1 I'm going to attempt to explain how you can do this with Numeric Python, but you'll have to understand I have no clue what I'm doing scientifically. So in particular I'm assuming that "atoms" is a scalar, say atoms=1000. I also don't really know why you're using s_vector[1:] ... intentionally omitting the zeroth data point for some reason...? Anyway, here's an interactive session that implements the above algorithm using Numeric, with *no loops*. Or rather, the loops are all hidden away where you don't have to worry about them. (They should run faster, too.) First, I'll import all the nice Numeric functions. C:\dev> python Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from Numeric import * Next, I'll create a few arrays of random data to work with. Perhaps all these numbers are completely unrealistic, but that's your field... :) >>> from random import random >>> s_vector = array([random()-.5 for i in range(5)]) >>> s_vector array([-0.27223098, 0.24265847, 0.27374879, 0.17003544, 0.44799364]) >>> r_vector = array([random()-.5 for i in range(5)]) >>> r_vector array([-0.25522363, 0.09085211, 0.32083166, 0.48250771, -0.26395574]) >>> f_s_vector = arange(0.1, 0.6, 0.1) >>> f_s_vector array([ 0.1, 0.2, 0.3, 0.4, 0.5]) >>> atoms = 1000 Now, I need to make a copy of r_vector, because I want it to be a 2-D matrix -- a column, not a row. Because r_vector is currently a 1-D matrix, I'll need to add a new axis to it. This is done by using a special slice syntax: >>> r_column = r_vector[:, NewAxis] >>> r_column array([[-0.25522363], [ 0.09085211], [ 0.32083166], [ 0.48250771], [-0.26395574]]) Now. Multiplying r_column and s_vector creates a full 2-D array, a sort of multiplication table (if that makes sense). >>> x = 2 * pi * r_column * s_vector >>> x array([[ 0.436554, -0.389131, -0.438988, -0.272671, -0.718410], [-0.155400, 0.138519, 0.156266, 0.097063, 0.255732], [-0.548775, 0.489161, 0.551835, 0.342765, 0.903085], [-0.825318, 0.735664, 0.829920, 0.515493, 1.358175], [ 0.451490, -0.402444, -0.454007, -0.282000, -0.742989]]) I deleted some extra spaces and decimal places to try and make that fit nicely into this message. When you do it at home you'll get more precision. Next, I'll calculate the 2 * sin(x) / x part ... >>> y = 2 * sin(x) / x >>> y array([[ 1.937076, 1.949906, 1.936379, 1.975308, 1.832347], [ 1.991959, 1.993610, 1.991870, 1.996861, 1.978271], [ 1.901115, 1.921189, 1.900027, 1.961066, 1.739018], [ 1.780558, 1.824418, 1.778189, 1.912591, 1.439403], [ 1.932741, 1.946448, 1.931996, 1.973597, 1.821001]]) Now I want the sum of each column. There's a special method that does this... >>> sums = add.reduce(y) >>> sums array([ 9.543451, 9.635572, 9.538462, 9.819425, 8.810042]) Now calculate the intensities from that. >>> i_vector = atoms * f_s_vector**2 * (1 + sums/atoms) >>> i_vector array([ 10.095434, 40.385422, 90.858461, 161.571108, 252.202510]) Let's demonstrate that this is the same result as you'd get with your algorithm, mostly as written: >>> def f(s_vector, f_s_vector, r_vector): ... n = 0 ... i_vector = [] ... for s in s_vector: ... sum = 0 ... for r in r_vector: ... x = 2 * pi * r * s ... sum = sum + (2 * (sin(x))/x) ... intensity = atoms * pow(f_s_vector[n], 2) * (1 + sum/atoms) ... i_vector.append(intensity) ... n = n + 1 ... return i_vector ... >>> f(s_vector, f_s_vector, r_vector) [10.095434515144179, 40.38542290296536, 90.858461626142727, 161.57110800726178, 252.20251050463611] Here's how that function would look using Numeric: >>> def f(S, FS, R, atoms): ... Rcol = R[:, NewAxis] ... x = 2 * pi * Rcol * S ... y = 2 * sin(x) / x ... sums = add.reduce(y) ... I = atoms * FS**2 * (1 + sums/atoms) ... return I ... >>> f(s_vector, f_s_vector, r_vector, atoms) array([ 10.09543452, 40.3854229 , 90.85846163, 161.57110801, 252.2025105 ]) >>> list(_) [10.095434515144179, 40.38542290296536, 90.858461626142727, 161.57110800726178, 252.20251050463611] Note that when Python displays an array, it only shows a few decimal places; but full precision is stored (and you can see it if you convert the result back to a Python list). The histogram version is up to you. :) Numeric lets you mix arrays and scalars randomly and it happily distributes multiplication and so forth. So the resulting code looks a bit more like the original formulas. Some folks like that. But if you don't, you can always code this in C and it'll be faster still. It won't take very long to learn C. The real problem is that C programs can be very difficult and time-consuming to debug. ## Jason Orendorff http://www.jorendorff.com/ From shredwheat at attbi.com Sat Mar 2 13:31:23 2002 From: shredwheat at attbi.com (Pete Shinners) Date: Sat, 02 Mar 2002 18:31:23 GMT Subject: Why isn't pychecker mentioned prominently? References: <3C80ED0B.42292C99@tds.net> Message-ID: <3C811C18.1020208@attbi.com> Edward K. Ream wrote: > I just found out about pychecker (http://pychecker.sourceforge.net/) and > I am wondering why it isn't mentioned prominently all over the Python > web site: the tutorial, the links on the left and side of the home page, > topics guides, general reference etc. I found out about it from reading > one of Guido's recent presentations in which he mentions it as one of > his favorite Python tools. So why is pychecker such a secret? i heartily agree. i now try to use pychecker on absolutely everything i do. i really wish it came as part of the standard distribution. it could easily be enabled on the commandline with some sort of -wall. heck, python recently added the full "warning" framework. it seems like an ideal place to tie that all in. then users can control if the pychecker warnings were silenced, printed, or treated as exceptions. From grey at despair.dmiyu.org Wed Mar 6 19:08:44 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Thu, 07 Mar 2002 00:08:44 -0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 15:35:06 -0800, David Eppstein wrote: > I diagree that the current method has both, or either. I don't know > about you, but I find "for x in range(n-1,-1,-1)" to be a difficult to > read and difficult to understand way of obfuscating a simple loop over > the numbers 0 to n-1 in reverse order. I think "for n > x >= 0" would > be much simpler. As stated in the PEP, perceived problem. for foo ? bar ? baz is less clear. Difference is, range[foo,bar,baz] is what is there and, for anyone who takes the time to learn the language instead of looking for problems, finds that it is quite clear. Start, end, step. Furthermore the "for x in foo" is generic enough that one can also prepare the list in any manner they choose. Overloading for adds unneeded complexity to address nothing more than a perception problem for those reading the code wanting something their way because they are too lazy to learn the ways the language already allows the same thing to be done. IE, this is the same thing we get every time someone stumbles onto Python and gets thier knickers in a twist because while (1): violates what their college professor stated. NO INFINITE LOOPS! Nevermind that the if statement right after the while does provide the same break. No, we get endless wars that we should have a do:while loop and a do:until loop and lord knows what other loop constructs to fit very specific cases which are handled just fine with a general construct. We have two looping constructs. While and for. Both give you ways to address the problem. We do not need an overloaded construct just to appease your sense of asthetics. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From hzhu at mars.localdomain Sun Mar 24 03:34:53 2002 From: hzhu at mars.localdomain (Huaiyu Zhu) Date: Sun, 24 Mar 2002 08:34:53 GMT Subject: Need help with plotting References: <3c9cd61e.8124286@news> Message-ID: brobbins333 at shaw.ca wrote: >I'm new to Python and doing pretty well with it so far. >One thing that has me stumped is finding an "easy" way, >or any way, for that matter, to plot simple graphs. I haven't >gotten into Tkinter yet and I'm not sure if there is another >way to make plots. I have scipy and Numeric and I can see >that there are graphing modules there but I have not been >able to access them with something like: from scipy import *. >This always fails with "not there" or "can't import." Have you tried Gnuplot package? (http://gnuplot-py.sourceforge.net/) If you have gnuplot installed, you might want to try it. It ultimately allows you plot anything that gnuplot can. See also http://matpy.sourceforge.net/MatPy/node30.html for a limited set of examples. -- Huaiyu Zhu From tim.one at comcast.net Tue Mar 26 02:32:29 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 26 Mar 2002 02:32:29 -0500 Subject: Indentation problem In-Reply-To: <7ieli7an7s.fsf@enark.csis.hku.hk> Message-ID: [Isaac To] > ... > It still works, but it doesn't look nice. What I want is a real > reindentation which understand how Python reads indentation, ... Read the docs for python-mode, especially for py-indent-region (not the same as the rigid py-shift-region). I wrote that more than 8 years ago; I doubt Barry has broken it . From d95-bli.no at spam.nada.kth.se Thu Mar 7 09:09:42 2002 From: d95-bli.no at spam.nada.kth.se (=?iso-8859-1?Q?Bj=F6rn?= Lindberg) Date: Thu, 07 Mar 2002 15:09:42 +0100 Subject: Order of constructor/destructor invocation References: Message-ID: <3C8774A6.52CF7F3A@spam.nada.kth.se> Christian Tanzer wrote: > Before this thread I would have agreed that destruction order is > completely well defined. Looking at your example I'm not sure about > one case. What if you write: > > void a_function () > { > sentry1 s1, s2; > ... > } > > ? Will s1 be destructed before s2 by all compilers? Guess, I never > cared about that because I tend to use multiple declarations myself. The destruction order is always opposite of the construction order. In this example s1 will be constructed first followed by s2. Destruction is performed in the opposite order, so s2 will be destructed first followed by s1. Bj?rn From deathtospam43423 at altavista.com Sun Mar 10 14:29:05 2002 From: deathtospam43423 at altavista.com (Flavian Hardcastle) Date: 10 Mar 2002 19:29:05 GMT Subject: How can I lock a file in Windows? References: Message-ID: Thanx. But will chatters get an IOError if one of them tries to access a file while it's already locked? "Fredrik Lundh" wrote in news:uyqi8.24010$n4.4643918 at newsc.telia.net: > > did you look under "MS Windows Specific Services" in the > library reference? > > http://www.python.org/doc/current/lib/module-msvcrt.html > => "file operations" > > something like this should work: > > def update(filename, new_content): > file = open(filename, "r+") > # look from current position (0) to end of file > msvcrt.locking(file.fileno(), msvcrt.LK_LOCK, > os.path.getsize(filename)) file.seek(0) > file.write(new_content) > file.close() # unlocks the file > > > > > > > -- "You can tell whether a man is clever by his answers. You can tell whether a man is wise by his questions." Naguib Mahfouz netvegetable at dingoblue.net.au From narnett at mccmedia.com Thu Mar 21 19:21:58 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Thu, 21 Mar 2002 16:21:58 -0800 Subject: Word frequencies -- Python or Perl for performance? In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Jim Dennis ... > I deliberately made it a class so you could instantiate > multiple word counts on different blocks of text to compare them > or whatever, and so you could import it into other programs and > use other methods (i.e. a web spider with urllib and a "text" extractor > with htmllib) to get your text. Yep -- that's where I'm headed. > With a bit of work this could be cleaned up into a more general > class which could then be used as the parent of some more specialized > word counters (with different notions of acceptable character sets, > and different semantics on handling hypens and apostrophes). In fact > it would make alot of sense to simply my Wordcount class and either > use it as a base class or put a Decorator class in front of it to > impose all the text parsing semantics prior to calling Wordcount.add() When I get it into good, flexible shape, I'll make it publicly available. Even though I don't think I want stemming, it'll be easy to optionally call a stemming module. > I'd definitely factor the "known words" list out of this; possibly > as its own class which could be (optionally) used by Wordcount (so > you'd decide at instantiation if a "known words" dictionary would be > used and (if so) which "known word" sources to use. It would then > be possible to use most of that to add support for "stop words" > ("words" that would NOT be counted). In practical usage it might be > sensible to pickle or shelve the "known words" dictionary since it's > moderately expensive to create it at each run-time). Definitely. For what I'm doing, almost everything is a stop word. I'm looking for outliers, trying to distinguish between those that are just freakish (random misspellings, etc.) and those that are actually emerging as significant. It's very interesting what can automatically emerge if you can spot outliers that are converging inward over time, so to speak. > Those bits of refactoring would be pretty simple. Using this in > a program that posted the results to your RDBMS should also be easy > enough. Most certainly. Thanks again. Nick From donn at u.washington.edu Fri Mar 15 14:34:28 2002 From: donn at u.washington.edu (Donn Cave) Date: 15 Mar 2002 19:34:28 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <1016173476.645562@yasure> <2b57f654.0203151021.7f709e4c@posting.google.com> Message-ID: Quoth wealthychef at mac.com (wealthychef): ... |> The complementary problem, of course, is that once you have invoked |> readline(), it will read all the data available on the file descriptor, |> or a lot of it anyway, and return only the first line. The next time, |> it will return the next line from its buffer, but you have no way to |> know that it has another line waiting there. select() can't see it. |> There are solutions, I think the easiest thing in most cases is to |> throw away the file object and just use the file descriptor (fileno()) |> (or sockets in this case.) | | This is even more frightening. I don't want to lose any data! How | can I protect myself from this? Why is using the file descriptor | better? Well, you're not exactly losing data, it's just buffered, though that may be too fine a point depending on the circumstances. The point with file descriptor is to use system I/O functions on the device, and avoid buffered C I/O. Basically because select is a system I/O function. If there were a C analogue to select, then you could use it with C buffered file objects, but there is no such thing. When select tells you "this thing is ready to read", it means the device is ready for a system level read(), as in os.read(fd, bufsize). So do that, and you'll get what select was telling you about. It's really simple. The rules are the same, if you get an empty string it's at "end of file" (the pipe closed.) I have lost track of what kind of devices we're actually talking about - I'm seeing the word "socket", but then what looks like popen2.Popen3. Note that in Python, sockets are are normally socket objects, with recv() methods etc., but these are unbuffered and recv() is like os.read(). Pipes (as created by Popen3) are either integer file descriptors or file objects, there isn't any special system level pipe object. As long as you're on UNIX, there's a certain purity of abstraction here that you can exploit if you want it just to simplify matters - you can get the file descriptor with s.fileno(), and you can use os.read() with that - or you can use sock.recv() if you prefer. Donn Cave, donn at u.washington.edu From rs at onsitetech.com Fri Mar 29 16:18:47 2002 From: rs at onsitetech.com (Robb Shecter) Date: 29 Mar 2002 21:18:47 GMT Subject: Python+wxWindows as Visual Basic replacement? Message-ID: Hey all, Anyone have any experience using Pythonas an alternative to VB for Windows database client apps? It looks like all the pieces are in place - wxWindows, py2exe, a Python ADO library... Python per se isn't the issue - what I'm not sure about is what the development and deployment experience is like, when using these parts, taken together. Thanks for any pointers, anecdotes, etc. -- Robb Shecter Senior Software Engineer www.onsitetech.com From max at alcyone.com Sun Mar 31 14:09:47 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 31 Mar 2002 11:09:47 -0800 Subject: PEP 285: Adding a bool type References: Message-ID: <3CA75EFB.A79F6D61@alcyone.com> Ralph Corderoy wrote: > What do you think of `truth(x)' for all the good reasons listed > elsewhere in the thread? You used truth yourself instead of Boolean > above. But you already have precisely this: from operator import truth -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From matt at mondoinfo.com Wed Mar 20 13:50:37 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Wed, 20 Mar 2002 18:50:37 GMT Subject: tkinter menuitem question References: Message-ID: <1S4m8.36908$N7.6523773@ruti.visi.com> On 20 Mar 2002 14:24:33 +0000, Ken Guest wrote: Dear Ken, >ok, I might be way off here but is there a way with a collection of >Tkinter menuitems that all have their callbacks set to be the one >function to determine which menuitem was clicked on? Yes, you can do that by storing the state in an object that has a __call__ method. I'll append a small example. Regards, Matt from Tkinter import * class genericCBO: def __init__(self,func,*positionArgs,**kwArgs): self.func=func self.positionArgs=positionArgs self.kwArgs=kwArgs return None def __call__(self): return apply(self.func,self.positionArgs,self.kwArgs) return None class mainWin: def __init__(self,root): self.root=root self.createWidgets() return None def createWidgets(self): menubar=Menu(self.root) myMenu=Menu(menubar) myMenu.add_command(label="Option 1",command=genericCBO(self.menuCB,1)) myMenu.add_command(label="Option 2",command=genericCBO(self.menuCB,2)) menubar.add_cascade(label="Menu",menu=myMenu) self.root.config(menu=menubar) return None def menuCB(self,index): print index return None def main(): root=Tk() mainWin(root) root.mainloop() return None if __name__=='__main__': main() From wealthychef at mac.com Fri Mar 15 11:51:44 2002 From: wealthychef at mac.com (Rich Cook) Date: Fri, 15 Mar 2002 08:51:44 -0800 Subject: readline() blocks after select() says there's data?? In-Reply-To: <15505.33265.747862.25428@12-248-41-177.client.attbi.com> References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> Message-ID: At 11:09 PM -0600 3/14/02, Skip Montanaro wrote: > >> selectables = [theProcess.childerr, theProcess.fromchild] > >> (input, output, exc) = select.select([],selectables, selectables) > ... > > >> It blocks forever waiting for theProcess.childerr.readline(bufsize) > >> to return. I expect it to block waiting for select.select(); that > >> would not be a problem. The problem is that select is claiming > >> there's stuff to be read, then when I try to read it, it's not there! > >> How can that be? > >Based upon the attribute names you are using, I suspect you instantiated >os.Popen3 to create theProcess. These are file objects, not sockets. I >believe select only blocks on sockets. See the comments about asynchronous >file i/o near the bottom of asyncore.py. I don't really need select to block. I just want it to be accurate. If it returns a file object in the list of things which are available, why should then readline() block on it? -- -Sincerely, Rich Cook 925-784-3077 ******************************************************************* Sometimes it is said that man cannot be trusted with the government of himself. Can he, then, be trusted with the government of others? Thomas Jefferson ******************************************************************* From gbreed at cix.compulink.co.uk Fri Mar 1 13:12:42 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Fri, 1 Mar 2002 18:12:42 +0000 (UTC) Subject: Javascript to Python References: <2030665d.0203010912.1bb9c0ae@posting.google.com> Message-ID: Sam Collett wrote: > Does anyone know of any good sites on Javascript > Python examples? Forgive me for being arrogant, but learning Python from the tutorial should tell you all you need. > I have a function in javascript that returns the file extension: > > function FileExtension(sFilePath) > { > return Right(sFilePath,sFilePath.length-sFilePath.lastIndexOf(".")) > } > > so FileExtension("/path/to/file.doc") would return .doc > I would also want to return the filename (file) and the path > (/path/to/). How would I go about that? >>> import os >>> os.path.splitext("/path/to/file.doc")[1] '.doc' >>> os.path.splitext(os.path.basename("/path/to/file.doc"))[0] 'file' >>> os.path.dirname("/path/to/file.doc") '/path/to' > What equivalents to the functions Right and Left (right side of > string, left side of string) >>> "hello world"[:5] 'hello' >>> "hello world"[-5:] 'world' > Also is there an easier way to do number incrementing (just me being > lazy): > while r<5 > print r > r=r+1 > > I have tried r++ to add 1 each time, and r-- to take away one, but > this does not work, so is the only way r=r+1 or r=r-1 ? Your code's missing a : You can use r+=1 and r-=1 with recent enough versions of Python. That particular example can be done >>> for r in range(r, 5): ... print r Graham From grey at despair.dmiyu.org Fri Mar 15 15:53:35 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Fri, 15 Mar 2002 20:53:35 -0000 Subject: ***Stopping a Python Thread*** References: <4378fa6f.0203151245.2a87b42d@posting.google.com> Message-ID: On 15 Mar 2002 12:45:48 -0800, Marc wrote: > command to try and kill it all. But the thread keeps running and does > not stop. How do I kill this thread before it completes? You must stop each thread from inside the thread. So have some flag somewhere that it can check to see if it needs to shut down early. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From * at spam.ruud.org Wed Mar 13 12:16:09 2002 From: * at spam.ruud.org (ruud de rooij) Date: 13 Mar 2002 12:16:09 -0500 Subject: Why I think range is a wart. References: <873cz44ea8.fsf@bunty.ruud.org> <3C8F82C9.3090308@mxm.dk> <87y9gw2yig.fsf@bunty.ruud.org> Message-ID: <87u1rk2xt2.fsf@bunty.ruud.org> ruud de rooij <*@spam.ruud.org> writes: > [ (item, sublist[i]) for (item, i) in thelist.items() ] oops, i meant: [ (item, sublist[i]) for (i, item) in thelist.items() ] - ruud -- ruud de rooij | *@spam.ruud.org | http://ruud.org From pereira at cis.upenn.edu Fri Mar 8 21:54:30 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Fri, 08 Mar 2002 21:54:30 -0500 Subject: why is python slow? References: Message-ID: On 3/8/02 12:28 PM, in article a6ascr$19l8$1 at nntp6.u.washington.edu, "Donn Cave" wrote: > We can wave our hands and say performance is a > tough problem, but it would be more convincing if it looked like it was > getting the most minimal attention. It's all a matter of resource allocation. Computers are cheap and common, Python experts are rare and expensive (at least I hope so, they deserve it). -- F From cliechti at gmx.net Tue Mar 5 16:08:56 2002 From: cliechti at gmx.net (Chris Liechti) Date: 5 Mar 2002 22:08:56 +0100 Subject: Updating Python...Newbie alert! References: Message-ID: "Mr.Lee" wrote in news:n3ah8.112697 $Hu6.28510292 at typhoon.neo.rr.com: > Hi all, > Being quite new to Linux, I am having a bit of a problem > when it comes to updating my installed version of Python(1.5.2) to > the version that I have now(2.2). > My problem is that I compiled Python in the directory that > I downloaded and now I don't know where to put all of the files > that were generated! It works, I ran the tests and it all came out > fine, but I just don't know where to put the files for maximum > efficiency. usualy one does "./configure;make;make install" and the "make install" places the files where they belong (in subdirectories of /usr/local/ usualy) chris -- Chris From jdgorman at ieee.org Thu Mar 14 00:45:35 2002 From: jdgorman at ieee.org (John Gorman) Date: Thu, 14 Mar 2002 05:45:35 GMT Subject: basic statistics in python References: Message-ID: <3C90392D.8000108@ieee.org> Doug, Another consideration is using the MLab module and Numeric. MLab emulates several Matlab function calls including "cov" (which doesn't have a docstring, by the way, but here's Matlab's definition of cov(): """COV Covariance matrix. COV(X), if X is a vector, returns the variance. For matrices, where each row is an observation, and each column a variable, COV(X) is the covariance matrix.... """ Anyway, you could write your own python-based code, but the cov() function is likely to be more efficient for large arrays. Here's an example using the scipy module (which contains Numeric and MLab): Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import scipy >>> # generate a vector of std nrml rv's >>> v = scipy.normal(0,1,100) >>> # cov returns the variance if its argument is a vector >>> # rather than a matrix >>> sig_v = scipy.sqrt(scipy.cov(v)) >>> print sig_v 0.97295502908 I haven't peeked under the hood with scipy.normal, but I'm assuming they're using something similar to the Box-Muller algorithm... Perhaps I ended up with a "bad seed" here (expecting sig_v = 1) ;^). Hopefully you get the picture... ;^) Finally, if you want access to other statistical routines there are some python based modules floating around including Scientific Python and Gary Strangman has stats.py at: http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html Cheers, John Gorman Fernando P?rez wrote: > dsavitsk wrote: > > >>i found this >>http://starship.python.net/crew/hinsen/ScientificPythonManual/ >>but it seems to be unix only and i am on win32. as far as standard >> > > you can probably get the stuff you want running under win. I'd be very > surprised if all of Konrad's code was tied to unix (though I can't tell for > sure, I use it under unix). > > >>There seems to be some stuff in scipy, but i am having trouble geting >>through the docs. also, do i want to look at numpy? >> > > Scipy is early and still a bit rough to install, but fabulous. And yes, you > NEED numpy for anything numerical in python above the toy level. Both > konrad's libs and scipy are numpy based anyway. > > cheers, > > f > From herrn at gmx.net Sat Mar 9 07:53:36 2002 From: herrn at gmx.net (Marco Herrn) Date: Sat, 9 Mar 2002 13:53:36 +0100 Subject: how to set the background color of a window with curses Message-ID: <20020309125336.GA2236@lurkabove.darkstar> Hi, I am trying to set a backround color for a window and did it with stdscr.bkgd(' ', curses.COLOR_BLUE) But that doesn't work. It seems to do nothing. What am I doing wrong? Bye Marco -- If you didn't have to work so hard, you'd have more time to be depressed. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From amoustafa at pobox.com Wed Mar 20 03:59:17 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Wed, 20 Mar 2002 08:59:17 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> Message-ID: <3C984F44.1090001@pobox.com> Gerhard H?ring wrote: > (Followup-To set to comp.lang.python, as this doesn't have any > relevance to Java any more) > > Ahmed Moustafa wrote in comp.lang.python: > >>How about web development? >> > > A little research of yourself would tell you all you need to know, but > I'm happy to give my informed opinion ;-) > > Web development is one area where Python really shines. Almost all of > the Python users I know personally use it for web development. > > My biggest webapp was build an online shop system with Python and > MySQL. From scratch, with its one templating system (of course), > dynamic site navigation and all that stuff. Development time was only > some 6 to 8 weeks. May I ask you what the scal for your webapp was? (Because MySQL is related to small to mid-size web applications). Is it the same case with Python? > > All the rest at http://www.python.org/topics/web/ > > >>Also, how is Python doing in the embedded applications? >> > > It's possible, but people using it for this are certainly a minority > among Python developers. > > Gerhard -- Ahmed Moustafa From anthony.brown at gs.com Thu Mar 21 17:10:20 2002 From: anthony.brown at gs.com (Anthony Enache Brown) Date: 21 Mar 2002 14:10:20 -0800 Subject: Calling stored procedures from zxJDBC Message-ID: Hi there, I'm writing a script against a Sysbase Adaptive Server Enterprise 11.9.2.1, and I'm having a tough time getting it to call a stored procedure. The jython code looks like this: db = zxJDBC.connect(d, u, p, v) c = db.cursor(1) c.execute( "execute DELETE_QUEUED_ACCOUNTS" ) This fails with: Traceback (innermost last): File "", line 1, in ? Error: SELECT INTO command not allowed within multi-statement transaction. Severity 16, State 1, Procedure 'FUTDEV DELETE_QUEUED_ACCOUNTS', Line 54 [SQLCode: 226], [SQLState: 01000] The same statement from within iSql works without a hitch. Any ideas as to what I am doing wrong? Thanks for your help, Anthony From jeff at ccvcorp.com Fri Mar 29 14:32:42 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 29 Mar 2002 11:32:42 -0800 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> <3CA3768B.32BB6AC9@ccvcorp.com> <3CA3C981.2433ECD7@ccvcorp.com> Message-ID: In article , philh at comuno.freeserve.co.uk says... > Jeff Shannon wrote: > > > >I disagree with your conception of high level language. A > >high level language hides > >unnecessary details, but I don't think that conversion between > >different data types > >is an unnecessary detail. > > So would you prefer: > > float(2) + 3.14 > > to: > > 2 + 3.14 > > ? In the particular case of numbers, it does make practical sense to consider "Number" to be a single data type, with several specializations (integer, float, complex). Thus, one can (somewhat) reasonably claim that converting int-->float is not truly between different data types. (Judging from the discussions regarding new division, this seems to be the view that Guido takes.) But I do consider numerics to be a special case, and not a good indication of a general rule. However, None is not a number, nor is it a sequence of any sort, nor is it... well, anything. None is a specific "not valid" value, and making it valid to perform arithmetic on a non-valid value is confusing at best. > >High level means that a logical step can be done in one > >or two lines of code, > > Define "logical step". Define "semantic". What I mean by this is that a low-level language is one in which a single conceptual (semantic) step is broken down into a series of instructions. A high-level language is one in which each conceptual step is done with a minimal number of instructions. The specific definition of "a single conceptual step" is variable, and describes just *how* "high- level" the language is. (Compared to assembly, C is relatively high-level.) > >There's a large class of cases where the interpreter, in > >trying to "do the right > >thing", is as likely to guess wrongly as it is to guess right. > > This is only true if what the interpreter will do is not cleanly > defined for the programmer. No, it's also true if the behavior is non-intuitive, despite being well-defined. Having a non-value be a valid component of an arithmetic expression is confusing. (Should we also be able to perform arithmetic on floating-point NaNs?) Confusing language constructs result in wrong programs, even when it's possible to examine closely and define exactly how it *should* behave. > > If you want an > >interpreter that guesses anyhow, use Perl. > > Yuck. My point exactly. What you're proposing would be a large step in the direction of Perl, and the fact that Python *doesn't* behave that way is exactly the reason that so many of us *prefer* Python over Perl. -- Jeff Shannon Technician/Programmer Credit International From erno-news at erno.iki.fi Fri Mar 8 12:19:59 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 08 Mar 2002 19:19:59 +0200 Subject: why is python slow? References: Message-ID: In article , Fernando Pereira writes: | Another reason is that a JIT compiler may not help Python as much as Java, | because [...] i think the last time there was an in-depth thread about this, many people speculated that a jit compiler could infact help python a lot. (perhaps a jit compiler can help java even more.) smalltalk and self implementation techniques were discussed. -- erno From edream at tds.net Mon Mar 4 04:26:18 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 04 Mar 2002 09:26:18 GMT Subject: The Text Widget References: <5Hzg8.72869$vP.290047@rwcrnsc51.ops.asp.att.net> <3C82E8C4.24531DE7@tds.net> Message-ID: <3C833DB8.6A4EB165@tds.net> Eric Brunel wrote: > > First, note that if you bind to a key-press () event, when the > > event handler is called the Text widget hasn't been changed yet(!) > > Other frameworks provide a "text will change" event and a "text did > > change" event, but AFAIK Tk does not. > > Tk does: it's simply that the event "" is a short-cut for > "", called when the key is depressed, so before the insertion > happened. To do a binding after the text has been inserted, the event is > "". Are you sure? I know I tried binding to and IIRC the text had not changed. Or maybe my memory is faulty and there were some other problems with . I do know that I tried and failed to find a way to get an event "just after" the the text had changed instead of waiting for idle time. I wanted to do this to make syntax coloring as fast as possible. Note that my main testing was done on Windows, if that makes any difference. BTW, I had all kinds of problems distinguishing "plain" key-presses from alt and control keys. I tried various ways of binding to and for the alt and control keys, without real success. I finally gave up and just had my handlers check to see whether the key-presses actually changed the text. If you have an example of fancy bindings for Text widgets I'd love to see it. Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From rgwright at ux.cso.uiuc.edu Fri Mar 29 17:10:47 2002 From: rgwright at ux.cso.uiuc.edu (robert garretson wright) Date: Fri, 29 Mar 2002 22:10:47 GMT Subject: Breaking String into Values Message-ID: I am working on reading in a data file format which is set up as a series of lines that look like this: 3500035000010104A Foo 45 I want to break up into a variables as follows: a = 35000, b = 35000, c = 10104, d = 'A', e = 'Foo', f = 45 My current code (auto-generated from a data dictionary) looks something like this: temp = line[0:5] a = int(temp) temp = line[5:10] b = int(temp) temp = line[10:15] c = int(temp) temp = line[15:16] d = temp temp = line[16:20] temp = temp.rstrip() e = temp temp = line[20:23] f = int(temp) with a bit more error checking around the int() calls. Is there a better way to do this? The files have around 1000-8000 lines each so I would like it to be fast. Is there a package around that someone has coded up as a C-extension to do this? -- Robert Wright rgwright at uiuc.edu From lac at strakt.com Sat Mar 23 03:04:34 2002 From: lac at strakt.com (Laura Creighton) Date: Sat, 23 Mar 2002 09:04:34 +0100 Subject: "Zope-certified Python Engineers" [was: Java and Python] In-Reply-To: Message from "A.M. Kuchling" of "22 Mar 2002 20:55:07 GMT." References: Message-ID: <200203230804.g2N84Yrq006316@ratthing-b246.strakt.com> > Andrew Kuchling wrote: > In article , > Laura Creighton wrote: > > One days reading of your weeks spam will yield you many offers of > > programs and advice on how to make your website rise in the Google > > ranking. This reflects the reality that once you have made it to the > > Rule #1 when dealing with spam: Spammers lie. I doubt any of those > offers would actually result in any useful information or visible > effect on your ranking. Absent Scientology-scale creation of fake > links, the only way is to update your site often and to get other > people to link to you. Er, I wasn't commenting on the technical feasibility of the solutiuons offered by the Spammers -- though my current crop of spam which just made mailman blow up appears to include a fake-link generation software -- just the fact that google leaders are even harder to replace than politicians. Incumbancy counts. > > > EBay has one sort of approach. So does Advogato (see http://advogato.org ) > . > > It is a real problem and one that interests me a lot. > > At the Web services panel at Python10, Tim Berners-Lee mourned that > third-party Web annotation tools such as crit.org or the commercial > Third Voice have never really caught on. Probably this is because, as > he suggested, the UI would be really complicated, because we already > have the technical pieces needed. I tink the problem has more to do with political will and lack of order in the www than the UI. > > Consider your example of a buggy formula on a Web page. Perhaps > someone has noted this error on some annotation service, but on which > one? The W3C's? crit.org? The American Mathematical Society? You > probably can't just pick one for the whole Web, because the AMS > annotations probably don't comment on X-Files Web pages much (or > particularly well). Instead you'd need a complex set of preferences > -- use the AMS for mathematical pages, use the MEMS Exchange for > MEMS-related pages, and so forth. This is Google-Next-Generation's problem. When they see a bad AMS or MEMs rating, they quickly deprecate the webpage, informing the page's owner why this happened. The difficult part is getting the page reclassified when its owner fixes his typo and produces the correct formula. The AMS doesn't have time for everybody's typos. But MEMS might -- if you could charge for this service. If getting a good MEMS rating encouraged people to use the service, then you could afford to hire people who were just concerned with maintaining MEMS' own standards. If having a good MEMS rating was indispensible for credibility, and getting a good google ranking, then many useful things could be done. > This quickly gets really messy. Who annotates a finite-element > analysis of a MEMS structure? Both services, or just one? Anybody who cares to should be able to annotate a page. > And how do > you tell if a page is mathematical, anyway? Or will I constantly > telling my browser which service to use for each URL, in a > never-ending task. (You could have a annotation service that just > classified pages, of course.) You would have to have this if people wished to browse the annotations. But for a first pass all we need to do is to make _Google_ care. If unclassified, unranked web-pages got a poorer showing than those which were classified as great by 'repuable authorities' but better than those which were classified as garbage by the same authorities. Then you only have to rank the authorities. And people could have their own lists -- if you think that Google's default authority ranking is reflects bourgeois American sensibilities, tell Google to use your list instead. > > A widely adopted solution would bring us much closer to Ted Nelson's > vision of a hyperlinked repository of all knowledge, but getting there > seems very, very difficult. > > --amk Up until fairly recently, there were strong links between people who wanted to share information and people who wanted to resist authority. The web is anti-authoritarian in nature, which is a great thing when you want to resist coercive political pressure, but a bad thing when what you actually want is a guaranteed correct reference. Countless schemes have come and gone with the flaw in their makeup 'my opinion is every bit as good as your opinion'. It is too big now for that, and Google is now the defacto authority for everything you want to find on the web. But putting Google out of business by producing a service that results in better quality hits on your searches is still possible. Finally, out of the chaos, we have produced the social situation where order beats freedom of expression hands-down. And Google must be responsive to it or risk going out of business. Would you trade 'the freedom to be different' for 'the choice to be excellent'? Every new python progrqammer who has given up on 'self-expression through my favourite brace style' is making this choice. The subversive message is 'order is a lot of fun'. I think that this message will finally produce people who are brave enough to say that they want good authorities, not the absence of all authorities. But then I'm an Order-loving Optimist. Laura Creighton From mmiller3 at iupui.edu Wed Mar 13 12:48:16 2002 From: mmiller3 at iupui.edu (Michael A. Miller) Date: 13 Mar 2002 12:48:16 -0500 Subject: python and analyze image format? Message-ID: <87henkickf.fsf@lumen.indyrad.iupui.edu> Anybody know of a python reader/write for analyze image data and header files? Would you provide a pointer if you do? Mike -- Michael A. Miller mmiller3 at iupui.edu Imaging Sciences, Department of Radiology, IU School of Medicine From stevena at neosynapse.net Fri Mar 8 06:48:43 2002 From: stevena at neosynapse.net (Steven D. Arnold) Date: Fri, 8 Mar 2002 06:48:43 -0500 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: <7x3czbag9q.fsf@ruckus.brouhaha.com> References: <7x3czbag9q.fsf@ruckus.brouhaha.com> Message-ID: <3437343234.20020308064843@neosynapse.net> On Thursday, March 07, 2002, at 10:29:37 PM, Paul Rubin wrote: PR> "Steven D. Arnold" writes: >> In the meantime, (istring is) practically like, say, an r or u >> string, except with parentheses: >> >> >>> from neo.istring import istring as i >> >>> l = [1,2,3] >> >>> i('first value is $l.0') >> 'first value is 1' PR> It occurs to me, you could get rid of the parentheses by making the PR> i object an instance of a class that overrides (say) division: PR> >>> from neo.istring import istring as i PR> >>> l = [1,2,3] PR> >>> i/'first value is $l.0' PR> 'first value is 1' Wow....interesting! I'm sure some would accuse me of abuse of operator overloading, but a cool idea all the same... -------------------------------------------------------------- Steven D. Arnold Neosynapse stevena at neosynapse.net Managing Partner AIM: abraxan MSN: neosynapse at hotmail.com From jeff at ccvcorp.com Tue Mar 5 15:00:56 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 05 Mar 2002 12:00:56 -0800 Subject: RFC PEP candidate: q''quoted ? References: Message-ID: <3C8523F8.38715E45@ccvcorp.com> Bengt Richter wrote: > >Making Python as gibberish as Perl is. And all that only to > >have Windows path be written without double-\ > Not 'only'. I said 'also' ;-) Perhaps my choice of '|' delimiter triggered > your 'gibberish as Perl' detector? > > I could have written > > q'###'c:\foo\bar\### > or > q'[quoting delimiter]'c:\foo\bar\[quoting delimiter] > > just as well for this one. I still don't like it. It's very difficult for me to see at a glance, what's part of the string and what is part of the delimiter, especially with the leading delimiter being quoted and the trailing one not quoted. It looks unbalanced, it looks ungainly, and, to me, it just plain looks ugly. I'd expect the above example to be equivalent to "'c:\\foo\\bar\\", with a leading mismatched single-quote... Your earlier example of cutting & pasting left me totally confused until I spent a minute sorting through it. At least to me, this seems totally unclear and totally nonintuitive. It vastly multiplies the possibilities for writing hard-to-read code, while providing a real benefit in relatively few situations. Considering how often triple-quotes appear in text files, I can only imagine this being needed when trying to programmatically generate Python code, which doesn't seem to be a terribly common task. I'd prefer to find an alternate solution for the specific case of that task, which doesn't require changing the core language and creating so much potential for ugly code in every other task that can be done with Python. Jeff Shannon Technician/Programmer Credit International From jason at jorendorff.com Mon Mar 11 08:54:11 2002 From: jason at jorendorff.com (Jason Orendorff) Date: 11 Mar 2002 07:54:11 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 11) Message-ID: <353A4A03E1CFF2E4.621DD6F68D7A71AA.CF3107F9DF8C4B86@lp.airnews.net> QOTW: "I am once again stunned by how good the Python standard library is. I spent an afternoon surfing and assumed I'd have to write code, but urllib does most of what I want by default." -Andy Robinson Seek fame & fortune as a Python developer! http://groups.google.com/groups?th=78c19cf834778b56 http://www.amk.ca/python/writing/python-dev.html Disipyl is a Python interface to DISLIN, a plotting library. Cool screenshots. http://pantheon.yale.edu/~pmm34/disipyl.html RPy is a Python interface to R, a programming language and environment for statistical computing and graphics. http://rpy.sourceforge.net/ http://www.r-project.org/ BBLImage is a collection of tools for processing volume images, especially medical images; it includes Pyvox, a Python extension for large multi-dimensional arrays. http://www.med.upenn.edu/bbl/bblimage lfm v0.8 is released. lfm is a 'midnight commander' clone written in Python. http://www.terra.es/personal7/inigoserna/lfm Mitchell Charity uses PyInline to add an interesting postscript to an essay by Guido about optimizing Python code. http://groups.google.com/groups?selm=mailman.1015705101.26116.python-list%40python.org Fran?ois Pinard shows how to convert images to monochrome with PIL in a single line of code. http://groups.google.com/groups?th=ad62f29aff8871a6 A question about Python weblogs and Web scripting yields a variety of Web-based weblog applications and Web scripting libraries. http://groups.google.com/groups?th=2e56b5ff1042343a Squishdot - http://www.squishdot.org/Documentation Plone - http://plone.org Albatross - http://www.object-craft.com.au/projects/albatross Webware WebKit - http://webware.sourceforge.net HTMLTMPL - http://htmltmpl.sourceforge.net jonpy - http://jonpy.sourceforge.net Mike Olson and Uche Ogbuji examine the Zolera SOAP Interface in this article, the second in a series. http://www-106.ibm.com/developerworks/library/ws-pyth6 Python User Groups now have their own page on the Python web site: http://www.python.org/UserGroups.html ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning, ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From skip at pobox.com Fri Mar 1 10:53:34 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 1 Mar 2002 09:53:34 -0600 Subject: Swapping out sys.stdout globally In-Reply-To: <20020301093135467-0500@braeburn.na.sas.com> References: <20020301093135467-0500@braeburn.na.sas.com> Message-ID: <15487.41982.968248.121857@12-248-41-177.client.attbi.com> Kevin> sys.stdout = NewFile() Kevin> sys.stderr = NewFile() Kevin> However, I have some logging routines in a separate package that Kevin> already have their own references to sys.stdout and sys.stderr Kevin> which are unaffected by this. Sounds like they use something like from sys import stdout,stderr The best solution there would be for those packages to import sys in the usual fashion: import sys and refer to sys.stdout & sys.stderr. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From robin at jessikat.fsnet.co.uk Fri Mar 1 12:24:02 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 17:24:02 +0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7F6765.94A82394@engcorp.com> Message-ID: <2vec8LAyk7f8EwEi@jessikat.demon.co.uk> In article , Thomas Heller writes >"Robin Becker" wrote in message news:PtFyMdAeY5f8Ew >jI at jessikat.demon.co.uk... >> after investigation it seems that module nt is using >> cmd.exe /c string >> >> to run programs and I can't find any way to quote things in the string. >> A typically rubbish M$-ism. >> -- >> Robin Becker > >On win2k it seems to be even documented (for the first time?): wow, well there's hope yet. I of course looked in the win2k help which is shorter than the /? output. I used this function to quote for passing to system def _quote(*args): fmt = max(map(lambda s: len(string.split(s)), args))>1 and '"%s"' or '%s' return fmt % string.join(map(lambda s: len(string.split(s))>1 and '"%s"' % s or s, args),' ') then I can do system(_quote(r'c:\program files\bingo\bango.exe', r'c:\test dir\my rubbish.txt')) and it seems to work. I guess spaces in filenames might be a pain everywhere in win32 land. Does the same work in other win32's? -- Robin Becker From jlh at cox.net Sat Mar 2 14:01:08 2002 From: jlh at cox.net (Jeff Hinrichs) Date: Sat, 02 Mar 2002 19:01:08 GMT Subject: Status of PEP's? References: Message-ID: "Carel Fellinger" wrote in message news:a5pmvd$fic$1 at animus.fel.iae.nl... > Jeff Hinrichs wrote: > > > What you are asking everyone to agree with is: > > 5 = [0,1,2,3,4] > > No he isn't:) He explicitly says he doesn't think of sequences at all. If it walks like a duck and talks like a duck... It's a duck. How can one iterate over something that is not a sequence/collection? > ... > > If you were to restate the above as: > > f(5)=[0,1,2,3,4] > > Then, I believe, that you wouldn't have any problem convincing a large > > majority that it is possible for f() to produce such an output. That being > > And this is precisly what he's proposing, f is called iter in his > case. But this is already in the language. It is called range/xrange. I haven't seen any argument on why range/xrange is less preferrable to iterable integers. I've heard the philosophical debate but not seen how python would be better for this addition. If a good, tangible case were made I could be influenced. It would have to be a stronger case than: for i in 5: is better than for i in range(5): print i print i I say that it isn't because the first case implies while the second case is explict. And it should show how my code would be improved in any of the following terms, a) readability b)robustness c)minimizing bugs >He comes from the camp that sees everything as an object, so > numbers are objects to. Hence integers know to do things, like > adding, subtracting, and ... counting! Three knows how to count from > zero upto but not including three. If you accept this, then the > discussion is not whether integers are sequences, but whether it's > natural to stretch Python's `for' construct to mean `count' or `over > its preceding numbers' in case of an integer. But I don't accept this. **Not everything is an object.** An apple is an object. A number is an abstact idea already. You can hold an apple. You can not hold a 7. A number is a property of something else. It is an atomic property. A number does not have ancestors nor children. Just because I have 7 apples doesn't mean that at one time I had 6. Numbers don't perform operations, you peform operations on operands. To make a number be able to count and perform operations on itself seems to me to be an extreme case of the tail wagging the dog. >Like the `for' > construct recently got stretched to mean `over all lines' and `over > its keys' for text-files and dictionaries. Admitted in those cases it > still was a clear `iterate over', but the what was debatable. The reason for this, is that it is natural to view a file/keys as a collection. It is not natural to consider a number as a collection of other numbers. > > > said, I would find that the argument favors the use of range/xrange over the > > concept of iterable integers. > > I'm still concerned how it releates to `programming for everybody', > as that goal is a sure measure to keep Python lean and simple. I am not sure whether you are referring to iterable integers or range/xrange by the above. > -- > groetjes, carel -Jeff Hinrichs From bokr at oz.net Sun Mar 10 17:37:45 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 22:37:45 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> Message-ID: On Sun, 10 Mar 2002 09:29:36 -0800, Gerhard =?ISO-8859-1?Q?H=E4ring?= wrote: >Grant Edwards wrote: >> If I did, couldn't I make all of >> "my" apps look in the same place for "my" DLLs? I really hate >> the idea of my app putting things in "system" directories. > >Sure you can. Just append to the PATH a directory where all your DLLs >go. This is of course best done with the installer. Here's a description >of how Windows searches for DLLs: > >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore/html/_core_The_Search_Path_Used_by_Windows_to_Locate_a_DLL.asp > I don't think they'll mind a quote snippet, do you? It'd be kind of stupid to paraphrase it. --- With both implicit and explicit linking, Windows first searches the set of pre-installed DLLs such as the performance library (KERNEL32.DLL) and the security library (USER32.DLL). Windows then searches for the DLLs in the following sequence: The directory where the executable module for the current process is located. The current directory. The Windows system directory. The GetSystemDirectory function retrieves the path of this directory. The Windows directory. The GetWindowsDirectory function retrieves the path of this directory. The directories listed in the PATH environment variable. Note The LIBPATH environment variable is not used. --- I.e., unless you are trying to override some pre-installed thing, just putting your DLL's in the same directory as your .exe ought to work. Regards, Bengt Richter BTW, you can't see the URL with Netscape 4.5. I wonder if their servers talk to IE in a special way ;-/ From grant53 at btinternet.com Thu Mar 28 09:55:34 2002 From: grant53 at btinternet.com (Grant Foster) Date: Thu, 28 Mar 2002 14:55:34 +0000 (UTC) Subject: Moving files Message-ID: Hi I am trying to move/delete files on my WinXp Pro system. I can copy files, but when I try and rename or unlink files I get an error saying that I don't have the correct permissions. I created all files and run them as the same user. Can anyone help? TIA Grant Foster grant53 at btinternet.com From susan at mars.provis.com Wed Mar 27 16:45:16 2002 From: susan at mars.provis.com (Susan Williams) Date: Wed, 27 Mar 2002 15:45:16 -0600 (CST) Subject: problems with circular references Message-ID: <200203272145.g2RLjG324197@mars.provis.com> > >I am working on python code that consist of quite a few files (about 50; >each file contains one class). All errors returned by functions are numeric >and are defined in the individual files. There is a MessageCatalog.py class >which will map these numbers into strings. This MessageCatalog.py has to >import all of the 50 other files to have access to their error numbers. So >far, so good - no problems yet. > >Here is the problem: Most of these 50 classes need to use the MessageCatalog >themselves. This means, of course, that classA imports MessageCatalog which >imports classA. This doesn't work very well. > >Does anyone have ideas on how to deal with this situation? > >Thanks, >Jim It sounds as though somehow or other you want to put the actual error number data for each class into MessageCatalog and give the 50 classes some interface for registering their error numbers with MessageCatalog. Then MessageCatalog is oblivious to what other classes there are, except that at run time they tell it about themselves. You could add another object for holding the error number data and have one instance per class---if that provides a convenient structure for accessing the error number data... susan From mtaylor at lowebroadway.com Mon Mar 25 05:37:24 2002 From: mtaylor at lowebroadway.com (Moray Taylor) Date: 25 Mar 2002 02:37:24 -0800 Subject: Root access with python Message-ID: Hi, I want to know how to run a 'root' command with python, i.e. mounting an NFS drive. On the terminal, you would do a 'su', type your password, then enter the command you wanted to run. How is this achieved within Python? My purpose is to make a small GUI app with PyQT to make mounting NFS volumes easier, I can handle the GUI bit, but I don't understand how to 'su'. Thanks for any help Moray From fperez528 at yahoo.com Sat Mar 2 04:13:38 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 02 Mar 2002 09:13:38 +0000 Subject: Python 2.2 seriously crippled for numerical computation? References: Message-ID: Huaiyu Zhu wrote: > There appears to be a serious bug in Python 2.2 that severely limits its > usefulness for numerical computation: > [snipped] Just to give some data points on this. I confirmed the problem on a Mandrake 8.1 box with python 2.2 built by hand, gcc 2.96. But the python 2.2 windows binary from python.org does NOT exhibit it in my WindowsXP box. The reuslt there is 1e-200**2 -> 0.0, as it should. I posted this report to the scipy-dev list to see if someone there (many linux users, all directly involved in numerical computing) can find out what the problem is. Cheers, f. From stevena at neosynapse.net Wed Mar 6 02:44:38 2002 From: stevena at neosynapse.net (Steven D. Arnold) Date: Wed, 6 Mar 2002 02:44:38 -0500 Subject: [ANN] istring 1.0.1 released; announce list created Message-ID: <118530121703.20020306024438@neosynapse.net> Neosynapse has released istring 1.0.1, a module for interpolating strings in Python. String interpolation means you can put variables directly in strings, like this: >>> from neo.istring import istring as i >>> n = 100 >>> s = i("Value is $n") >>> s "Value is 100" The new release fixes several small bugs. In addition, we have created an istring-announce list, which will receive information regarding minor version updates and bug fixes. To subscribe, go to: http://www.casti.com/mailman/listinfo/istring-announce. The istring download page is at: http://www.neosynapse.net/interpolated_string.htm -------------------------------------------------------------- Steven D. Arnold Neosynapse stevena at neosynapse.net Managing Partner AIM: abraxan MSN: neosynapse at hotmail.com From laurent.szyster at q-survey.be Fri Mar 29 06:47:25 2002 From: laurent.szyster at q-survey.be (Laurent Szyster) Date: Fri, 29 Mar 2002 12:47:25 +0100 Subject: chat server References: Message-ID: <3CA4544D.6646CB30@q-survey.be> Henning Peters wrote: > > i am planning to write a small chat server that uses select() in > python. multiple clients should be able to connect and chat wih > each other - like on a normal chatserver, just asynchronous ... Don't reinvent the wheel. Use asyncore.py and asynchat.py, it's part of the standard Python library. Laurent From martin at v.loewis.de Sun Mar 17 17:00:57 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Mar 2002 23:00:57 +0100 Subject: Still same bug even with email ver. 1.2 References: Message-ID: Sheila King writes: > What should I try next ???? If you think you found a bug, submit a bug report. If you know how to fix it, submitting a patch would be even more appreciated. Regards, Martin From tanzer at swing.co.at Thu Mar 14 12:51:00 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Thu, 14 Mar 2002 18:51:00 +0100 Subject: Why I think range is a wart. In-Reply-To: Your message of "Wed, 13 Mar 2002 11:48:12 EST." Message-ID: > > for index in range(len(mylist)): > > > > > > and in the body I need to make use of the indexes. I am not > > sufficiently qualified to say if this is Pythonic or not, but I find > > myself doing this quite often. > > It happens to me too, mostly when I'm using a sliding window > type algorithm, that is, I need to look at two adjacent members > of the list. You can't do this easily by iterating through the list; > unrolling the first entry and the last entry are a pain. I use a function pairwise to do such things: for l, r in pairwise(mylist) : Probably not as fast as index manipulation, but IMHO much easier to read/write/understand. -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From tim.one at comcast.net Fri Mar 29 14:50:13 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 29 Mar 2002 14:50:13 -0500 Subject: Python 2.2 chr representation errors with embedded C In-Reply-To: <000701c1d72b$b6a50c40$02ff1a42@peanut> Message-ID: [Mark Szigety; chopped python-dev from the address list] > I have recently made the upgrade to Python 2.2 from 1.5.2. In the > Python application which I develop, we have several embedded C > functions, one of which is a simple function to convert a hex string to > octal--it simply chars each byte and returns the new buffer. Post the function -- I can't guess what that means. > However, I have noticed a 0.01% error rate in Python 2.2 which I > did not see in Python 1.5.2 (it was 100% accurate). That is, 1 out > of 10,000 hex strings will be converted incorrectly in the C function, > usually one byte is returned as \x00 instead of what is should be. Post the function . > I also have noticed that in Python 2.2, chr(0xff) returns \xff instead > of \377 in Python 1.5.2. The return value of chr(0xff) has never changed. I expect you're mistaking the change in what repr(a_string) produces for a change in what chr() returns. repr(a_string) has changed to use hex escapes instead of octal escapes; chr() has not changed. Note that >>> '\377' == '\xff' 1 >>> in all versions of Python. > Could this be the source of the communication breakdown? No. > I should mention that writing a similar conversion function totally in > Python is 100% accurate in Python 2.2 as well as Python 1.5.2, although > it is an order of magnitude slower. Post your C function; it's quite likely got a subtle bug, or other C code is corrupting the memory it writes into. From duncan at NOSPAMrcp.co.uk Mon Mar 25 05:03:21 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 25 Mar 2002 10:03:21 +0000 (UTC) Subject: [albatross-users] Re: Python embedded like PHP References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> Message-ID: Dave Cole wrote in news:mailman.1016855556.16177.python-list at python.org: > You are forced to embed programming logic which is used to dynamically > alter the presentation of the interface directly inside the > presentation elements. I have a feeling that this makes the whole > template unduly fragile and resistant to change. I would have said you are forced to remove almost all programming logic from the template entirely and wrap it up in a separate script. All that is left in the template is the display logic. > The idea that an HTML developer who does not understand ZPT will be > able to ignore the ZPT attributes and just change the interface in > isolation is a fantasy. The ZPT attributes define an executable > program - their correct placement is critical to the functioning of > the template. Note that the same is true of Albatross tags, but you > can change the HTML in isolation to the Albatross tags. I agree with you here up to a point. I would break down the roles into html developer who needs to know some ZPT, presentation developer who just needs to know what not to touch, and content developer who just needs to know which parts of the page require content. You can even edit ZPT using Microsoft Frontpage, and mostly things don't break. If someone is simply adding content to a specified cell in a table, then they can edit happily within that cell. It would be nice though if the HTML editor could somehow be told to make the rest of the template readonly. I think that until I actually used ZPT, it wasn't obvious just how good a job it does of separating the logic, the presentation, and the content. In particular the CMF skins help a lot. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From Oschler at earthlink.net Tue Mar 5 01:41:06 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 5 Mar 2002 01:41:06 -0500 Subject: Get reference to "owner" Message-ID: I've never seen this feature in any programming language I've worked in but it can't hurt to ask. Can an aggregated class object get a reference to the class object that aggregates it? So if ClassAggregator contained an instance of ClassAggregatee is there a Python syntax/construct that a function in ClassAggregatee could use to get a reference to the instance of ClassAggregator that contained it? Thanks. From emile at fenx.com Wed Mar 6 08:38:24 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 6 Mar 2002 05:38:24 -0800 Subject: Pep 276 - if 6 were 9 Message-ID: If, in the beginning, Guido opted to call 'in' 'of', would there be a question of iterating over an integer? For example, for each of range(6): for each of mylist: for each of 6: I'm not advocating a change here, but just wondering how thinking in terms of 'in' vs 'of' might influence the debate. Or am I too far on the supporting side to appreciate that this has no bearing on it what-so-ever-thank-you-very-much? ;-) -- Emile van Sebille emile at fenx.com --------- From eppstein at ics.uci.edu Fri Mar 15 12:09:47 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 15 Mar 2002 09:09:47 -0800 Subject: ANN: Python Imaging Library 1.1.3 (march 15, 2002) References: Message-ID: In article , David Eppstein wrote: > > Version 1.1.3 adds distutils build scripts, improved resampling, > > screen grabbing support (windows only), and more. > > Any chance of adding box filters for higher quality downsampling? Never mind, looking through the online docs I found the new ANTIALIAS filter. Thanks, this should be very helpful! -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From bkelley at wi.mit.edu Wed Mar 27 11:27:35 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Wed, 27 Mar 2002 11:27:35 -0500 Subject: Tkinter: Why won't it work? References: Message-ID: <3CA1F2F7.8070306@wi.mit.edu> A.Newby wrote: > Hi. > > Below is an example exercise from "An Introduction to Tkinter" by Fredrik > Lundh. It simply creates a box with a quit button in it. Problem is, > everytime I click Quit, the program freezes. > > Is this a rare but well known bug with Tkinter, Python 2.2, or Windows 98? > Or is more probable that it's cuz my system is screwed? > > Does this problem exist when you hit the "QUIT" button or the "X" in the upper left corner of the window? This code seems to work fine in Python 2.2 windows 2000 but in chapter 7 of Introduction to Tkinter: =================== Note that even [though] you don't register an handler for WM_DELETE_WINDOW on a toplevel window, the window itself will be destroyed as usual (in a controlled fashion, unlike X). However, as of Python 1.5.2, Tkinter will not destroy the corresponding widget instance hierarchy, so it is a good idea to always register a handler yourself: top = Toplevel(...) # make sure widget instances are deleted top.protocol("WM_DELETE_WINDOW", top.destroy) Future versions of Tkinter will most likely do this by default. ==================== Here if you are ultra paranoid, you might want to alter the protocol of your root window as above. This is also handy for popping up a message box asking something like "Are you sure" for conformation. -Brian From cmkleffner at gmx.de Mon Mar 18 09:42:12 2002 From: cmkleffner at gmx.de (cmkl) Date: 18 Mar 2002 06:42:12 -0800 Subject: HP-UX, PyThread_* missing References: <1016327182.366474@cswreg.cos.agilent.com> Message-ID: <3b091a1c.0203180642.69cc22b3@posting.google.com> HP-UX 10.20 has user threads, HP-UX 11 has kernel threads (a POSIX threads implementation by HP) - and AFAIK HP-UX 10.30 has it. HP-UX 10.20 has located s subset of pthread call's in libcma - not enough for Python2.2. But I can remember, that prior python versions (2.0, 1.5.2 ??) could configured with threads. I can't test it anymore, because I have only access to HP-UX 11.00 at the moment. Another problem is, that the dynamic loader is not thread-safe in 10.20 (but it is in 10.30 and above) - see 'HP-UX Linker and Libraries Users's Guide' But in principle HP-UX 10.20 supports threads (user threads or green threads) and it is used i.e. with Java for HP-UX. Carl martin at v.loewis.de (Martin v. Loewis) wrote in message news:... > weeks at vitus.scs.agilent.com (Greg Weeks) writes: > > > In either case, though, "make test" fails at test_threads with: > > > > test_thread > > *** Termination signal 14 > > > > That was where I got stuck, and I'm *still* stuck. > > Does the test also fail if run on its own? I.e. what happens if you do > > ./python Lib/test/regrtest.py test_thread > > Also, since you said that threads work fine in 1.5.2 for you, what > happens if you run this test in Python 1.5.2? > > Regards, > Martin From nhodgson at bigpond.net.au Wed Mar 27 01:41:50 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 27 Mar 2002 06:41:50 GMT Subject: python, cvs, win32 -- slightly ot References: <3CA15642.7FA3E117@earthlink.net> Message-ID: Hans Nowak: > I use WinCVS: > > http://www.wincvs.org/ I like both the command line CVS tools installed by WinCVS and TortoiseCVS which adds CVS commands to the Windows Explorer and highlights file icons based on whether they are under CVS control (green) and changed from their archived state (red). May be too intrusive for some tastes. http://www.tortoisecvs.org/ Neil From jimd at vega.starshine.org Wed Mar 27 13:57:07 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 27 Mar 2002 18:57:07 GMT Subject: Why does this work? References: <3CA1BB93.FC00D40D@pop.ntlworld.com> Message-ID: In article <3CA1BB93.FC00D40D at pop.ntlworld.com>, a.clarke11 wrote: > Hi > I defined a class, and made an instance. The class sis not have a > def__init__() line. In the class, I defined a function f(x) and an list > object X.tiles. Why can I later call instancename.f, and > instancename.tiles? > I thought the class had to have a def__init__() line in it for this to > work? I would be glad if somebody could spell this out for me, although > it is working perfectly well in the finished program! > The relevant code is: You have the right to a constructor (def __init__()). If you do not have the skill or time to type in your own constructor one will be inherited into your class for you. You have the right to remain silent and Python will just do "the right thing(TM)" for you. A class is a template for creating objects. Objects, in Python, are namespaces containing members (variables) and methods (functions) (*and* containing linkages to parent classes through inheritance). So instance.f() and instance.tiles are instantiated into your objects because they were part of the template. Note that Tiles, Sound, and playlist from your example (below) are all *class members* rather than instance members. In other words they are shared by all instances. That's probably not what you want. You probably want playlist (at least) to be specific to each player (though your code is far to confusing for me to know what you're trying to do). Normally the __init__() (constructor) for a player in a game would initialize instance specific things like his or her "name" (or initials), "color" (or icon or "piece" (a la Monopoly) or other designator), and any initial score, tokens, money, "stats" or whatever. > class Player: > import random > Tiles=[] > Sound="click" > Win="yippee" > playlist=[] > def chooseTiles(x): > import random > random.shuffle(Setup.r) > x.Tiles=[] > while len(x.Tiles)<7: > l=0 > l=Setup.r.pop(random.uniform(1,len(Setup.r))) > x.Tiles.append(l) > x.Tiles.sort() > playstring=[] > Porky=Player() > Porky.chooseTiles() > Thanks in anticipation > Tony From dgallion1 at yahoo.com Thu Mar 14 14:07:40 2002 From: dgallion1 at yahoo.com (Darrell) Date: 14 Mar 2002 11:07:40 -0800 Subject: hack to exec a 'C' for loop Message-ID: I parse a lot 'C' code and should move to a real parser. Today I had to add a single kind of 'for' loop to the tool. Thought I'd share that for fun. If anyone knows of a cool tool :) It's a tricky problem when many symbols are undefined. And I only care about small parts of the code that for the most part are fully defined. The idea is to pull special data into a database to feed test tools and docs. So far it works and it's fast. Although the "for" loop thing is 10min old and here to be chopped up. --Darrell ### 'C' For loop test import re def ns(**kw): return kw def indentBlock(block, tab=4): tab=' '*tab lines=block.split("\n") lines=map(lambda l: (tab+l.strip()).rstrip(), lines) buf="\n".join(lines) return buf def fixPrintf(s): s=re.sub('printf\s*\(\s*(".*?"),(.*?)\);', 'print \g<1>%(\g<2>)',s) return s def fixForLoop(s): f,b,t = re.split("{|}",s) # No nested braces allowed mo=re.search( r"""(?x) \(.*?\s+ (?P[^=]+)=(?P[^;]); \s*(?P=var)\s*(?P[<>=]+)\s*(?P[^;]+); \s*(?P.*?)\) """, f) dict=mo.groupdict() if dict['compare']=="<" and re.match("%(var)s\s*\+\+"%dict,dict['operation']): buf="".join( ['''for %(var)s in range(%(start)s, %(limit)s-1):'''%dict, indentBlock(b)]) return buf def fixIt(s): s=fixPrintf(s) return fixForLoop(s) vars= ns(MAX_SAMPLES=5) s=""" for (int i=0; i < MAX_SAMPLES; i++) { printf("%d, %d",MAX_SAMPLES-i, i); } """ res=re.findall("(?s)(\n\s*for.*?;\s+})", s) for r in res: if len(r[0]): exec fixIt(r[0]) in vars From rasmussn at lanl.gov Wed Mar 13 11:10:45 2002 From: rasmussn at lanl.gov (rasmussn at lanl.gov) Date: Wed, 13 Mar 2002 09:10:45 -0700 Subject: Python on Windows soon forbidden by Micro$oft? In-Reply-To: Message-ID: On Tuesday, March 12, 2002, at 02:54 PM, phil hunt wrote: > > Lying to get money = fraud > > I think MicroShit's directors and laywers should be banged up for a > few years. Let me throw out a different interpretation on Microsoft's actions. As I was reading Microsoft's license, I thought of it in relation to the GPL. Maybe Microsoft is just covering it's backside so that users of their products won't use it in ways that will break the GPL. After all, the GPL forbids linking GPL code with non GPL code, i.e. MS libraries. At least I think so from reading the GPL FAQ (http://www.gnu.org/licenses/gpl-faq.html). For example, in answer to I am writing free software that uses non-free libraries. What legal issues come up if I use the GPL? The FAQ states: If the libraries that you link with falls within the following exception in the GPL: However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. then you don't have to do anything special to use them. In other words, if the libraries you need come with major parts of a proprietary operating system, the GPL says people can link your program with them. Since VC++ is not normally distributed with the operating system, I would assume that MS VC++ libraries are not compatible with GPL code. Now I should rush to point out that I don't know this to be the reason for Microsoft's license, I'm just wondering. Anyone more familiar with the law in this area care to comment? Craig From borcis at geneva-link.ch Mon Mar 4 04:00:27 2002 From: borcis at geneva-link.ch (Boris^2) Date: Mon, 04 Mar 2002 10:00:27 +0100 Subject: regular expression for nested matching braces References: Message-ID: <3C8337AB.2080806@geneva-link.ch> Darrell wrote: > > Tim Peters Explains it here. > http://groups.google.com/groups?th=ed6a75bc5eed7ee9&seekm=000401be9e6d%2427a98ec0%24029e2299 > > Searched on > "tim peters match" > It's result 203$ Tim expounds there that : >> "Regular expressions can't count" -- nested brackets are beyond their abilities. Nevertheless, searching google groups with "context-free expressions" turns up : http://groups.google.ch/groups?q=context-free+expressions&hl=de&selm=1v35mpINNl78%40uwm.edu&rnum=1 that tells a slightly different (and interesting) story. Boris From eppstein at ics.uci.edu Fri Mar 1 20:12:40 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 17:12:40 -0800 Subject: Status of PEP's? References: Message-ID: In article , James_Althoff at i2.com wrote: > I was thinking in a more general sense: I would like to create an iterator > with start, end, and step values and pass it into a function without first > actualizing it as a list (like one would have to do using for+relational in > conjunction with list comp.s). And use the same construct in for-loops, > list comp.s, etc. (For those just tuning in: I realize that I can create a > class for this -- actually, I already have. I'm refering to proposals for > new idioms in Python for iterating intervals of integers.) Well, you can still always use xrange... Or the recently proposed [yield x for ...] generator-comprehension syntax. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From peter at engcorp.com Sun Mar 10 15:19:32 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 15:19:32 -0500 Subject: ' in ' works, why doesnt ' in '? References: <4abd9ce7.0203081538.6ee9a2cc@posting.google.com> <4abd9ce7.0203090840.21a020eb@posting.google.com> <4abd9ce7.0203101059.444f1ec1@posting.google.com> Message-ID: <3C8BBFD4.A29A69F1@engcorp.com> damien morton wrote: > > Check this out: > > ('fox' in 'the quick brown fox') > ('the quick brown fox'.find('fox') != -1) > > Which of these expressions is clearer, more intuitive and convenient? > > I appreciate your thoughtfull comments, and I agree with you that > inconsistency should be avoided, but I would assert that this should > not be at the cost of intuitiveness, convenience and clarity. Inconsistency is neither intuitive nor clear (after the first impression at least). It may be convenient. On balance, it's never worth it. (Put another way, this question is a matter of opinion, and I'm afraid yours is outweighed by the mass of existing Python code and programmers. Nothing personal, but don't waste your time.) -Peter From mlerner at asteroids.gpcc.itd.umich.edu Thu Mar 14 12:45:51 2002 From: mlerner at asteroids.gpcc.itd.umich.edu (Michael George Lerner) Date: Thu, 14 Mar 2002 17:45:51 GMT Subject: YANRQ (yet another regex question) References: Message-ID: Tim Peters wrote: > [Michael George Lerner] >> I'd like to rewrite my regular expression to match any of these, >> and I'd really rather not write it all out like this: >> >> (?P(foo | foo | foo | foo | foo|) > That will also match an empty string (remove the last vertical bar; ditto > the 2nd left paren). Oops. That's what I get for retyping things quickly instead of cut 'n pasting them. >> Is there some easy way to do this that I've overlooked? > You already found an easy way . If you ask whether there's an easier > way, the answer is no. hrmph. oh well. at least i can save myself some time with this: >>> def getPat(text, patLength, padChar = ' ', patName = None): ... text = text.strip() ... if patName is None: ... patName = text ... assert len(text) <= patLength ... numPadChars = patLength - len(text) ... pats = [] ... for i in range(numPadChars + 1): ... pats.append(padChar * i + text + padChar * (numPadChars - i)) ... return r'(?P<%s>%s)' % (patName, '|'.join(pats)) ... >>> getPat('foo',7) '(?Pfoo | foo | foo | foo | foo)' >>> getPat('foo',7,'.') '(?Pfoo....|.foo...|..foo..|...foo.|....foo)' >>> getPat('foo',7,'.','flonk') '(?Pfoo....|.foo...|..foo..|...foo.|....foo)' >>> getPat('foo',2) Traceback (most recent call last): File "", line 1, in ? File "", line 5, in getPat AssertionError >>> r = re.compile(getPat('foo',7)) >>> len(r.match(' foo ').groupdict()['foo']) 7 >>> -michael From dalke at dalkescientific.com Tue Mar 12 13:34:46 2002 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 12 Mar 2002 11:34:46 -0700 Subject: doctest Hassles! References: <10d46bdc.0203120928.7e9c708b@posting.google.com> Message-ID: Douglas Garstang: > when I print the value of ls, I get: > >' > example.py > example.pyc > tester.py > >' > >Notice the blank line at the end. Where did that come from? The print statement adds its own newline to the end. Instead, try it without the print. >>> import os >>> ls=os.popen("/bin/ls","r").read() >>> ls example.py example.pyc tester.py >>> I've also found it useful to end the doctest with an empty '>>>'. Andrew dalke at dalkescientific.com From logiplexsoftware at earthlink.net Tue Mar 12 19:10:41 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Tue, 12 Mar 2002 16:10:41 -0800 Subject: is time.sleep a thread safe function? In-Reply-To: References: Message-ID: <20020312161041.17af899b.logiplexsoftware@earthlink.net> On 12 Mar 2002 15:47:10 -0800 Zihong Lu wrote: > Can someone please tell me the answer? > > Recently, we have seen some weird behaviors in our python application > in Solaris 2.6, 2.7,and 2.8 platform. The application is a web based > server, that uses threads heavily. It runs fine in Linux and win32 > platforms, but in Solaris, it stopped accepting after ran for couple > of hours. One of our guesses is that the time.sleep() used through > out our application is not thread safe. Can any one please help us > eliminate/confirm this factor? Thanks. AFAIK, time.sleep() is thread-safe. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From jeff at ccvcorp.com Fri Mar 15 19:31:53 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 15 Mar 2002 16:31:53 -0800 Subject: Parsing string into fixed-width pieces References: Message-ID: <3C929279.E734152C@ccvcorp.com> "Johnson, Brad" wrote: > I'm new to Python and have been combing the documentation and the message > archive here for information on splitting a string into fix-width pieces. I > assume their is an easy way to do this, I just don't seem to be able to find > it in the reference material. Any suggestions? Something like this, perhaps? >>> mystring = "123456789ABCDEF" >>> mylist = [mystring[x:x+3] for x in range(0,len(mystring),3)] >>> mylist ['123', '456', '789', 'ABC', 'DEF'] >>> Note that it's not terribly common to want to split a string in fixed width pieces. It's far more common that there's some sort of delimiting character that you want to break on, and for those cases, there's the split method: >>> mystring = "123,456,789,ABC,DEF" >>> mylist = mystring.split(',') >>> mylist ['123', '456', '789', 'ABC', 'DEF'] >>> Hope that helps... Jeff Shannon Technician/Programmer Credit International From dpeter at designtheory.org Fri Mar 15 17:55:00 2002 From: dpeter at designtheory.org (Peter Dobcsanyi) Date: 15 Mar 2002 22:55:00 GMT Subject: Why I think range is a wart. References: <7UYj8.31929$l93.6269941@newsb.telia.net> Message-ID: Bengt Richter wrote: > I wonder how the proportions would change if len(ls) > were 1,000,000 instead of 1,000 > and/or if you used xrange in place of range. Good question, as it turned out. I timed only the following methods: def foo(ls, q): for i in range(len(ls)): if ls[i] == q: return i def xfoo(ls, q): for i in xrange(len(ls)): if ls[i] == q: return i def bar(ls, q): i = 0 for x in ls: if x == q: return i i += 1 If you have to go over (almost) the entire list then the proportions don't really change. len(ls) = 1000 search for "998" repeat 3000 times i in range(len(ls)): 2.02 i in xrange(len(ls)): 2.25 x in ls; i+=1 : 2.24 ---------------------------------------------------------- len(ls) = 10000 search for "9998" repeat 3000 times i in range(len(ls)): 23.71 i in xrange(len(ls)): 25.04 x in ls; i+=1 : 25.44 ---------------------------------------------------------- len(ls) = 100000 search for "99998" repeat 3000 times i in range(len(ls)): 212.83 i in xrange(len(ls)): 220.57 x in ls; i+=1 : 257.96 ---------------------------------------------------------- But when the number of iterations over the list is small compared to the length of the list then xrange and the counting methods obviously win. In all cases below I have searched for '998'. len(ls) = 1000 search for "998" repeat 3000 times i in range(len(ls)): 2.02 i in xrange(len(ls)): 2.26 x in ls; i+=1 : 2.28 ---------------------------------------------------------- len(ls) = 10000 search for "998" repeat 3000 times i in range(len(ls)): 3.36 i in xrange(len(ls)): 2.19 x in ls; i+=1 : 2.27 ---------------------------------------------------------- len(ls) = 1000000 search for "998" repeat 3000 times i in range(len(ls)): 22.40 i in xrange(len(ls)): 2.22 x in ls; i+=1 : 2.57 So it depends :-) Peter From anders.eriksson at morateknikutveckling.se Fri Mar 22 05:48:30 2002 From: anders.eriksson at morateknikutveckling.se (Anders M Eriksson) Date: Fri, 22 Mar 2002 11:48:30 +0100 Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: <1o2m9ucoqb9qqs2fcign6sts3ckc3mqkma@4ax.com> Hello Jim! I tried to run the program in Python 2.1 but I get errors >if __name__ == '__main__': > wcount = Wordcount() > for i in sys.argv[1:]: > file = open(i,"r") > for line in file: Here I get the error ^ for line in file: TypeError: loop over non-sequence Is this something specific for Python 2.2, or just a typo? // Anders From vince at news.videotron.ca Mon Mar 18 13:02:08 2002 From: vince at news.videotron.ca (Vincent Foley) Date: Mon, 18 Mar 2002 18:02:08 GMT Subject: XML help Message-ID: Hi, I have a XML document . I want to put the latest_version value in a variable. How would I do that? Thanks -- Vincent Foley-Bourgon Email: gnuvince at yahoo.ca Homepage: http://darkhost.mine.nu:81 From gmcm at hypernet.com Sun Mar 10 07:42:36 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 10 Mar 2002 12:42:36 GMT Subject: TkInter/McMillan installer question. References: <21298535.0203091603.337835a@posting.google.com> Message-ID: Svein Brekke wrote: > Hi there. I've got a Tkinter application for portuguese vocabulary > training, and I'm trying to distribute it through McMillans installer. > The installer is excellent except for one problem I have not been able > to solve. Could anyone please help me? > > My configuration is: Win2KPro, python 2.2b1, McMillan installer 5 > alpha1 > > Concider the following program (call it test.py): > > --8<-------------------------------8<----------------------------- > import Tkinter # I have also tried: ,unicodedata,codecs [snip] For 5a1, an "import codecs" is needed to include all the codecs. For 5b2, you get codecs unless you specify --ascii to Makespec.py. With 5b2, I get the same answer from the exe as I get from running it in Python: the round trip doesn't work. I assume that's because Tk makes it's own (conflicting) assumption about encoding. -- Gordon http://www.mcmillan-inc.com/ From garret_mcgraw at yahoo.com Mon Mar 18 18:14:48 2002 From: garret_mcgraw at yahoo.com (Garret McGraw) Date: Mon, 18 Mar 2002 18:14:48 -0500 Subject: Digest Number 868 In-Reply-To: <1016408215.641.83517.m12@yahoogroups.com>; from python-list@yahoogroups.com on Sun, Mar 17, 2002 at 11:36:55PM -0000 References: <1016408215.641.83517.m12@yahoogroups.com> Message-ID: <20020318181448.A970@wood.mcgraw.org> Hi- Does any know a good way to talk to a mysql database besides depending on the fact that the computer might happen to have that mysql module installed? I guess I could just figure out how the protocol works and access it by opening a socket to it and interpert what it gives me...... but I would like to know if someone has already done that and see if i could download it. It can be very simple...just as long as its there and it will do simple things. If there is no such thing then does anyone just think this is a project that could not done right? Let me know what you think about it. GEM From mwh at python.net Mon Mar 18 12:06:35 2002 From: mwh at python.net (Michael Hudson) Date: Mon, 18 Mar 2002 17:06:35 GMT Subject: Still same bug even with email ver. 1.2 References: <7876a8ea.0203180837.4aaa1542@posting.google.com> Message-ID: woodsplitter at rocketmail.com (David Rushby) writes: > And here's SourceForge bug #491612 (closed now), which was filed to > report this very bug: > http://sourceforge.net/tracker/index.php?func=detail&aid=491612&group_id=25568&atid=384678 > > Unfortunately, contrary to Oleg's assertion in c.l.py and Barry's in > his message added to the SF bug report, the CVS version of has *not* > been fixed. Are you sure? It's certainly possible, but I think revision 1.6 of Lib/email/Parser.py, which became revision 1.5.10.1 on the release22-maint branch, was certainly aimed at fixing this bug. > The bug is a showstopper for the email package (it stopped my show, > at least), but the fix is quite simple. Could we get it fixed > before the final release of Python 2.2.1? If it's not already, probably. 2.2.1c1 is imminent (later today, I hope) and it's too late to change that. > Should someone resubmit the bug to mimelib's SourceForge bug tracker, > or will this message be enough? First it would be good if you could supply some evidence that the bug isn't, in fact, fixed. Cheers, M. -- [Perl] combines all the worst aspects of C and Lisp: a billion different sublanguages in one monolithic executable. It combines the power of C with the readability of PostScript. -- Jamie Zawinski From bh at intevation.de Fri Mar 1 09:37:45 2002 From: bh at intevation.de (Bernhard Herzog) Date: 01 Mar 2002 15:37:45 +0100 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: <6q3czkqrpi.fsf@salmakis.intevation.de> James_Althoff at i2.com writes: > [Aahz Maruch] > > My primary complaint about the PEP is that the following idiom is > > awkward, ugly, and prone to misunderstanding: > > > > if i in 5: > > I will note this. > > However given that current Python seems able to do type-checking on strings > used with "in" as in, for example: > > >>> 1 in 'spam' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'in ' requires character as left operand > >>> That's because strings implement the in operator. However, Python is smart enough to make in work for iterable objects. Quick experiment (Python 2.2): >>> from __future__ import generators >>> class MyInt(int): ... def __iter__(self): ... for i in range(self): ... yield i ... >>> num = MyInt(3) >>> for i in num: print i ... 0 1 2 >>> 1 in num 1 Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://mapit.de/ From tl_news at nexgo.de Fri Mar 15 05:17:13 2002 From: tl_news at nexgo.de (Tino Lange) Date: Fri, 15 Mar 2002 11:17:13 +0100 Subject: does Python support some kind of "casting" References: Message-ID: Duncan Booth wrote: Hi Duncan! Thanks for your answer! >> So the best solution is to transport an object like >> return list(newlist) >> >> But I guess this makes a temporary copy of my MaxSizedList just for the >> XML-RPC-transport, or? So it's horrible inefficient? >> > Yes, that will make a copy. But copying a list is a pretty efficient > operation, so no, it isn't really horribly inefficient. Have you tried it > and identified this as a bottleneck? How long are your lists anyway? 3600 Elements each. No I didn't check if it's a bottleneck. But I immediately didn't feel good when writing "return list(newlist)" (the list contains a list of strings itself - so it's much stuff to copy) > One way to do this that avoids the copying is to aggregate a list object > into your class instead of trying to subclass the list type. Then you can > simply return the internal list object if you want. I think I'll do that. Funny: This is the userlist-approach - so despite having the new 2.2 feature of subclassing it's better to use the old userlist. > However, from your description I would be much more worried about the > throwing away elements from the front of the list every time you append to > the end of the list. I do hope you are batching these up into large chunks > to be discarded, not throwing them away one or two at a time. Of course :-) This logic took most of the implementation time. But I can just copy it in the userlist MaxSizedList - that's no problem. Thanks! Best regards Tino From jeff at ccvcorp.com Thu Mar 7 20:03:53 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 07 Mar 2002 17:03:53 -0800 Subject: Status of PEP's? References: Message-ID: <3C880DF9.4236BF90@ccvcorp.com> James_Althoff at i2.com wrote: > 2) The "indices" approach is not general enough to handle the example used > in PEP 276. > > >>># not the real thing, but an incredible simulation > >>> > >>>for rowindex in indices(mytable): > >>> print mytable.getValueAt(rowindex,0) > >>>... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: len() of unsized object > >>> However, neither would "for rowindex in mytable" work. In either case, you'd need to use something similar to mytable.GetRowCount(). >>> for rowindex in mytable.GetRowCount(): or >>> for rowindex in xrange(mytable.GetRowCount()): (In this case, since we don't need to grab the collection of rows, we'd use xrange() instead of indices(), but the effect is the same. All that PEP 276 seems to be gaining us, to my mind, is a not needing to type a single function name.) Jeff Shannon Technician/Programmer Credit International From matkin at iar.se Thu Mar 21 09:55:00 2002 From: matkin at iar.se (Mats Kindahl) Date: 21 Mar 2002 15:55:00 +0100 Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: jimd at vega.starshine.org (Jim Dennis) writes: > In article , Nick Arnett wrote: > > > Anybody have any experience generating word frequencies from short documents > > with Python and Perl? Given a choice between the two, I'm wondering what > > will be faster. And a related question... any idea if there will be a > > significant performance hit (or advantage?) from storing the data in MySQL > > v. my own file-based data structures? > > > I'll be processing a fairly large number of short (1-6K or so) documents at > > a time, so I'll be able to batch up things quite a bit. I'm thinking that > > the database might help me avoid loading up a lot of useless data. Since > > word frequencies follow a Zipf distribution, I'm guessing that I can spot > > unusual words (my goal here) by loading up the top 80 percent or so of words > > in the database (by occurrences) and focusing on the words that are in the > > docs but not in the set retrieved from the database. > > > Thanks for any thoughts on this and pointers to helpful examples or modules. > > > Nick Arnett > > I don't know what you're really trying to do, but I decided to > code up a quickie "word counter" for the hell of it. > > I started with one that would simply count "words" (white space > separated sequences of letters, hyphens and apostrophes). I then > decided to also denote which of them were "known" words and keep > a count of those as well. > > So, here's my very own version (in about 80 lines): > > > #!/usr/bin/env python2.2 [program removed] > I tested by running the following commands: > > for i in /bin/* /usr/bin/*; do > bname=$(basename $i); man $bname | col -b > /tmp/$bname.man > done > > time ./wordcount.py /tmp/*.man | hea speed. > > Here's the output from that: > > 1602048 1361723 36978 0.849988889222 0.0271553025101 > 117960 the* > 41673 to* > 36275 is* > 34975 a > 32191 of* > 27045 and* > 22881 in* > 20336 for* > 17571 be* > Traceback (most recent call last): > File "./wordcount.py", line 81, in ? > print "%7d %s" % (count, word) > IOError: [Errno 32] Broken pipe > > real 1m48.212s > user 1m47.950s > sys 0m0.250s > $ ls /tmp/*.man | ./wc.py > 1761 1761 31804 > $ du /tmp/*.man > .... > 15836 total > $ find /tmp/*.man -printf "%s\n" \ > | awk '{n++; t+=$1}; END { print t/n ; }' > 7104.33 > > ... so it handled over 1700 medium size files (average 6K each, > about 14Mb total) in less than two minutes. Of the words I > counted it looks like about 84% of them were "known" words from > /usr/share/dict/words; and it looks like I found about 2% of the > known words. (In other words, the Linux man pages only use about > 2% of the English vocabulary). I doubt the top ten words from my > list will surprise anyone: the, to, is, a, of, and, in ... > > I don't have the urge to write a version in Perl. Not tonight > anyway. Just to have something to compare with, you here have a Perl version that does something I belive is along the same lines. #!/usr/bin/perl my %dict; my %known; my $known_words = 0; open(DICT,"/usr/share/lib/dict/words") or die "open: $!\n"; { my @words = ; # Read all the words into a list chop @words; # Drop the trailing newlines $known_words = @words; # Count known words # Enter the list of words into a hash @known{@words} = (1) x $known_words; } close(DICT); undef $/; # Read each file in one go while (<>) { chop; # Drop trailing newline foreach (split(/\s+/)) { s/\'$|^\'|\'ll$|n\'t|\'s//; next if /^-|-$|\W|^\s*$/; ++$dict{lc $_}; ++$total; } } print "Known: $known_words words, total: $total words\n"; foreach (sort { $dict{$b} <=> $dict{$a} } (keys %dict)) { print "$dict{$_} $_*\n" if $dict{$_} > 1; } I tried it on only approx. 600 manual pages, with the result: bash-2.01$ time perl wordcount.pl tmp/* | head Known: 25143 words, total: 464709 words 44362 the* 13174 is* 12593 of* 11907 a* 11859 to* 8735 and* 7438 in* 6255 for* 6044 if* Broken Pipe real 0m42.669s user 0m22.190s sys 0m0.360s > Of course this script is free for any use you can think of. Same here. Good luck, -- Mats Kindahl, IAR Systems, Sweden Any opinions expressed are my own, not my company's. From mikeb at mitre.org Wed Mar 13 18:56:45 2002 From: mikeb at mitre.org (Mike Brenner) Date: Wed, 13 Mar 2002 18:56:45 -0500 Subject: possible string.strip memory leakage Message-ID: <3C8FE73D.3A03C085@mitre.org> There might be a memory leak in string.strip. I wrote a python function to strip blanks off the left and right of a string. When I discovered string.strip, I replaced the call to my version with string.split, and I got a large memory leakage. When I put the call back to calling my python function, the memory leakage went away. From gerhard at bigfoot.de Wed Mar 27 07:31:23 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 27 Mar 2002 12:31:23 GMT Subject: Looking for a python shell under linux like PythonWin References: Message-ID: In article , newgene wrote: > Hi, group, > The only python shell under linux I can find is IDLE, but it is > not as good as PythonWin. A important feature "Attribute expansion"(a > list of attributes for selection when pressing period after a module > name) is not available. Is there a good python shell existing on linux > now? PyCrust does this (http://sourceforge.net/projects/pycrust): PyCrust is an interactive Python shell written in Python using wxPython. Gerhard From gcordova at hebmex.com Thu Mar 14 12:08:17 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 14 Mar 2002 11:08:17 -0600 Subject: Performance problem with filtering Message-ID: <19650FF08A99D511B19E00B0D0F0632301D68955@SRM201002> > > Anybody wrote a subclassed list yet that is optimized for > __contains__? Btw. > this is different from a dictionary, as a list can contain > the same value twice. > > Gerhard > -- The main hurdle is that the list is a general-purpose list, and that means that you can't make any assumptions about the data. To make a fast list --for searches--, either: 1. Keep it sorted, and do a binary search when you need to find an element. 2. Keep it in a tree, and do a tree search when looking for an element. Duplicated elements impact on the performance of this. -gustavo From just at xs4all.nl Mon Mar 4 06:46:17 2002 From: just at xs4all.nl (Just van Rossum) Date: Mon, 04 Mar 2002 12:46:17 +0100 Subject: problem with locale References: Message-ID: In article , "marcin andrzejewski" wrote: > everything works fine in IDLE, but when running as script, i 've got > following error: > > import locale > locale.setlocale(locale.LC_ALL, '') > a= locale.format ('%.2f',-100000.236,1) > > Traceback (most recent call last): > File "locale.py", line 1, in ? > import locale > File "locale.py", line 2, in ? > locale.setlocale(locale.LC_ALL, '') > AttributeError: 'module' object has no attribute 'setlocale' > >Exit code: 1 > > what's wrong ? I think your script is called locale.py: Python will find it before the "real" locale.py is found when importing. Just From mwh at python.net Fri Mar 1 05:14:16 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 1 Mar 2002 10:14:16 GMT Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <20020227163411.71b4b4d8.alex@netWindows.org> Message-ID: Dennis Roark writes: > The Python book appears substantially based on the templates of > their previous books. Certainly the first draft of chapter 2 that I reviewed[0] looked suspiciously like the corresponding chapter from Java:HTP. That went back with a lot of red ink on it... Cheers, M. [0] My, there were a lot of reviewers weren't there? -- same software, different verbosity settings (this one goes to eleven) -- the effbot on the martellibot From martin at v.loewis.de Tue Mar 19 16:00:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Mar 2002 22:00:01 +0100 Subject: Chewing international (unicode) filenames on windows? References: Message-ID: "Neil Hodgson" writes: > It is the right approach but in terms of packaging its a mess and this > will have a maintenance cost. Perhaps moving all the NT specific Unicode > handling into a separate file would help although I haven't seen a clean way > to do that either as it will then require a bunch of forwarding functions. > If there was a good way to subclass posixmodule for this code... Subclassing may not be the right solution - perhaps it is better to admit that ntmodule.c really should be different from posixmodule.c. What do you think? Regards, Martin From writeson at earthlink.net Thu Mar 7 21:41:45 2002 From: writeson at earthlink.net (Doug Farrell) Date: 7 Mar 2002 18:41:45 -0800 Subject: Text Search Engine that works with Python References: Message-ID: <88bc63c6.0203071841.1867a977@posting.google.com> To everyone, Thank you for all the feedback, I really appreciate it. Here is some more detail about what I'm looking for and how it should work, this may or may not be helpful . One of the things my company works on is a large reference title that is sold on CD-ROM. The current un-compressed text is 70 megs. The reason we compress that currently is because of all the other media that goes on the CD. Our current search engine is a piece of junk, but works in the C++ environment of our current application, which is only for Windows. I am considering an alternative with Python for a couple of reasons. Easier to write than C++. The app is not speed critical and I think Python would be more than fast enough anyway, I'm considing wxPython as the GUI, so most of the window calls are implemented in C anyway. Writing the app in Python would possibly allow us to market the CD for Windows, Mac, Linux and Unix systems. So the requirements of the search engine are that it compress the text (or have index files so small that compression is un-necessary) and the retrieval engine have an API accessible to Python, not implemented as a command line tool. I want to incorporate the search engine into a larger application that links the text together with media. I know, I know, big demands, but that's why it's in the conceptual stage with me right now. Anyway, hope that adds more information to the thread. Thanks again, Doug mertz at gnosis.cx (David Mertz, Ph.D.) wrote in message news:... > |Here is a related question -- Is there a search program for > |structured text files, in particular something that searches XML > |files. > > You might like my xml_indexer program. There is a writeup on the design > at: > > http://gnosis.cx/publish/programming/xml_matters_10.txt > > As with indexer, from which xml_indexer is derived, the module has been > aggregated into a package found at: > > http://gnosis.cx/download/Gnosis_XML_Utils-0.9.tar.gz > > Yours, David... From eppstein at ics.uci.edu Mon Mar 4 20:08:46 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 04 Mar 2002 17:08:46 -0800 Subject: Status of PEP's? References: Message-ID: In article , James_Althoff at i2.com wrote: > Yes, I'll grant "is at least consistent". But, in the case of the > for-loop, at some point -- rather quickly I suspect -- you are going to > have to leave the realm of relational operators and get right back to > talking about iterators. Because you're going to have to explain why > for x <= i <= y: > works and why > for x <= i and i != y: > is a syntax error. For the same reason that for item in list works but for dictionary.has_key(item) doesn't: The for-loop syntax only allows a very restricted set of expressions that it knows how to handle. The current set consists only of expressions like "item in list". The proposal is to extend it to also include three-way comparisons. > And why > for i < rowcount: > uses "i" as the loop variable instead of "rowcount" -- or does it? > for rowcount < i: > How would Python decide? It wouldn't -- that is not one of the expressions proposed to be allowed in a for loop. > And if it can't, then does this mean that the idiom cannot support > shortcuts for the common case of iterating the indices of a list? So, do > we have to write: > for 0 <= i < rowcount: > specifying the "0 <=" part every time? Yes. One could extend the proposal to allow two-way comparisons that start at zero, but that wouldn't be in the spirit of the proposal, because your suggested "for i < rowcount" wouldn't loop over all those i for which "i < rowcount" is true (it would skip negative i). And of course, there is no logical contradiction between the proposed new syntax and PEP 276, once one accepts that PEP 276 defines a meaning for the expression "i in 276" and not just the loop "for i in 276". From frr at ThouShallNotSpam.EasyJob.NET Fri Mar 8 05:09:13 2002 From: frr at ThouShallNotSpam.EasyJob.NET (Fernando Rodríguez) Date: Fri, 08 Mar 2002 11:09:13 +0100 Subject: Text Search Engine that works with Python References: <88bc63c6.0203071841.1867a977@posting.google.com> Message-ID: On 7 Mar 2002 18:41:45 -0800, writeson at earthlink.net (Doug Farrell) wrote: >is because of all the other media that goes on the CD. Our current >search engine is a piece of junk, but works in the C++ environment of >our current application, which is only for Windows. I am considering What are you using? Decent and unexpensive IR systems aren't very common. Maybe MySQL is enough (they now have full text indexing). You may consider: a) http://www.lextek.com/onix/ (never used it) b) http://200.6.42.16:2001/p_isis_dll.html (In portuguese, though the manuals are in English). Used to be very unreliable but apparently it has improved. c) Altavista's sdk. Whatever you use, you will probably have to write the Python interface. If I was in your situation I would write a Python interface to the mg system that someone already recommended to you... | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Fernando Rodr?guez frr at EasyJob.NET | http://www.EasyJob.NET/ | Expert resume and cover letter creation system. | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From philh at comuno.freeserve.co.uk Mon Mar 25 11:48:50 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 25 Mar 2002 16:48:50 +0000 Subject: list comprehension question References: Message-ID: On Sun, 24 Mar 2002 17:44:44 -0800, Emile van Sebille wrote: >brueckd at tbye.com >> >>> lo, hi = 1, 3 >> >>> [x/2 + 0.1*(x%2) for x in xrange(lo*2, (hi+1)*2)] >> > >Which, after only a few moments of inverse re-factorization as per YP* >practice, devolves into: > >>>> [round(map(float, [int(x/2) + 0.1*(int(x%2))])[0]*10)/10. > for x in map(int,xrange(lo*2, (hi+1)*2))] > >* something had to come before XP... ;-) WP, surely? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From dale at riverhall.NOTHANKS.co.uk Thu Mar 28 14:51:41 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 28 Mar 2002 19:51:41 +0000 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: Syver Enstad wrote: >Adding the registry settings so that one can drop data files on .py >and .pyw files and the files dropped will be received as commandline >arguments would also be nice. > I raised this issue some while ago. I don't think that's just a registry change. -- Dale Strickland-Clark Riverhall Systems Ltd From gmcm at hypernet.com Mon Mar 25 09:36:45 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 25 Mar 2002 14:36:45 GMT Subject: Installer 5b3 problem References: Message-ID: [posted and mailed] Zoltan Felleg wrote: > If this list is not the right place for this stuff, please redirect me > to the proper one (and forgive me for bothering you here). You'll usually get faster response on the Installer mailling list. See the bottom of mcmillan-inc.com/install5_ann.html. > I have a problem with the new mcmillan installer, namely the following > code freezes at the commands.getstatusoutput() line when its function > runs as a thread. The script itself works correctly, the "frozen" > executable does not. (It did work with installer 5b2). The system is Red > Hat Linux 7.2, with Python 2.2 compiled from source, and the database > (for the shelve) is gdbm. (I can use installer 5b2, but if the problem > is not in my script, it would be nice to have the next installer version > without this glitch). The script is as follows: The problem is solved by modifying iu.py. The line (around 273) that reads: mod = _self_doimport(nm, ctx, fqname) should become: try: mod = _self_doimport(nm, ctx, fqname) except: if threaded: self._release() raise I'll try to get that out (as 5b3.1) later today. -- Gordon http://www.mcmillan-inc.com/ From jjb5 at cornell.edu Wed Mar 27 14:32:03 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Wed, 27 Mar 2002 14:32:03 -0500 Subject: The Python Way References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: > In any large application, it gets *tiresome* to see this, particularly > if you add another layer of nested try/except. Thinking of automatic locking concepts, has there been a PEP for synchronized objects like Java? class Snorf: def __init__(self): self.lock = lock.lock() def doSomething(self,x) synchronize(self.lock): code It would be nice if the synchronize parameter could be an instance, class or module lock. Joel From tim.one at comcast.net Fri Mar 15 17:33:29 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 15 Mar 2002 17:33:29 -0500 Subject: Optimising list comparison In-Reply-To: Message-ID: [Graham Ashton] > A friend of mine is using Python in a research project where he needs to > compare each element of two vectors, such that comparing [a, b, c] and > [d, e, f] would involve comparing a with d, b with e and c with f. > > The only possible values in either list are 0, 1 and -1. When comparing > two values, if either value is set to -1 then both values are deemed to > be equal. So we've got: > > 0 == 0 > 0 == -1 > 1 == 1 > 1 == -1 > 1 != 0 I assume -1 == -1 too. > What he wants to know is simply whether all the values in the two lists > are "equal", in which case the comparison returns 1, otherwise it > returns 0. > > Now, having read Skip M's python optimisation page I would have thought > that the following example could be beaten into the ground by an > alternative involving map(). Obviously, a C extension would win the > grand prize, but I'm interested in learning some map() tricks.... > > list1 = [1] * 20 > list2 = [1] * 19 + [0] > > def compare(): > for i in range(len(list1)): > a = list1[i] > b = list2[i] > if (a != b) and (a != -1) and (b != -1): > return 0 > return 1 This will run *significantly* faster if you pass list1 and list2 to compare() as arguments (access to function locals is much quicker than access to globals). You could also exploit Python's chained comparisons: if -1 != a != b != -1: return 0 However, the order in which you wrote your compares strongly favors your specific test input, and the chained comparison would be significantly slower given your specific test input for that reason alone. If real life throws a "random" mix of -1, 0 and 1 at you, different ways of spelling the compares would be more effective. For example, your rules are such that "!=" is the correct result if and only if the sum of two elements is 1 (think about it: 0+0=0, 1+1=2, -1+i <= 0 for every i in {-1, 0, 1}, and 1+0=0+1=1; the last is the only case in which the sum is 1). So if list1[i] + list2[i] == 1: return 0 should work fine, and runs at the same speed regardless of relative frequency of the various input-pair possibilities. Then it's actually quite difficult to explain why import operator def attempt5(list1, list2, sum=operator.__add__): return 1 not in map(sum, list1, list2) isn't quicker than an explicit loop doing the same thing. > Neither of us have yet managed to come up with anything to beat it > (we've been timing the alternatives over 100000 itterations). Keep trying . Also give for a, b in zip(list1, list2): a shot. It may surprise you . > Any hints? What I can't work out how to do is how to break out of a call > to map() if two values don't match. You can't, short of raising an exception. Whether you *want* to break out early depends on the expected distribution of input pairs; e.g., if, like the example you're timing, it's typical that the vectors start with a long stretch of equal elements, breaking early would be much more useful if you started comparing at the end. > The only thing I've come up with so far is this: > > func = lambda a, b: (a == b) or (a == -1) or (b == -1) or 1 / 0 > try: > map(func, list1, list2) > except ZeroDivisionError: > pass > > and though I felt quite smug when I'd thought of it, it's more than a > bit hacky. The raise and except also double the execution time on my > machine. Well, your specific test case always raises an exception. Exceptions are cheaper if they're not raised. In the intended application, what percentage of the time do you expect inequality to occur? An exception gets more attractive the less often inequality obtains. Note that having to use a lambda is also a drag on speed. map() speed tricks are much more effective if a builtin function can be mapped. However (and this is a clue to an earlier mystery), an infix "+" applied to integers is much quicker than operator.__add__ applied to integers. > Here's my complete script: > ... Thanks! That's very helpful. From killspam at darwinwars.com Sun Mar 3 08:38:52 2002 From: killspam at darwinwars.com (Andrew Brown) Date: Sun, 03 Mar 2002 13:38:52 GMT Subject: Black Adder and PyQt References: <3C80B1E3.575761B7@river-bank.demon.co.uk> Message-ID: Per Gummedal wrote in news:mailman.1015085345.6196.python- list at python.org: > From the BlackAdder readme file: > The license of the Beta version prevents run-time components of the > Business Edition being distributed with your applications. This > restriction will be removed when the final version is released. > Yes, but _when_ will the final version be released? Not that I have anything I might want to distribute, but I see fro my records that I paid for the beta nearly a year ago, and in that time there has been one update, last summer, and since then a resounding silence. It would be a shame if the project just sputtered and died. There are all sorts of unselfish reasons for hoping that some company (or kompany) figures out a way to make money from Linux sometime. From mwh at python.net Fri Mar 1 09:18:43 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 1 Mar 2002 14:18:43 GMT Subject: Apology to Bill Gates (was Re: ASV module, CVS modules) References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: Skip Montanaro writes: > John> Python, starting from a Unix background, where there is evidently > John> no such thing as an invalid character in a file name, ... > > I believe "/" is not allowed in Unix filenames. Not sure if this is > escapable or not. Don't think so. NULLs are out, too. Cheers, M. -- Presumably pronging in the wrong place zogs it. -- Aldabra Stoddart, ucam.chat From aahz at pythoncraft.com Tue Mar 26 22:54:32 2002 From: aahz at pythoncraft.com (Aahz) Date: 26 Mar 2002 22:54:32 -0500 Subject: list comprehension question References: <20020325113323.A26319@glacier.arctrix.com> <3C9FC8AD.CD82FEA0@engcorp.com> <3CA13DA5.DF1C3C7C@engcorp.com> Message-ID: In article <3CA13DA5.DF1C3C7C at engcorp.com>, Peter Hansen wrote: >Laura Creighton wrote: >>>Peter Hansen: >>> >>> If it's a bot, you don't have to apologize. Bots feel no emotion. >>> >>> And you're safe, too -- remember the First Law. >>> >>> -objectifying-tim-ly yr's, >>> Peter >> >> Tisk tisk. Only half of the apologising you do for the other person. >> The other half you do for yourself. > >Not sure I understand the sentiment, but perhaps it would have >helped you if I included an explicit smiley? That _was_ a joke. >Happily, I think from Tim's reply he understood and took it that way. >(The reference to Asimov might be obscure to some. Sorry.) > >Thanks for the gentle advice though. :) Um, Peter? I think the following quote from my .sig collection would be appropriate here (at least if I understand Laura correctly, and I think I do): "If sarcasm were posted to the Net, would anybody notice?" --JDN -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From cjw at sympatico.ca Sat Mar 23 12:56:11 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 23 Mar 2002 12:56:11 -0500 Subject: struct - Library Reference 4.3 Message-ID: <3C9CC1BB.A6C8A9C8@sympatico.ca> The struct doc provides information about the functions pack, unpack and calcsize, but none about error. When a pack error occurs, one is given a message such as: error: required argument is not an integer This gives no indication as to which of the argument's components is the source of the grief. Any information about the error function would be appreciated. Colin W. -------------- next part -------------- An HTML attachment was scrubbed... URL: From siegfried.gonzi at kfunigraz.ac.at Tue Mar 5 05:38:01 2002 From: siegfried.gonzi at kfunigraz.ac.at (Siegfried Gonzi) Date: Tue, 05 Mar 2002 11:38:01 +0100 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> <3C848DBE.CEF2A2F7@cs.kun.nl> Message-ID: <3C84A009.D0E65B6@kfunigraz.ac.at> Ronny Wichers Schreur wrote: > > Siegfried Gonzi wrote (in comp.lang.python): > > > After my nightmare using Clean [..] [Clean] is a useless big > > pile of shit! [..] Clean's array-type-system is an impudent > > scandal for its own > > As one of the Clean developers, I'm sorry to read that you're > frustrated with our language. There is more to say. > > I believe that you should use the right tools for the right > job. This depends on the job, but also on your own preference. > Judging from your comments you seem more at ease with a language > that's not statically typed and that doesn't enforce referential > transparency. A) No, No, No. This isn't about statically typed languages; at least not what I mean. Type checking is a tool, what I have written many times, which helps one produce readable code. The problem in Clean: the array concept is not a tool which helps a programmer it impedes the programmer. The problem is not that an array has a type the problem in Clean actually is that it is impossible often to judge what is allowed and what not. I started hating Clean when I had completed my program for a 2 dimensional Kriging interpolation. The code worked, but when I augmented it, it just behaved different, e.g. it was immediately not possible to assign a row in a calculation (but just before it *was* possible). I then had to copy the results back to the array via list/array-comprehension. B) Clean does often not work correctly. Look at my code which I have posted in comp.lang.python. Sometimes the code failed and the count_lines routine does not work. Last year I wrote some programs in Clean in order to translate some files: 12:03:2001,12:23:23,3.344,45.556,.. to the fractional part of the year. I had to translate about 50 stations. Sometimes the Clean function worked for that station sometimes not. Often I was forced to copy one content of a file to a file where just before the Clean version worked. And I had used then this file to translate "the other file". Btw.: I had downloaded the file-directory module, but at this time it was corrupted and I had always to restart the Clean program in every directory of the station (this was cumbersome). C) I wrote a program for a German colleague which reads in some numbers from a file and does perform some calculations. The version worked on the Mac but it only *sometimes* worked correctly on NT/XP/2000! Sometimes the first result was a wrong number, but sometimes not. And in turn I have just rewritten the version in C in order to deliver a program to a colleague. It was impossible to correct the Clean version. What should one do when it sometimes behave correct but sometimes not. CC) I am not sure whether I fooled myself or not: but reading a number from a console-command-line does not work. I had to use a readline and then get rid of the whitespaces. This was cumbersome. D) Last year I wrote some programs in order to calculate some summary-statistics: Mean, Median, Min, Max,.. It was impossible to augment the code. I wanted to augment it with the skewness but the compiler complaint (I would have to re-start the program to get the special compiler message, but I can send you the program if you like). It was not possible to add the calculation for the skewness. Maybe there were too many variables in a function (this was my guess at this time). I have used the R-language then to calculate the statistics. D) And the worst matter: There is no way to write numbers with a specific precision to a file. Fabian T.'s library just does not always work as expected. Point D is my greatest crtisim on Clean and the array concept. I really miss types but not as Clean demonstrates it. > Maybe Python with NumPy is the right choice for your job and [...] > Happy hacking. Thank your for your kind mail. I didn't contact any Clean developers, because still I think all there are kind guys which are working hard, but I am not sure anymore that they discern what people complain about.Surely, there a peoples who are not contented with the license-scheme (and open source); and others expect this; and others this; and others that. But shouldn't the following trigger the sirens: Did you observe that the user community is shrinking and shrinking and shrinking? I have to repeat myself: types are not my problem. If Clean hadn't performed as it had I would have never contemplated to throw it away. Regards, S. Gonzi From mwh at python.net Wed Mar 13 09:43:13 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 13 Mar 2002 14:43:13 GMT Subject: zlib vulnerabilities and python References: Message-ID: aahz at pythoncraft.com (Aahz) writes: > In article , > Robin Becker wrote: > > > >Does the recent zlib double free vulnerability > >http://news.com.com/2100-1001-857008.html > >impact zlib.pyd? > > Dunno, but I filed a SF bug to check compatibility with the new 1.1.4. But because mail from the sf tracker seems to be hitting the bit bucket, noone knows about this. Time to look at roundup again? The tracker on sf is starting to piss me off (even more). Cheers, M. -- We've had a lot of problems going from glibc 2.0 to glibc 2.1. People claim binary compatibility. Except for functions they don't like. -- Peter Van Eynde, comp.lang.lisp From skip at pobox.com Sun Mar 3 14:02:55 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 3 Mar 2002 13:02:55 -0600 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: <3c82575f$1_3@news.newsgroups.com> References: <3c82575f$1_3@news.newsgroups.com> Message-ID: <15490.29535.647204.404077@12-248-41-177.client.attbi.com> Brad> This also happens on Win2k with Python 2.2 Brad> P:\PUBLIC\DEMOS\WSOCK>python Brad> Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Brad> Type "help", "copyright", "credits" or "license" for more information. >>>> 1e-200**2 Brad> 0.0 >>>> 1e-200 Brad> 9.9999999999999998e-201 >>>> I believe your executable is working properly. The exponent range for IEEE floats is -308 ... + 308. 1e-200 is thus distinct from zero, but when you square it (1e-200**2), it's not. The problem people are having is that instead of silently underflowing to zero as you demonstrated, it's raising an OverflowError. This appears to be because glibc's pow() implementation isn't silently returning 0.0, but also setting errno to ERANGE. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From gh_pythonlist at gmx.de Tue Mar 19 17:35:19 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Tue, 19 Mar 2002 23:35:19 +0100 Subject: arrays help In-Reply-To: <000501c1cfb6$495eed80$77c75ed1@umesh> References: <000501c1cfb6$495eed80$77c75ed1@umesh> Message-ID: <20020319223518.GB3851@lilith.hqd-internal> Le 19/03/02 ? 18:23, Umesh Persad ?crivit: > Hi, > I am just getting started with Python from a c/c++ and Java > background. I am programming a game and I wanted to > represent a gameboard by a double subscripted array. > How do I do this in Python? Thanks, An easy way is to use a dictionary, mapping coordinates to the "stone" values, like this: cord = (0, 0) board[coord] = 'X' # put a 'X' stone on the field (0, 0) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.7 ?C Wind: 1.1 m/s From max at alcyone.com Wed Mar 20 17:22:58 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 20 Mar 2002 14:22:58 -0800 Subject: error:"_imaging C module is not installed" References: <3C989278.9189857C@helicon.net> Message-ID: <3C990BC2.C5745585@alcyone.com> Rodney Loisel wrote: > Just upgraded from PY 1.5.2 to 2.2.1c1 > and TCL 8.3 > Also installed PIL (Python Imaging Library) Your error means that PIL is not installed. Try installing it again. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From mwh at python.net Fri Mar 8 05:28:49 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 8 Mar 2002 10:28:49 GMT Subject: marcos and .pyc References: Message-ID: "dskhdskf dsfhs" writes: > Is there a feature in the basic python for doing inline marcos > (similar to the ones found in C and C++)? No. > Also is there a way to specify where .pyc files are to be deposited? No. Sorry, M. -- same software, different verbosity settings (this one goes to eleven) -- the effbot on the martellibot From grante at visi.com Sun Mar 10 12:56:56 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 17:56:56 GMT Subject: should i learn it first ? References: Message-ID: In article , G. Sumner Hayes wrote: > In article , Bengt Richter wrote: >>> >> I'd say if you don't know C, C++, or Python, then start with Python. >> Then C++, then C. In that order, you won't have to unlearn patterns >> of design you absorb solving problems with C. > > Ugh, I can see learning Python first but definitely learn C before > C++. Definitely. Also learn Scheme, Smalltalk, Modula-3, Prolog, Forth, and Bliss-32 before learning C++. Learning C++ at an impressionable stage will mess you up. -- Grant Edwards grante Yow! It's the RINSE at CYCLE!! They've ALL IGNORED visi.com the RINSE CYCLE!! From python at chajadan.net Fri Mar 1 22:15:36 2002 From: python at chajadan.net (chajadan) Date: Fri, 01 Mar 2002 19:15:36 -0800 Subject: wxPython error on import -- number 2 Message-ID: <5.1.0.14.0.20020301191524.00a82ec0@63.118.78.184> I get this error: from wxPython.wx import * SystemError: C:\Code\22\Objects\listobject.c:88: bad argument to internal function Now, there is no C:\Code\22\ anything on my comp, but maybe you guessed that. This error generates with or without the .wx on wxPython I'm on Windows, using python 2.2 and wxPython (Hybrid) for 2.2 hmm.... maybe it's this hybrid thing... any help, as always, gives me less work to do ;) --chajadan From a.h.batchelor at ncl.ac.uk Mon Mar 11 07:22:48 2002 From: a.h.batchelor at ncl.ac.uk (Andybee) Date: 11 Mar 2002 04:22:48 -0800 Subject: Newbie Import two coloums of floating point data into python HOWTO Message-ID: <7eb201fc.0203110422.1e9c7dec@posting.google.com> Dear All Can some one tell me how to import two coloumns of data in a ascii text file,into two arrays in python? I cant seem to work it out. The data is genereated in matlab and I want to import it into python Thanx in advance Andy From spokra at home.com Sat Mar 16 15:34:17 2002 From: spokra at home.com (Steven Pokrandt) Date: 16 Mar 2002 12:34:17 -0800 Subject: SocketServer.ThreadingTCPServer question Message-ID: trying to use the threading tcp server class. It all works right from a quick look. But when I run top I see many processes leading me to think it is really forking. I also can't get global varibles inside the thread. should I be able to have a varible in the main thread, and declare it global in a thread? I'm running linux (mandrake 8.1) both the default python 2.1.1 and the 2.2 that I compiled do the same thing. a ldd python shows that the pthreads.so is linked to python. What em I missing? From tshumway at uci.edu Sat Mar 23 01:08:11 2002 From: tshumway at uci.edu (Terrel Shumway) Date: Fri, 22 Mar 2002 22:08:11 -0800 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: On Fri, 22 Mar 2002 20:45:22 -0800, Walter Moreira wrote: > On Fri, Mar 22, 2002 at 02:59:15PM -0500, Barry A. Warsaw wrote: >> >> To maintain www.python.org, we use a web page templating system called >> `ht2html', which transforms .ht template files into .html files. > > Why not Zope, and Page Templates? > > Walter ht2html is a *much* lighter weight solution than Zope. The focus is on building static pages from templates, "way ahead of time", rather than "just in time". different problem --> different solution 8-) From mhammond at skippinet.com.au Mon Mar 18 17:28:02 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 18 Mar 2002 22:28:02 GMT Subject: Relieved but disappointed: The Pariah thread References: Message-ID: <3C9669FD.20706@skippinet.com.au> Tim Churches wrote: > > PS The newspaper article which prompted the post featured a picture of > Mark, and not only is his name remarkably similar to that of a famous > Australian National Park ranger, he even looks like a younger version of > Ed Devereaux...and his email address is mhammond at skippinet.com.au > ...hmmm. hehehe. When I was but a teenager, my shared name with this TV character bestowed me with the nickname "Skippy". To this day, my friends still call me "Skip". When I was looking for a business/domain name, I decided to try and meld this history into the name - hence skippinet! Who would have thought an Aussie version of Lassie (with a Kangaroo instead of a dog) would still be impacting my life :) Mark. From peter at engcorp.com Sun Mar 10 20:01:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 20:01:06 -0500 Subject: How "expensive" are Exceptions? References: <3c8bf3ef@nntp.server.uni-frankfurt.de> Message-ID: <3C8C01D2.F9CC7C73@engcorp.com> Michael 'Mickey' Lauer wrote: > > Hi, given the fact that excpetion handling can be very > expensive in languages like C++ - is python similar in > this aspect? [...] > Which version would be to prefer if the return types > are distributed evenly? > > try: > a, b = somefunc() > except: > return None > ... Never do this. :-) You have not specific which exception you are catching, so you'll quietly hide all exceptions including things like out of memory problems and so forth. In this case, a quick check at the interactive prompt reveals you should be looking for TypeError. > selection = somefunc() > if len( selection ) != 2: > return None > else: > model, iter = selection > ... Definitely less readable, isn't it? Given this sort of difference, you should probably be much less concerned with raw performance and more with readability and maintainability. Only optimize when you have actually hit a performance bottleneck. A search at Google with the search pattern "python exception handling performance" reveals the answer to your original question, no more than four hits down: http://aspn.activestate.com/ASPN/Mail/Message/python-list/998253 Short answer: exceptions are not expensive. -Peter From fredrik at pythonware.com Tue Mar 19 17:27:13 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 19 Mar 2002 22:27:13 GMT Subject: How to count pixels of a color in an image? References: <6b7cc392.0203191233.26760fc2@posting.google.com> Message-ID: <5XOl8.33425$l93.6577162@newsb.telia.net> "jjv5" wrote: > I need to count the number of pixels that are purple or blue-green in > a large image. I can do this with the Image module easily enough, > but it is painfully slow. I do something like this: > > green=0 > purple=0 > dat = im.getdata() > for i in range(len(dat)): > r,g,b = dat[i][0],dat[i][1],dat[i][2] > green = green + (( b>r) and (g>r)) > purple = purple + ((r>g) and (b>g)) > > The slow part is the for loop over the image data. Even if the loop > body is empty it still takes about 15 seconds on a fast computer. the > getdata function takes about 3 seconds. Surely there is a better way. this sounds like NumPy country, but some creative use of the ImageChops stuff might help a bit: from ImageChops import * r, g, b = im.split() pixels = im.size[0] * im.size[1] green = pixels - darker(subtract(b, r), subtract(g, r)).histogram()[0] purple = pixels - darker(subtract(r, g), subtract(b, g)).histogram()[0] From robin at jessikat.fsnet.co.uk Sun Mar 24 18:26:09 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 24 Mar 2002 23:26:09 +0000 Subject: ranking and searching [was: Re: "Zope-certified Python Engineers"] References: Message-ID: Certifiable has connotations with rather too many connections to the sort of mind state entered whilst trying to grock Zope internals. -Straightjacketed-ly yrs- Robin Becker From clpy at snakefarm.org Fri Mar 8 09:11:45 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Fri, 08 Mar 2002 15:11:45 +0100 Subject: print >> details??? References: Message-ID: <3C88C6A1.22DE64B3@snakefarm.org> spex66 wrote: > class x: > def write(self, s): > print 'START' > print s > print 'END' > > print >> x(), 'Hello' > > and got following result: > > START > Hello > END > START > > END > > where does the second call of x.write() come from??? It comes from the newline character that is automatically appended by the print statement. You can see it if you replace 'print s' by 'print repr(s)'. cg. -- 'In iteger arithetric divsion is no the oposite of multiplication.' -- scenes from comp.lang.python From logiplexsoftware at earthlink.net Fri Mar 15 20:43:33 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Fri, 15 Mar 2002 17:43:33 -0800 Subject: Help Required In-Reply-To: References: Message-ID: <20020315174333.6c80a199.logiplexsoftware@earthlink.net> On 15 Mar 2002 17:24:33 -0800 Surajsub wrote: > Hi, > I am a newbie to Python and am pretty fascinated by it power and > speed.I am however puzzled in trying to write this script. > The script builds a list of userids to be fed to ldap and it is > supposed to be > > uid1,uid2,uid3....and so on.( Notice there is no space) The script builds a string or a list? > However when i am trying to create the uid list it gives > > uid1, uid2, uid3,...and so on. > how do i get rid of this leading space if u would call it.. Don't know how you got it there, so I can't tell you how to remove it. > string.lstrip does not work either. You need to not put the spaces there in the first place. Far simpler than removing them after the fact. > what am i doing wrong? I can't see _anything_ you are doing, let alone what you are doing wrong ;) Try posting a least _a little_ code. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From loewis at informatik.hu-berlin.de Mon Mar 18 06:14:44 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 18 Mar 2002 12:14:44 +0100 Subject: bug reporting References: Message-ID: "Arthur Siegel" writes: > It could waste time of the developers to have to > weed through false alarm bug reports. One of the > roles of this list is to vet some of these issues. That is a reasonable approach. However, the question is how one should react if the newsgroup does not give any feedback. IMO, the next step should be to research the exact cause oneself. > The issue was related to overloading operators in a class subbed from the > 'complex' built-in - not exactly a high traffic lane, I suspect. > > Is the recommendation to submit it as a maybe bug? In general, yes. If you clearly understand the problem and its causes, and can demonstrate the problem in a small, self-contained example, submit a bug report. Bug reports should be structured as - what did I do - what happened - what did I expect to happen instead. Without seeing the details of subclassing complex: there was a sort-of explicit decision not to call subclass methods in the implementations of the builtin types, for efficiency. So for a dictionary, .get() won't call __getitem__(), instead, it will operate directly on the internal representation. If your problem is of the same type, you will need to implement all derived methods. If it is something else, report a bug. Processing of a bug may take many months; in some cases even years. Bug reports primarily help the Python developers, not the reporters. Of course, the community at-large is encouraged to review the bug reports, in addition to reading this list - perhaps they can help resolving some of them. Regards, Martin From shalehperry at attbi.com Wed Mar 6 12:08:57 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 06 Mar 2002 09:08:57 -0800 (PST) Subject: PEP 284, Integer for-loops In-Reply-To: Message-ID: I am a little confused. Your proposal starts with the claim that people are looking for a natural way to loop over a range of integers. Fair enough. However the definition of 'natural' seems vague here. As I read your proposal I kept looking for what modified 'var'. From watching the lists I have seen more people looking for C style for(;;) loops than anything. The syntax you propose is extremely confusing to anyone who has used a for loop in C. My other complaint is the lack of generality caused by not using the C syntax. You cover this at the end. Having one syntax for looping over 1..10, but another for looping over 2..10 evens only seems a bit odd. From emersonwood at yahoo.com Sat Mar 23 18:39:31 2002 From: emersonwood at yahoo.com (Emerson Wood) Date: 23 Mar 2002 15:39:31 -0800 Subject: forgetting state Message-ID: <98b6685d.0203231539.1459d00d@posting.google.com> Hi, how would I make a python interpreter shell forget everything that I've done and run a script or accepts commands as if it were first run? The reason I ask is that I'm running on Windows, and using the IDLE which keeps a Python shell up all the time. It would be natural to use that shell to test my program, but I'm finding problems running it twice. -Emerson From cbbrowne at acm.org Fri Mar 15 02:32:50 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 15 Mar 2002 02:32:50 -0500 Subject: XML-RPC Question References: Message-ID: In an attempt to throw the authorities off his trail, jolsen at mailme.dk (Jesper Olsen) transmitted: > "Thomas Weholt" wrote in message news:... > > I'm not sure about this, but I think SimpleXMLRPCServer only provide access > > to the methods of the object you "publish", in your example the methods of > > MyClass, nothing else. > > > > system.listMethods() comes from .... .NET ?? > > > > I migth be wrong, and if so, please let me know. > > > > No, not from .NET > > system.listMethods() is from the XML RPC introspection API > - se section 11.20.1 in the python reference doc > > It is nice to have when connecting to servers you have not written yourself. > > It should be very easy to support it in the SimpleXMLRPCServer, > but I guess it is not quite a standard, so they did not bother ... And it's not necessarily forcibly supportable. For instance, it's possible to register a bunch of Perl packages to dynamically accept requests. When that happens, the set of methods can get augmented (or perhaps even decremented) at runtime, and there's not really a good way of saying what the "list" of methods are. You might not want to list them all, for security reasons. (Not that this is forcibly protective of terribly much...) -- (concatenate 'string "cbbrowne" "@acm.org") http://www.ntlug.org/~cbbrowne/ Rules of the Evil Overlord #26. No matter how attractive certain members of the rebellion are, there is probably someone just as attractive who is not desperate to kill me. Therefore, I will think twice before ordering a prisoner sent to my bedchamber. From gerhard at bigfoot.de Wed Mar 20 00:41:07 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 20 Mar 2002 05:41:07 GMT Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: Fernando P?rez wrote in comp.lang.python: > Magnus Lie Hetland wrote: > >> >> - Magnus (who also is a bit baffled as to why distutils doesn't >> include?an?"uninstall"?command,?such?as?the?one?implemented?by >> Thomas?Heller.) > > Amen. It's incredibly annoying to have to tell users that a simple python > setup.py install does the trick as far as splattering files all over their > system, but that there's no reasonable way of undoing the process easily. You know about "python setup.py bdist_rpm" for RPM-based Linuxen and "python setup.py bdist_wininst" for Windows, right? A bdist_deb or bdist_bsd_pkg or whatever simply isn't publicly available, yet. But I'm pretty sure a patch implementing a new packaging method would make it into Python. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From bokr at oz.net Tue Mar 12 12:43:27 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Mar 2002 17:43:27 GMT Subject: Redirecting output in Windows NT References: <96e9dee5.0203120044.33a1e19c@posting.google.com> <3C8DC473.2070809@skippinet.com.au> Message-ID: On Tue, 12 Mar 2002 09:03:12 GMT, Mark Hammond wrote: >Paul Lydon wrote: >> Running Python 2.2 on Windows NT 4 Workstation. >> Suppose I have a Python program named 'splat.py' consisting of: >> "print 'splat'". >> >> If I type 'splat' and hit 'Enter', NT knows that it must run the >> Python interpretor and I see 'splat' on the screen. If I redirect the >> output to a file: >> 'splat > splat.txt', the resulting file is 0 bytes long and empty. >> The same thing would happen with Perl, if you have that installed and type 'splat.pl > splat.txt' (or 'splat > splat.txt' if .PL has priority over .PY in PATHEXT ;-) Anyway, it's a windows wart you can usually work around by invoking the interpreter (or other program) explicitly rather than through file extension association, e.g., python pyscript.py script_arg1 script_arg2 > captured_stdout If you run your script a lot, you may find it convenient to wrap it in a .cmd file. E.g., I collect a lot of little utilities in c:\util, and just added pargs.py and its wrapper pypargs.cmd as follows, simulating your situation (although apparently you've set .PY in PATHEXT or you'd have had to type 'splat.py > splat.txt' as I did below.): (dirf is a wrapped perl thing from long ago to munge dir output into something I like better). -- [ 9:34] C:\pywk>type \util\pargs.py import sys for i in xrange(len(sys.argv)): print 'argv[%d]: "%s"' % (i,sys.argv[i]) [ 9:34] C:\pywk>type \util\pypargs.cmd @d:\python22\python c:\util\pargs.py %* [ 9:35] C:\pywk>pargs.py 1 "two with spaces" 3 argv[0]: "C:\UTIL\pargs.py" argv[1]: "1" argv[2]: "two with spaces" argv[3]: "3" [ 9:35] C:\pywk>pargs.py 1 "two with spaces" 3 > junk.txt [ 9:35] C:\pywk>dirf junk.txt 02-03-12 09:35 0 C:\pywk\junk.txt [ 9:35] C:\pywk>pypargs 1 "two with spaces" 3 argv[0]: "c:\util\pargs.py" argv[1]: "1" argv[2]: "two with spaces" argv[3]: "3" [ 9:36] C:\pywk>pypargs 1 "two with spaces" 3 > junk.txt [ 9:36] C:\pywk>dirf junk.txt 02-03-12 09:36 85 C:\pywk\junk.txt [ 9:36] C:\pywk>type junk.txt argv[0]: "c:\util\pargs.py" argv[1]: "1" argv[2]: "two with spaces" argv[3]: "3" -- >> If I run the same program directly by typing 'python splat.py', again >> I see 'splat' on the screen and when the output is redirected 'python >> splat.py > splat.txt' I get a file containing the string 'splat' (as >> you would expect). >> >> Any ideas why the output redirection doesn't work in the first place? > >It is a bug in the NT command prompt. Works OK in Win2k. I believe >there is a FAQ on it too. > IIRC you can get the analogous problem in other ways than just interactively if you rely on file-association-driven program invocation. Regards, Bengt Richter From phd at phd.pp.ru Tue Mar 5 04:43:54 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 5 Mar 2002 12:43:54 +0300 Subject: =?koi8-r?Q?R=E9f=2E_:_Re:_R=3Ff=2E_:_Re:_strange_libtk8=2E3=2Eso:_open_f?= =?koi8-r?Q?ailed?= In-Reply-To: <"020305011813Z.WT09319. 17*/PN=Francois-regis.Chalaoux/O=RESEARCH/PRMD=SANOFI/ADMD=ATLAS/C=FR/"@MHS>; from Francois-regis.Chalaoux@sanofi-synthelabo.com on Mon, Mar 04, 2002 at 06:01:04PM +0100 References: <"020305011813Z.WT09319. <"020305011813Z.WT09319. 17*/PN=Francois-regis.Chalaoux/O=RESEARCH/PRMD=SANOFI/ADMD=ATLAS/C=FR/"@MHS> Message-ID: <20020305124354.H475@phd.pp.ru> On Mon, Mar 04, 2002 at 06:01:04PM +0100, Francois-regis Chalaoux wrote: > Why not add this latest path in LD_LIBRARY_PATH for the root deamon if it > is the problem ? The administrator tell me it is not a good idea to do > that !! > > What do you think ? I think: 1. Adding /usr/local/lib to LD_LIBRARY_PATH is a bit insecure, so your admin really must be careful. But if (s)he is careful - no problem. 2. If (s)he still does not want to add it, you can do it yourself. Instead of directly calling your python scripts from Apache, wrap then into shell scripts, that set LD_LIBRARY_PATH, and then exec your python script. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From max at alcyone.com Sun Mar 31 22:26:05 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 31 Mar 2002 19:26:05 -0800 Subject: PEP 285: Adding a bool type References: <3CA75F2F.198772EB@alcyone.com> <8NMp8.184567$2q2.15567243@bin4.nnrp.aus1.giganews.com> Message-ID: <3CA7D34D.F054FB95@alcyone.com> Terry Reedy wrote: > Yesterday, I gave four reasons for prefering 'truth' (or something > else) to bool. Please consider them. Already, my prediction in > point D is being borne out in some subsequent posts by some. > Something about the word 'bool(ean)' sets off something in some > people's brain that makes them want cripple a formalized Python truth > type by prohibiting currently valid and useful behavior. I find this > as offensive both to the spirit of Python and my programming freedom > as the suggestion that sequence*int should be deprecated and then > prohibited because it violates some standard of 'proper' sequence > behavior. Rather than have to put up with and have to argue against > such suggestions for the rest of my life, I would rather switch to a > different term that does not carry with it the baggage that 'bool' so > obviously does. But "truth" is the wrong word; you mean truth _value_. Calling the type name "truth" gives the impression that the only value it can have is True :-). This seems a semantic argument; I don't see any compelling reasons for calling it anything other than the common name. It doesn't make sense to follow other languages' lead _for its own sake_, but it sure does if that is by far and away the most common name for that type of thing. Such values are called "Booleans" (an instantly recognizeable name in computer science) far more often than they're called "truth functional values," or "truth values," or (more to the point) "truths." -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From idot at vt.edu Tue Mar 12 11:34:59 2002 From: idot at vt.edu (Carl Banks) Date: 12 Mar 2002 08:34:59 -0800 Subject: Is there a good reason why we cannot (as of 2.1.1) deepcopy complex objects? Message-ID: Strangely, I've found no mention of this anywhere: the docs, the Python FAQ, or the Google archives. Thanks, -- CARL BANKS From grante at visi.com Sun Mar 10 02:06:32 2002 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Mar 2002 07:06:32 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> <3C8B00E2.75783719@engcorp.com> Message-ID: In article <3C8B00E2.75783719 at engcorp.com>, Peter Hansen wrote: > Not sure how you would make your app look elsewhere than in > the executable's directory for DLLs, if you need to avoid the > system directories. I don't know that I "need" to, but it just seems to be good common sense not to put user files into system directories. I guess I'm not using "WindowsThink" yet. > Might be possible. Anyone? >> AFAICT, there doesn't appear to be a practical way to have >> multiple versions of DLLs installed, so if you've got two apps >> that require different versions of DLLs, then one of the apps >> is screwed. > > A good reason to use the everything-in-one-folder method and > not worry about it. That sure sounds like the best bet. >> Windows users... worried about drive space... ROTFL! > > Who's worried? Not me. I thought you might be, and I didn't > want to insult you by saying I thought that would be silly. Personally, I _don't_ think it's silly to worry about disk space. I've still got Linux systems I use every day running with a few hundred MB of disk space. It wasn't more than 3-4 years ago I was using a Linux system with under 100MB of disk space. But, AFAICT, Windows users have completely abandonded any hope of usable systems with less than several GB of disk space. I thought multi-GB disk drives were pretty pointless until I started playing with MP3 files. :) > If you don't care, then you have little reason not to go with > the options suggested. Distributing to Windows users via > a single executable is actually worse than via an installer > (which would hide the multiple files if it's not statically > linked) since (a) they get cute icons in the Start menu, > (b) they can uninstall without having to run Explorer and > manually delete files, (c) you can split out parts that > should be modular (resources such as help files, etc.), and > (d) they're used to it and don't know what to do with an > executable (depending on the ignorance level of the user). Good points. I'm pretty much convinced that a folder full of stuff and an installer are the way to go. -- Grant Edwards grante Yow! I'm not available at for comment... visi.com From niemeyer at conectiva.com Mon Mar 25 10:57:35 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Mon, 25 Mar 2002 12:57:35 -0300 Subject: embedded python ... In-Reply-To: References: Message-ID: <20020325125735.A2194@ibook.distro.conectiva> > --------------------------------------------------------- > Traceback (most recent call last): > File "./blue.py", line 2, in ? > import math > ImportError: /usr/lib/python2.1/lib-dynload/math.so: > undefined symbol: PyExc_OverflowError > --------------------------------------------------------- If you're linking libpython.a into the main executable, use the -rdynamic flag of gcc, or --export-dynamic flag of ld. If you're linking the library into a shared object, make sure you're using RTLD_GLOBAL in the dlopen() call. This should probably be inserted somewhere in the embedding documentation. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From bokr at oz.net Sun Mar 3 19:28:42 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Mar 2002 00:28:42 GMT Subject: RFC PEP candidate: q''quoted ? References: Message-ID: On Sun, 3 Mar 2002 14:56:45 +0300 (MSK), Roman Suzi wrote: >On 3 Mar 2002, Bengt Richter wrote: > >>Problem: How to put quotes around an arbitrary program text? > >Have it in a separate file. > That's fine in a lot of cases, but does require reliable presence of both files. It's not so convenient if you are trying to write e.g. a program generator and want to write out snippets containing mixed triple quoted doc strings and data etc. Or if you are writing copied example snips as part of dynamic HTML from CGI. You can say, "Well adopt a consistent methodology, so you don't try to quote triple quotes with quotes of the same kind." Ok. But IMO it's easier to think up a safe delimiter for yourself and use that to quote. Yes, Perlophobes can point to $s = <>Obviously a program may contain quoted material using all the >>defined string quoting methods (and this new method as well), >>so the problem is defining delimiters that won't occur in the text. >> >>I propose using a variation of the MIME multipart delimiter idea: >> >>Note the lack of quotes around the final delimiter string, since it itself is >>the final delimiter. This can also be used to solve the final unescaped ^^^^ >>backslash problem for quoting windows paths: >> >> q'|'c:\foo\bar\| > >Making Python as gibberish as Perl is. And all that only to >have Windows path be written without double-\ Not 'only'. I said 'also' ;-) Perhaps my choice of '|' delimiter triggered your 'gibberish as Perl' detector? I could have written q'###'c:\foo\bar\### or q'[quoting delimiter]'c:\foo\bar\[quoting delimiter] just as well for this one. >AFAIK, latest Windows also use / for delimiting dirs. >So this is non-problem. Sure, you have identified a context-dependent non-problem ;-) Regards, Bengt Richter From frederic.giacometti at arakne.com Mon Mar 4 21:53:21 2002 From: frederic.giacometti at arakne.com (Frederic Giacometti) Date: Tue, 05 Mar 2002 02:53:21 GMT Subject: microthreads and C calls Re: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> <7xzo1om5wt.fsf@ruckus.brouhaha.com> Message-ID: <3C8433CD.83B75D33@arakne.com> Paul Rubin wrote: > Christian Tismer writes: > > Makes pretty much sense to me. > > Stackless can provide light-weight threads to all platforms. > > There is no need to use OS threads unless you need it > > for I/O. > > Do you think it's feasible to modify Python to use non-blocking i/o > everywhere, and then simulate blocking in Stackless? I.e. when a > microthread does an i/o operation, Python would start the operation > asynchronously, and the Stackless microthread scheduler would block > the microthread til the i/o operation actually completes (detected > using select or SIGIO). Yes; that's pretty much what I described earlier. Without change, existing modules would keep working as they do presently, though. Existing C modules would have to be slightly edited to take advantage of the new capability, though. I could add the feature to the Python engine myself, but I need funding. Sponsors...? Frederic Giacometti From cliechti at gmx.net Thu Mar 14 13:45:55 2002 From: cliechti at gmx.net (Chris Liechti) Date: 14 Mar 2002 19:45:55 +0100 Subject: Telnet-like interface with authentication in server References: <8zYj8.63$5Kn.179044352@news.telia.no> Message-ID: "Thomas Weholt" wrote in news:8zYj8.63$5Kn.179044352 at news.telia.no: > ... Would it be possible to have a normal telnet-client connect to > my server somehow, get a prompt for username and password and be > able to run simple commands and see some output ? > This would be very handy for debugging etc. is it that what i call "Remote Access Python Interpreter" on my page? http://www.geocities.com/chrisliechti/ chris -- Chris From danny at ricin.com Mon Mar 18 19:58:43 2002 From: danny at ricin.com (Danny Pansters) Date: Tue, 19 Mar 2002 01:58:43 +0100 Subject: zipfiles module... read a file from archive Message-ID: <20020319005800.B60DD24D03@mail.ricin.net> Hello, I am not subscribed to this list because so far the documentation and/or the ease of Python has been so good I didn't need to ask anything, but I do have a problem now. So please send or CC to me! I would like to know if reading from a zipfile is only possible by reading its entrire contents in memory (the read() method of the ZipFile class) or is there a way to do this, say, line by line. I'm anticipating doing file uploads to users' websites through a web form (that way I don't need to give them FTP (yaiks) or SSH/shell (WinSCP) access and they dont need to learn anything but a simple web interface). I want to avoid a load of client site javascript to easily do multiple file uploads (yes I will have a "more" button to add more upload widgets but if a user has a huge pile of files or wants to upload or overwrite a particular directory tree with some files here and there this method gets very time consuming) so I want to include the option to upload a (pk) zipped file and extract it at the server into the desired target. Anyone who can use winzip can then have her whole site uploaded in one take. So I was hoping for a method that makes me read files in the zip archive line by line or bit by bit for all I care and have them written accordingly to their targets much like one would do with ordinary file upload. The zipfile will probably already be on the server in the user's directory. I guess that would be easiest to follow the routine I use for normal file upload and then if its a zip file have it be extracted after uploading it. So, am I stuck with having every file in the zip archive in memory to be able to write them to disk (would yield some limits just for safety) or can I do it in chunks somehow? Best regards, Python ROCKS! ------------------------------- Danny Pansters danny at ricin.com http://www.ricin.com ------------------------------- From tdi01fhu at syd.kth.se Fri Mar 29 19:12:34 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Sat, 30 Mar 2002 01:12:34 +0100 Subject: Ang: Re: Random... Message-ID: >>> "Chris Gonnerman" 02/03/29 14:57 >>> ----- Original Message ----- From: "Wojtek Walczak" > ** Since micro$oft is stupid it doesn't mean > ** that you should be stupid too - do NOT toppost. Well, personally I don't see what all the fuss is about. I top-post mainly because of the mailsystem we have at my school (Novell). http://mordor.obitus.org/gfx/arguing.jpg /Fredrik From adam at gliwice.pl Wed Mar 20 12:39:35 2002 From: adam at gliwice.pl (Adam Przybyla) Date: 20 Mar 2002 17:39:35 GMT Subject: Python2.2 Installation References: Message-ID: Joel Bender wrote: > I downloaded and almost installed Python 2.2 from the Python-2.2.tgz > release on SF by doing the 'usual "gunzip; tar; configure; make" dance'. > I now have a Python-2.2 directory which seems to work by itself. > Now I'm trying to add the pyserial-1.12 extensions by using distutils > and getting the following error: > distutils.errors.DistutilsPlatformError: invalid Python > installation: unable to open /usr/local/lib/python2.2/config/Makefile > (No such file or directory) > So how do I complete the installation so that Python2.2 is at least in > /usr/bin? How do I replace the 1.5.2 installation that came > preinstalled (which is in /bin)? try: /path/to/your/new/python2 setup.py build /path/to/your/new/python2 setup.py install Regards Adam Przybyla From jkraska at san.rr.com Wed Mar 6 22:34:11 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 07 Mar 2002 03:34:11 GMT Subject: PEP 284, Integer for-loops References: Message-ID: <7bod8uo9oec7uuh2onfkrjtsal4v3ksjmr@4ax.com> >I would submit, no change to the language I have seen proposed in a PEP does >*anything* significant *for* novices - and only adds to general static. I would have to agree. The kitchen sink is being thrown at Python lately, and it's hitting with a clank and a bang. C// From junkster at rochester.rr.com Sun Mar 17 19:32:37 2002 From: junkster at rochester.rr.com (Benjamin Schollnick) Date: Sun, 17 Mar 2002 19:32:37 -0500 Subject: Eliminate Spam Now... >g< Python w/DNS/&POP3 In-Reply-To: <20020317144859.B18963@glacier.arctrix.com> Message-ID: on 3/17/02 5:48 PM, Neil Schemenauer at nas at python.ca wrote: > Look at the check() function. It does a RBL-like check using >socket.gethostbyname(). I missed something fundamental, but quite simple. Your not doing a getbyhostname ("www.yahoo.com").... You are doing a gethostbyname ("www.yahoo.com.outputs.orbz.org") which forces your DNS server to check the ORBZ DNS server.... I feel a little foolish for not realizing that... Thanks for the hint, and that has completely (!!) simplified the entire problem by several 1000%. - Benjamin From philh at comuno.freeserve.co.uk Sun Mar 10 08:51:46 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sun, 10 Mar 2002 13:51:46 +0000 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> Message-ID: On Sat, 09 Mar 2002 17:21:39 GMT, Gerson Kurz wrote: > >!0,1.!1,1.!2,1.!3,1.,.@?0.!4,?0.!0,?1.~4,?0.!1,?4.~2,?3.!5,?2.A5,10.-5 > >will print the first ten fibonacci numbers. I wonder what it does in Perl? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From kkto at csis.hku.hk Mon Mar 25 22:23:58 2002 From: kkto at csis.hku.hk (Isaac To) Date: 26 Mar 2002 11:23:58 +0800 Subject: Indentation problem References: Message-ID: <7isn6o9fld.fsf@enark.csis.hku.hk> >>>>> "Gilles" == Gilles Diribarne writes: Gilles> Hi, I like Python language and use it every day. But... I read Gilles> some articles from October, 1998 where there was a fight with Gilles> space and tabs and indent problems. Today, we can found code Gilles> with spaces and tabs in the code. Gilles> I've some problem with identing code. I'm allright with the Gilles> example. But, I think it's important to have an "end" building Gilles> block like "!:" Gilles> What do you think about that? Hm... sounds very reasonable. But I think it would be useless in the current state of Python: most code is already written like what you prefer not to have. When you have to merge code, you'll always find that some of them are in the old style and some in the new style. I'd rather suggest to have a Python-specific indentation command in Emacs that will "reindent a region in a way that fits the current indentation style and fit in the current context, but retain the original meaning". This really shouldn't be that difficult. Anyone will try his elisp skills? Regards, Isaac. From tejarex at yahoo.com Mon Mar 25 14:18:32 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Mon, 25 Mar 2002 19:18:32 GMT Subject: Question: recursion and scope References: Message-ID: wrote in message news:a7nrl8$snv$1 at slb6.atl.mindspring.net... > Hello, Pythonistas. > > I am attempting to teach myself some basic computer programming concepts > using Python. > > I'm currently extending the recursive binary tree program in Programming > Python to traverse the tree and count its depth. The program successfully > traverses the tree and counts the number of nodes. > > So far, though I haven't figured out how to calculate the "maximum depth" of > the tree without declaring "maxdepth" as a global variable. > > If maxdepth is declared as a local variable within the recursive method, it > gets re-set for each subtree. > > What am I missing? Perhaps you want something like the following (untested, adjust for your tree implementation): def maxdepth(tree): if leaf(tree): return 1 elif onlyleftchild(tree): return maxdepth(leftchild) + 1 elif onlyritechild(tree): return maxdepth(ritechild) + 1 else return max(maxdepth(leftchild), maxdepth(ritechild)) + 1 If you want to simultaneously count nodes, then you must return a tuple of (count,depth) and add a bit more calculation machinery. Terry J. Reedy From emile at fenx.com Mon Mar 25 18:33:33 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 25 Mar 2002 15:33:33 -0800 Subject: Looking for bids References: <7085ec43.0203251529.527ce980@posting.google.com> Message-ID: dc > We are looking for bids to create an online alumni directory similar > to classmates.com using zope/MySQL. We need quotes and timeframes. We > will accept bids up to 3/29/02. Thank you. *3*/29/02??? Are you trying to keep the original bedder honest? Emile van Sebille emile at fenx.com From James_Althoff at i2.com Mon Mar 4 16:02:49 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 13:02:49 -0800 Subject: Status of PEP's? Message-ID: [Jeff Hinrichs] > What you are asking everyone to agree with is: > 5 = [0,1,2,3,4] [Carel Fellinger] > No he isn't:) He explicitly says he doesn't think of > sequences at all. Exactly! Rest assured that PEP 276 does *NOT* in any way call for 5 to be an alternate spelling for the list [0,1,2,3,4]. It calls for class int to define an __iter__ method that returns an iterator object whereby that iterator object would produce (for the case of integer 5) the numbers 0,1,2,3,4 in turn. Just to reinforce the point of the minimalist approach of PEP 276: -- PEP 276 calls for *ZERO* (None, nill, nada) new syntax for Python. -- PEP 276 basically amounts to adding to the int class a method similar to the following: def __iter__(self): i = 0 while i < self: yield i i += 1 raise StopIteration That's it. [Jeff Hinrichs] > If you were to restate the above as: > f(5)=[0,1,2,3,4] > Then, I believe, that you wouldn't have any problem convincing a large > majority that it is possible for f() to produce such an output. That being [Carel Fellinger] > And this is precisly what he's proposing, f is called iter in his > case. He comes from the camp that sees everything as an object, so > numbers are objects to. Hence integers know to do things, like > adding, subtracting, and ... counting! Three knows how to count from > zero upto but not including three. If you accept this, then the > discussion is not whether integers are sequences, but whether it's > natural to stretch Python's `for' construct to mean `count' or `over > its preceding numbers' in case of an integer. Like the `for' > construct recently got stretched to mean `over all lines' and `over > its keys' for text-files and dictionaries. Admitted in those cases it > still was a clear `iterate over', but the what was debatable. Right. The builtin function iter would work on integers. For example, iter(5) would return an iterator object that would iterate over 0,1,2,3,4. Jim From phd at phd.pp.ru Sat Mar 9 17:50:34 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sun, 10 Mar 2002 01:50:34 +0300 Subject: range Failure? In-Reply-To: <3C8A8564.E2F005AA@sympatico.ca>; from cjw@sympatico.ca on Sat, Mar 09, 2002 at 04:57:56PM -0500 References: <3C8A8564.E2F005AA@sympatico.ca> Message-ID: <20020310015034.A32508@phd.pp.ru> On Sat, Mar 09, 2002 at 04:57:56PM -0500, Colin J. Williams wrote: > It would seem that the first execution below should deliver the same > result as the second. No, it is not :) > >>> range(5, 2) > [] > >>> range(0, 5, 2) > [0, 2, 4] > > The help has: > range([start,] stop[, step]) range(5, 2): start = 5, stop = 2, step = 1, result => [] Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From eppstein at ics.uci.edu Thu Mar 7 12:36:10 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 07 Mar 2002 09:36:10 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , philh at comuno.freeserve.co.uk (phil hunt) wrote: > How about: > > for i = 1 to 10: > > or > > for i is 1 to 10: > > I think these are both equally good and both much preferable over > the horrible > > for 1 <= i <= 10: > > which I can only assume is someone's sick idea of a joke. Your "1 to 10" syntax (and most other ideas floated previously on this group) assumes a fixed type of interval (closed, I'm guessing, but it's not clear), and not even the most common type (half-open). The proposed syntax makes explicit what would happen at the ends of the intervals. One alternative proposal, that didn't seem to have as much support but might still be worth looking at, was to allow the creation of ranges by "1 <= ... <= 10" (possible without much modification of the compiler via a clever enough definition of "...") so then one could do "for i in 1 <= ... <= 10". I would appreciate it if you could give me a more constructive criticism of PEP 284 than "horrible", "someone's sick idea of a joke", which don't give me much idea why you don't like it. From gerhard at bigfoot.de Thu Mar 14 22:10:22 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 15 Mar 2002 03:10:22 GMT Subject: Python2.2 and expat References: Message-ID: Colin Fox wrote in comp.lang.python: > Hello, everyone. > > I'm trying to build garnome, which requires Python2.2 + Python2.2-xml. > I've got Python2.2 built, but for some reason it doesn't seem to build > expat. And when I try to "import xml.parsers.expat" I get: > >>>> import xml.parsers.expat > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.2/xml/parsers/expat.py", line 4, in ? > from pyexpat import * > ImportError: No module named pyexpat > > Where is pyexpat supposed to come from? It's part of the standard Python 2.2 sources and it is built ok if you've installed expat *and* the expat development files. Chances are that Python didn't find the expat headers during build. If you're using Linux, there's often a seperate package expat-devel or some such. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From claxtonr at beer.com Thu Mar 21 00:08:38 2002 From: claxtonr at beer.com (hejduk) Date: 20 Mar 2002 21:08:38 -0800 Subject: sys.path append problem Message-ID: I've recently installed python 2.2.1 on my slak 8.0 linux computer. I want to do some gui programming with wxPython, but in order to do that I have to change the module search path (sys.path) to include the wxPython module. I've tried the following: import sys sys.append('/some/new/dir') This works, but when i shut Python down and restart it the Path has been reset to the default, meaning that it is impossible to run scripts that attempt to import modules from outside of this default path. When I used python on windoze the sys.path saved when I appended to it, so I'm assuming that this is what is suppossed to happen. I realize that there are several work arounds to this problem, but I would prefer to correct it rather than cheat around it, because it could be just a symptom of a larger problem. Anyone know what the problem is? From skip at pobox.com Thu Mar 28 17:15:20 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 28 Mar 2002 16:15:20 -0600 Subject: findsyms.py - new script to help you document Python... Message-ID: <15523.38392.350596.205450@beluga.mojam.com> Got a few minutes to kill during commercials while watching the West Wing or Survivor? I just checked findsyms.py into the src/Tools/scripts/ directory of the Python CVS tree. This script rummages around in the LaTeX source looking for symbols that are exported by documented modules, but not themselves documented. It generates output like ... Not mentioned in smtplib docs: quoteaddr quotedata Not mentioned in SocketServer docs: ForkingTCPServer ForkingUDPServer ThreadingTCPServer ThreadingUDPServer ThreadingUnixDatagramServer ThreadingUnixStreamServer ... It's crude, and certainly not foolproof, but I think should help identify objects within modules that still need to be documented. Since it's new, you'll have to get it from CVS for the time being. If you have the libref sources already, you can snag a copy here (warning: monster sf.net url ahead that may well break): http://cvs.sf.net/cgi-bin/viewcvs.cgi/*checkout*/python/python/dist/src/Tools/scripts/findsyms.py?rev=1.1&content-type=text/plain Feedback is welcome. It has only been tried on Linux. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From sumner-nntp5 at forceovermass.com Sun Mar 24 15:53:01 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Sun, 24 Mar 2002 20:53:01 GMT Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> Message-ID: In article <3c9e2692$0$24819$e4fe514c at dreader3.news.xs4all.nl>, Boudewijn Rempt wrote: > Running each agent in its own process makes the system very > costly in terms of resources, makes it necessary for the agents > to implement inter-process messaging. Not to mention them > showing up individually in _top_... Other than IPC, those are definitely not inherent differences between threads and processes. On many systems, processes aren't "very costly" relative to threads, and on systems that implement threads in the "Plan 9 way" (rfork/sproc/clone on Plan 9/Irix/Linux) rather than the (IME, broken) Solaris/Win32 way then the threads are likely to show up under top anyway, though of course this depends on the version of top you're using (and you can always use process groups and a top utility which aggregates processes within those groups). It's okay to worry about performance between threads and processes as long as you realize that this is an implementation detail rather than an architectural decision--i.e. measure and make sure it's actually a performance problem before deciding it is. The primary factor in making an architectural choice between threads and processes should be whether or not you want to share all memory (and I find it useful to look at it from both sides--also consider "do I explicitly _not_ want to have protected memory here?") > That's the received opinion indeed. It still leads to problems. > I mean -- it's why you can kill a process, but not a thread. But in > an agent system, every agent (presumably running a thread, although > I've implemented systems where agents share threads, cooperative > multi-tasking agents) is on its own, and shouldn't own objects > or locks. The basic case sounds like a perfect candidate for muliple processes to me. Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From mlh at vier.idi.ntnu.no Sun Mar 31 18:53:24 2002 From: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) Date: Sun, 31 Mar 2002 23:53:24 +0000 (UTC) Subject: Streaming XML-RPC? References: <3C9F51EE.5000203@jerf.org> <3C9FAF96.5DE9A0@bgb-consulting.com> Message-ID: In article , Jim Dennis wrote: >In article , Magnus Lie Hetland wrote: >>In article , Skip > >>Montanaro wrote: > >>> Don> Are there any decent (finished/tested) Jabber libraries for Python? > >>>Don't know what its status is, but there is jabberpy: > >>> http://jabberpy.sourceforge.net/ > >> It's LGPL, which may make it unsuitable for some projects (like the >> standard Python library). But it seems to support the basic protocol. > > Why would LGPL be allergic to the Python License? I don't think it is, but AFAIK you couldn't include GPL or LGPL software in the Python standard library, for instance. (But then again, if that were an issue, the authors would probably donate the code to the PSF anyway...) -- Magnus Lie Hetland The Anygui Project http://hetland.org http://anygui.org From wurmy at earthlink.net Wed Mar 27 23:12:43 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Thu, 28 Mar 2002 04:12:43 GMT Subject: problems with circular references References: Message-ID: <3CA298C1.6F5791AE@earthlink.net> jimh wrote: > > I am working on python code that consist of quite a few files (about 50; > each file contains one class). All errors returned by functions are numeric > and are defined in the individual files. There is a MessageCatalog.py class > which will map these numbers into strings. This MessageCatalog.py has to > import all of the 50 other files to have access to their error numbers. So > far, so good - no problems yet. > > Here is the problem: Most of these 50 classes need to use the MessageCatalog > themselves. This means, of course, that classA imports MessageCatalog which > imports classA. This doesn't work very well. > > Does anyone have ideas on how to deal with this situation? Like some others already pointed out, exceptions are probably a better and more Pythonic way to handle this. But maybe, for some reason, you cannot use them. I cannot see your code, so I can't tell. How about putting all error codes in one file? E.g. errors.py: FOO_ERROR = 1000 BAR_ERROR = 1001 BAZ_ERROR = 1002 ...etc... Now all your 50 files can import errors.py and use the error codes, rather than having to define them themselves. All your MessageCatalog class needs to do is import that errors.py file as well. Since it seems to be used for mapping, have you considered using a dictionary? E.g. error_mappings = { FOO_ERROR: "Foo not implemented", BAR_ERROR: "Ixnay on the bar", ...etc... } Again, I can't see your code, so maybe I'm oversimplifying. Still, knowing your description only, this is how I would set it up. HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ From bokr at oz.net Fri Mar 1 21:26:34 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Mar 2002 02:26:34 GMT Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: On 01 Mar 2002 11:04:06 +0100, Martin von Loewis wrote: >bokr at oz.net (Bengt Richter) writes: [...] > >> Perhaps we could just use a file to contain extra file metadata, >> letting a file of metadata govern other files it names in the same >> directory as itself. Probably a dot file in *nix. > >Nice idea, different PEP. > >> For PEP 263 purposes, it would only need to be a text file with file >> names tab delimited from keyword=encoding-info, with the first line(s) >> perhaps with a glob pattern for a compact way of specifying encoding >> for a lot of files in a directory at once. > >I don't think the file encoding information should be stored in a >different file; the risk of the two files becoming disassociated is >just to big to be acceptable. > Well, there's risk of a sym link becoming dissociated from its file too, but if you are using the mechanism, it's quickly apparent when it breaks. I agree there is a dissociation danger, but when an error pops up, it will be easy to add the misbehaving file's name to the local meta-data directory file. Encoding detection tools also could do a one-time scan of a directory and validate the metadata, or at least warn. If desired you can hide the actual data file by renaming it to a hashed or other alias name, using the metadata entry to show the original name and its symlink-like location option to point to the renamed file. Thus you force the tools either not to find file_orig_name, or to look in the directory file, where it will find file_orig_name encoding=UTF-8 location=./hashedname or not find it at all, but meta-data would not silently be ignored. But the best way to keep metadata is with actual file system support, as Paul Prescod mentioned privately (and I was about to go into when I decided my post was getting too long ;-) What I want is a universal file typing metadata prefix with codes issued through a registry system that assigns numbers in a way that provides for both common de facto standards and private company proprietary file types. The prefix would be copied with any copy of the data file, but it would be excluded from the range of normal seek operations. If the prefix contained a location symlink, that would be all that was copied by default. Data-verifiable links could contain md5 hashes of the data they link to. The reason for the location link option is to be able to wrap legacy files and whole file systems without modifying them, yet being able to integrate them into the new file system. I like the idea of doing the prefix in UTF-8 so that a local system can wrap a foreign system with local file names in the "symlinks". Think of it as meta-data-enhanced UTF-8-encoded super-symlinks, with the principal purpose of carrying universal-file-type-code & encoding-id in the meta-data, and the option of an absent location-link meaning data follows immediately in the same container as the super-symlink. Note that not touching the linked file's data would allow you to enhance the meta-data to handle compounded encoding formats which would not allow embedding -*- "cookies" -*-, such zip, tgz, pgp, bin64, etc., etc. You could create a new file with the metadata as a prefix with data immediately following (probably on a block boundary), but this would be nicest with file system support. >> To provide international encoding for file-associated info, like >> a local dialect/special characters name etc., in a system whose >> native file naming is more restricted, perhaps this directory of >> file attributes could be standardized to UTF-8 for its own encoding. > >We are not talking about file names here, but about file contents. > Right, I was 'introducing an optional side benefit'[1] of the main idea. IOW, you could e.g. have optional meta-data containing a sanskrit string for whatever purpose, irrespective of the type or encoding declared for the file that the meta-data was associated with. If the meta-data file were standardly always UTF-8 encoded, there would be no restriction on *its* content, though the associated data file might be EBCDIC or whatever. Whether you wanted to support file annotations, or special-language display names or whatever would be a design decision above the super-symlink general infrastructure I am describing. [1] I guess that's a bad habit when trying to communicate a main idea ;-/ >> There are some changes as to legality checks, apparently, >> as of last May. I'm wondering if this affects PEP 263 >> and/or the unicode implementation in Python. > >That doesn't affect this PEP; as for the Unicode 3.1 conformance, I >believe the current CVS implements UTF-8 correctly. > I'll take your word for it ;-) BTW, if my display font is Lucida Console will I be able to see infinity like the 'A' in the following? >>> u'\u0041' u'A' >>> u'\u221e' u'\u221e' Will the following work? >>> print u'\u0041' A >>> print u'\u221e' Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) >>> And if I redirect the output to a file, what will be in the file? Regards, Bengt Richter From deathtospam43423 at altavista.com Sat Mar 9 07:54:04 2002 From: deathtospam43423 at altavista.com (A.Newby) Date: 9 Mar 2002 12:54:04 GMT Subject: Q: How can I lock a file in Windows? References: Message-ID: Graham Ashton wrote in news:XBli8.5326$OP.143152 at stones: > On Sat, 09 Mar 2002 10:06:08 +0000, A.Newby wrote: > >> Is there another way I can lock the file in Windows? > > Yes. Try this: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 > Thanx! That should work, except I don't seem to have the following extension modules ... win32con, win32file, and pywintypes. Any idea where I can get them? -- cdewin at dingoblue.net.au From aahz at pythoncraft.com Mon Mar 25 19:28:43 2002 From: aahz at pythoncraft.com (Aahz) Date: 25 Mar 2002 19:28:43 -0500 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> <3C9FBDB0.7E0BCA16@engcorp.com> Message-ID: In article <3C9FBDB0.7E0BCA16 at engcorp.com>, Peter Hansen wrote: > >Now that someone has pointed us there repeatedly, but without >much explanation, I figured it had to be me, not the site. Now >I notice the "ht2html at SourceForge" link in the upper right (hidden >in plain sight -- the old purloined letter trick!), which leads >you to the real repository. And from there you have to click on >the little "CVS" link, and if you want to browse via the web >you then have to click on "Browse CVS repository". *Then* you >can see the danged .py files everyone is probably looking for. >Maybe there's a more direct route, but I didn't see it. > >Maybe it's just the ones who already knew how to do this, who >knew how to do this.... ;-) Hmmmm... I guess you're right. I'll cc Barry on this to clean up the page a little. (I guess maybe I searched a little harder than others because I'm used to pages looking a bit odd in Lynx. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From amckay at merlinsoftech.com Tue Mar 26 18:00:34 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Tue, 26 Mar 2002 15:00:34 -0800 Subject: xml config file to python object In-Reply-To: References: Message-ID: <200203262258.g2QMwoq13774@mail.merlinsoftech.com> > Is there a way to pickle (serialize) any python object > to xml and back? http://www.google.com/search?hl=en&q=xml_pickle -- Andy McKay From nico at aries.logilab.fr Fri Mar 22 12:44:20 2002 From: nico at aries.logilab.fr (Nicolas Chauvat) Date: Fri, 22 Mar 2002 17:44:20 +0000 (UTC) Subject: New SIG on logic/CLP programming in Python Message-ID: Hello Pythonistas, I'd like to entertain you with a new subject: logic programming and constraint-propagation features in Python. I teach Python and advocate it often. One argument I use is that you have several "programming paradigms" available in Python. You need simple things and scripts? Use procedural programming, with variables and functions. You need more structure? Use object-oriented programming. You miss Lisp and need to process lists? use (some) functionnal programming. You need concurrency? Look at Python 2.2's future and stackless. It's all there. Mix'n match as you wish, you're not tied to a specific approach, just use what fits best your model and data. No need to mix languages. Now, what if you need logical programming? Use pyprolog. And copy your data back-and-forth from prolog-space to python space. Or look at Mozart/Oz. Yeah, it's all there too: procedure, functions, objects, concurrency, logic, constraint-propagation, even distribution and security. Right, but the syntax is... difficult. I'm sorry to have to tell Mozart folks lurking here, that I'm a big fan of "indent-what-you-mean" and will have trouble telling our new programmers that this complicated syntax is good for them. And that brackets have different meanings depending on where they are. And Python already has a user-base that's increasing at rocket-speed. When teaching Python I often tell people "if you need to code something in Python, go to google first, you'll probably find it there and move to more important matters". As you already understood, I am thinking about implenting some logical/constraint-propagation features on Python. My (rough) understanding is that is would be doable on top of microthreads/stackless/generators. I am looking for interested people to form a Logic-SIG or CLP-SIG. You think this is a great idea? You think this is stupid? Please speak up! If you have no idea what I am talking about, don't worry, I'll try to post an example here this week-end. Waiting for your comments. -- Nicolas Chauvat http://www.logilab.com - "Mais o? est donc Ornicar ?" - LOGILAB, Paris (France) From krissepu at vip.fi Sun Mar 10 16:37:43 2002 From: krissepu at vip.fi (Pekka Niiranen) Date: Sun, 10 Mar 2002 23:37:43 +0200 Subject: Syntax to catch specific exceptions ? Message-ID: <3C8BD227.7D1D5539@vip.fi> I am trying to find correct python syntax and structure for the following exceptions ------------------------ mypath = os.path.join(os.getcwd(), 'mydirectory', 'mysettings.pxp') try: f = open(mypath, "r") except "mydirectory does not exists": try: create_mydirectory_for_the_next_read() save_default_values(mypath) except "no permission to create mydirectory": do_whatever() except "no permission to enter mydirectory": print "whatever1" use_defaults() except "file mysettings.pxp does not exist": print "whatever2" use_defaults() except "no permission to open mysettings.pxp": print "whatever3" use_defaults() ------------------------- I can get the error text and number as follows, but how to catch only "File exists" OSError ? try: ... os.mkdir('e:\\tmp') except OSError, (errno, strerror): ... print strerror ... File exists -pekka- From xhalasa at fi.muni.cz Tue Mar 19 04:12:14 2002 From: xhalasa at fi.muni.cz (Jan Halasa) Date: Tue, 19 Mar 2002 09:12:14 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> Message-ID: Ahmed Moustafa wrote: > 1. Where can I find an unbiased comparison between Java and Python? > 2. Will Python dominate? > 3. Who does support Python? This topics were discussed here about one month ago, try to search the archive at groups.google.com. Jan Halasa From dpeter at designtheory.org Fri Mar 15 06:17:39 2002 From: dpeter at designtheory.org (Peter Dobcsanyi) Date: 15 Mar 2002 11:17:39 GMT Subject: Why I think range is a wart. References: <7UYj8.31929$l93.6269941@newsb.telia.net> Message-ID: Tim Legant wrote: > No. Your bar() function is broken and the test results invalid. Try > this instead: > > def bar(ls): > i = 0 > for x in ls: > if x == '998': > return i > i += 1 Oops, you are right! I fixed it and ran the test again. 3000 times, Python 2.2, Linux: i in range(len(ls)): 2.03 x in ls; i+= : 2.28 lambda x:zip(range(len(x)), x): 3.76 Iter class: 10.18 10000 times: i in range(len(ls)): 6.68 x in ls; i+=1 : 7.55 lambda x:zip(range(len(x)), x): 12.56 Iter class: 35.56 Interestingly, "range(len(ls))" is still faster. Peter From cliechti at gmx.net Fri Mar 22 17:13:33 2002 From: cliechti at gmx.net (Chris Liechti) Date: 22 Mar 2002 23:13:33 +0100 Subject: Copmlex structures.... References: Message-ID: "Dmitry S. Makovey" wrote in news:iUMm8.141$%52.3298 at jekyl.ab.tac.net: > Hi. The problem itself is - I want to use complex structures like > described below, but i want it another way.... > > 01. >>> f={} > 02. >>> f['name']='dimon' > 03. >>> f['age']=20 > 04. >>> a=[] > 05. >>> a.append(f) > 06. >>> print a > 07. [{'age': 20, 'name': 'dimon'}] > 08. >>> f['age']=22 > 09. >>> print a > 10. [{'age': 22, 'name': 'dimon'}] > > I don't like result in the last like I've expected to have [{'age': > 20, 'name': 'dimon'}], how could i do this? it's what i would expect :-) the list stores a reference to the one and only dictionary object and you can get there through the list or through the old name. > I know that it must be as simple as using something like b[:], but > what? that would only give you a copy of the list with copies of all references (flat-copy). what you need is a deep-copy that dives and copies recursively. look at the "copy" module for such functionality and/or serach groups.google.com for "deep copy" chris -- Chris From peter at engcorp.com Wed Mar 20 02:14:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Mar 2002 02:14:39 -0500 Subject: bug tracking system References: Message-ID: <3C9836DF.1E877634@engcorp.com> mohamed lazreg wrote: > > Dear pythoners, > > Are you aware of any free bug tracking system written > in python? Several based on Zope... (http://www.zope.org) From cfelling at iae.nl Sat Mar 2 21:07:51 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 3 Mar 2002 03:07:51 +0100 Subject: PEP 234 little bug? References: <3c817238@nntp.server.uni-frankfurt.de> Message-ID: Michael 'Mickey' Lauer wrote: > Just read through some of the already implemented PEPs. > PEP 234 (iterators) states: >> Resolution: this has been implemented. > I can't see a next() in a file object. Shouldn't it be > "Resolution: this has not been implemented." ? No, but you can find a `__iter__' method, and in places where an iterator is expected that function is called, and low and behold the resulting object of that __iter__ call does have a next method. So all is well after all:) -- groetjes, carel From mwh at python.net Wed Mar 6 09:17:03 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 6 Mar 2002 14:17:03 GMT Subject: Flushing stdout with raw_input - BUG References: Message-ID: Jonathan Gardner writes: > raw_input and several modules that are part of the standard library that > handle input and output with stdout and stdin (cmd.py) do NOT - I repeat - > do NOT flush stdout before waiting for input. > > No, I don't want to flush buffer stdout everytime I write to it. That is > wasteful and inefficient. I want to flush the buffer when I am done writing > to it, or when I make a call to raw_input(). (This has been brought up > before a long time ago - why is it not fixed? Why does Guido want it to > behave like this?) > > If it is running with a terminal, then the underlying code (in C or the > Kernel, I am not sure) will flush stdout before reading input. However, it > does not automatically flush stdout before reading stdin if stdout and > stdin are not terminals. > > That means if I write a program that forks off another process that runs a > python script that uses stdin and stdout, (using something like Popen3), > then the conversation goes something like this: [snip melodrama] > Should I turn on -u for the child script? That is silly. Just write > raw_input properly, and make everyone happy. If you don't, I'll be > *forced* to hack on the cpython code, and then you'll *really* > regret it! =) Not necessarily -- you could use a pseudo terminal. That way the child will think it's talking to a terminal, and so things will be line buffered. > I am running Linux 2.4.14 and Python 2.1.2. I tested this bug in Python 2.2 > and it is still there. > > I posted a bug about cmd not flushing the buffer to sourceforge. I will > post another bug about raw_input not flushing the buffer. I will write > another bug report about the unresponsiveness to bug reports as well, as > there are a lot of bugs that aren't even addressed at sourceforge. Oh, that will help, sure. Please note that Python is a volunteer effort. You have no right to expect bug reports to be attended to. However, they are. I know *I* scan through open bugs fairly regularly. Martin von Loewis does the same. I can only fix the bugs I have time to fix, and so fix the bugs that seem to me to be worth fixing. I've spent multiple hours in just the past few days with my head stuck deep in the Python internals, and TBH posts like this do not make me think it was worth it. > PLEASE PLEASE PLEASE! Examine your code. If you do not use raw_input, then > flush your buffers! Otherwise, we will not be able to fork off your > script/module and use it as a child process without -u. If you are interacting with a subprocess that is expecting to talk to a user, you should probably be using pseudo-tty's. Cheers, M. -- Just put the user directories on a 486 with deadrat7.1 and turn the Octane into the afforementioned beer fridge and keep it in your office. The lusers won't notice the difference, except that you're more cheery during office hours. -- Pim van Riezen, asr From dsavitsk at e-coli.net Thu Mar 14 17:39:27 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 14 Mar 2002 22:39:27 GMT Subject: basic statistics in python References: Message-ID: this is really embarassing :-) >>> import win32com.client >>> xl = win32com.client.Dispatch('Excel.Application') >>> xl.WorksheetFunction.StDev(1,1,1,3,3,45,3,2,1,1,2,3,2,1) 11.565627361442019 >>> xl.WorksheetFunction.Pearson((1,4,3,2,5),(5,3,2,5,4)) -0.48507125007266594 -d "dsavitsk" wrote in message news:OvQj8.10177$k5.3810357 at newssvr28.news.prodigy.com... > hi all, > > never having done numeric calculations in python* i am seeking advice on how > to best go about doing some basic statistics. in particular, i need to find > standard deviations and point bi-serial correlations**, and i am seeking > advice on the best way to go about it. i know how to do them, but i am > wondering if there are prebuilt modules that might simplify the task. > > i found this > http://starship.python.net/crew/hinsen/ScientificPythonManual/ > but it seems to be unix only and i am on win32. as far as standard > deviations, i found this in an old ng post. > > def stddev( *x ): > if not x : return 0 > if ( len(x) == 1 ): x = x[0] > m = mean( x ) > var = 0 > for n in x: > n = n - m > var = var + (n * n) > return sqrt( var / float(len(x)-1) ) > > There seems to be some stuff in scipy, but i am having trouble geting > through the docs. also, do i want to look at numpy? > > any suggestions? > > thanks, > > doug > > > > * all text processing thus far. > ** i think that is the correct term, item total correlations in other > words. > *** in general though nobody is going to live or die by what the state say, > so a small amount of error is not too big a deal. > > From bergeston at yahoo.fr Thu Mar 21 06:24:35 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Thu, 21 Mar 2002 12:24:35 +0100 Subject: eval of a private attribute References: <3C998F89.66DB1290@infomaniak.ch> Message-ID: Those work both: --1. Instance variables------ class CObsFile: def __init__(self): self.__user="~briner/big/usr.rdb" self.__location="~genevay/system/location" def get(self,var): tobeEval ='self._CObsFile__'+var print 'toBeval: '+tobeEval p=eval(tobeEval) print 'Evaluated: '+p return p p=CObsFile() p.get('user') --2. Class variables------ class CObsFile: __user="~briner/big/usr.rdb" __location="~genevay/system/location" def get(self,var): tobeEval = 'CObsFile._CObsFile__' + var print 'toBeval: '+tobeEval p=eval(tobeEval) print 'Evaluated: '+p return p p=CObsFile() p.get('user') -------------------------- HTH B. "BRINER Cedric" wrote in message news:3C998F89.66DB1290 at infomaniak.ch... > hi, > I'd like to create a method which will be able to get > any attribute of the class. > > Unfortunately this example is not working: > > > class CObsFile: > __user="~briner/big/usr.rdb" > __location="~genevay/system/location" > def get(self,var): > tobeEval ='self.__'+var > print 'toBeval: '+tobeEval > p=eval(tobeEval) > print 'Evaluated: '+p > return p > > p=CObsFile() > p.get('user') > > any idea why From gerhard at bigfoot.de Wed Mar 13 08:11:03 2002 From: gerhard at bigfoot.de (=?ISO-8859-15?Q?Gerhard_H=E4ring?=) Date: Wed, 13 Mar 2002 14:11:03 +0100 Subject: module import in cgi scripts References: Message-ID: <3C8F4FE7.1090001@bigfoot.de> Dag wrote: > I'm trying to write a cgi script in python but I'm having a lot of > problems importing modules. > > I've simplified my script down to > #!/usr/bin/python2.2 > import pg > print "hello\n" This won't work as a CGI script. You'll have to send the HTTP headers, then an empty line, then the HTTP body. For the HTTP headers, you'll need at least the content type, so use something like this: print "Content-type: text/plain" # for plain text, or text/html for HTML print print "hello" > if I run it from the command line it prints "hello" as expected, > but if I put it in my cgi-bin directory and access it from a web > browser the web server returns Internal Server Error and the > error log says: > Traceback (most recent call last): > File "/var/www/cgi-bin/summarypie.py", line 4, in ? > import pg > ImportError: No module named pg > > I have checked and double checked and the pg modules is in the > python sys.path. What's wrong? Most probably the CGI script is run as user nobody, group nogroup and the pg module or its parent directory don't have the correct permissions. Doing a "chmod -R +rX" on your Python library directory should fix this. To test this kind of problem, you can also su to root, then su to nobody to have the same environment a CGI script run under Apache. Btw. you should also consider using pgdb instead of pg (assuming pg is part of PyGreSQL). pgdb is the DB-API 2.0 compliant wrapper on top of pg. If you use pgdb, you can easily switch from PyGreSQL to a different Python-PostgreSQL database interface later. Or to an altogether different database. The pg module, however, uses a proprietary interface. If you use PyGreSQL, also be sure to use the latest version, as this contains fixes for some very annoying bugs. The most current can be found inside the PostgreSQL 7.2 source tarball. Gerhard From martin at v.loewis.de Sat Mar 16 14:54:07 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Mar 2002 20:54:07 +0100 Subject: HP-UX, PyThread_* missing References: Message-ID: "Paul F. Dubois" writes: > I am trying to get Python 2.2 to compile on HP-UX B.10.20. I get a set of > missing externals with names PyThread_something. I need threads so I don't > want to turn them off. Is there a package I need to install first? Or some > other hint about what to do? If you need threads on HP-UX 10, you may need to write your own thread package first :-( Provide more info: what compiler (bundled - nah, can't be, unbundled, gcc?); what symbols are missing, etc. In any case, the common understanding is that Python does not really support threads on HP-UX, and probably never will unless some HP-UX user who understands all the issues provides patches. Regards, Martin From johnroth at ameritech.net Fri Mar 8 07:29:22 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 8 Mar 2002 07:29:22 -0500 Subject: why is python slow? References: Message-ID: "les ander" wrote in message news:a2972632.0203071841.7cd09181 at posting.google.com... > Hi, > i am just curious as to why different programming languages have different > speed. I understand that if a language has an extensive grammar > (such as c++) the compiler would take longer. Modern parsing technology just about eliminates any effect of the grammer on compile speed, unless the parser needs to do huge amounts of backtracking. What affects compile speed is externals such as how many header (or whatever name you call it) files need to be accessed for a compile, and how much optimization you do. > But what about execution? > why is a perl program faster than similar python program? There's no good evidence that Perl is substantially faster than Python. It varies by application. > For example > when java came out it use to be pretty slow, but now it is pretty fast. How > was this speed-up acheived and why is it not possible to have such a speed up > for python? Part of the speedup was relentless optimization by the various Java licencees, and part was "just in time" compilation. So far, nobody has worked on a JIT engine for Python. There's a vast difference in the amount of effort expended on Java as opposed to Python. John Roth > > thanks > les > > P.S. I am just trying to understand and do not intend to put down python by > any means. From terabaap at yumpee.org Fri Mar 1 14:38:42 2002 From: terabaap at yumpee.org (Manoj Plakal) Date: Fri, 01 Mar 2002 13:38:42 -0600 Subject: RSS writer module? Message-ID: <3C7FD8C2.9040702@yumpee.org> Does anyone know of a Python module to write RSS files? The format is not that hard to generate manually but perhaps someone's already done it? Manoj From shalehperry at attbi.com Wed Mar 6 12:30:19 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 06 Mar 2002 09:30:19 -0800 (PST) Subject: PEP 284, Integer for-loops In-Reply-To: <6874703.1015406166@[192.168.1.100]> Message-ID: On 06-Mar-2002 David Eppstein wrote: > On 3/6/02 9:08 AM -0800, Sean 'Shaleh' Perry wrote: >> From watching the lists I have seen more people looking for C >> style for(;;) loops than anything. The syntax you propose is extremely >> confusing to anyone who has used a for loop in C. My other complaint is >> the lack of generality caused by not using the C syntax. > > Thanks for the comments, but it seems clear (and I think it's a good thing) > that C-style for's are not going to happen in Python. They're very > general, but not very intuitive, especially to non-C-programmers. > The intention was not 'we should have C style for loops'. Rather, I was trying to point out the limited gain from adding the propsed syntax. I personally find it annoying to have special case syntax. Loop over the first M numbers in a sequence: for n <= var < n+m: print var Loop over the even numbers between N and M: for var in xrange(n, m, 2): print var A new programmer frequently tries something simple like the first item, then moves onto the second. I believe they would be equally confused by the need for a completely different syntax. From holger at trillke.net Sun Mar 24 10:59:56 2002 From: holger at trillke.net (holger at trillke.net) Date: Sun, 24 Mar 2002 16:59:56 +0100 Subject: Stopping threads from the outside In-Reply-To: ; from aahz@pythoncraft.com on Sun, Mar 24, 2002 at 10:03:27AM -0500 References: Message-ID: <20020324165956.E12768@prim.han.de> > >how could you stop a running threading.Thread from the *outside*? of > >course i could introduce some kind of flag into the event loop of the > >Thread.run-method, but i really would prefer to have a non-instrusive > >way for several reasons. > > > >Any way to do this? > > Not really. Why do you want to do it? You really want to know it? I am currently working on (coded) agents which move through the network. Some Agents want to actively run in a thread (my http-serving agent for instance). And i would rather not impose any restrictions on their event loops. But of course i'd sometimes like to shut down some or all agent-threads. Any ideas? Maybe something with signals (one of the areas i have no experience with)? Is the questions actually strange in any way? Like something you wouldn't usually like to do? holger From devnull at terra.com.br Sat Mar 23 20:21:48 2002 From: devnull at terra.com.br (Devnull) Date: Sat, 23 Mar 2002 22:21:48 -0300 Subject: Where can I find these imports? (with the imports' imports included :P) Message-ID: <001801c1d2d2$456fe250$02c8a8c0@christo.com> seriously I need to compile a program I found that needs these files: import Tkinter import tkFileDialog import Pmw import level import guimaker import formgui import shelve import os import os.path import guimixin from guimixin import * I got already Pmw, but I can't find guimaker, formgui, level and guimixin anywhere, I wonder if anyone has them, can they please send me these files? or tell me where I can get them (with their respective imports) thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From cliechti at gmx.net Mon Mar 25 16:48:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Mar 2002 22:48:01 +0100 Subject: Doing a ps in windows.. (Is application XYZZY running?) References: Message-ID: Andrew Markebo wrote in news:m38z8g74hw.fsf at localhost.localdomain: > *blush* yeah I know.. not really.. here, only almost :-) > > I have the windows-compiled python 2.2, and I would like to see if > Opera or Netscape is running on my computer (poor sod, running Win2k, > XP or 98).. How do I do this, I suppose I could use something in the > win32api, but what is something.. :-) ?? there is an example on EnumWindows in the win32all package. it gives you integer window handles which you can then use to retreive the GetWindowText. chris -- Chris From jon+usenet at unequivocal.co.uk Tue Mar 5 20:27:39 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Wed, 06 Mar 2002 01:27:39 -0000 Subject: New Python CGI/FastCGI/web-templating system Message-ID: Just a quick note to say that I have put an alpha release of my Python CGI/FastCGI/web-templating system up at http://sourceforge.net/projects/jonpy (with documentation and examples at http://jonpy.sourceforge.net/ if you don't want to bother downloading it), so if anyone is interested in this sort of thing and willing to try out alpha software, please take a look (and let me know what you think!). (And yes, I know there are a zillion and one similar systems already, but mine is, of course, better And actually I think the templating system is genuinely innovative in the way it corresponds document structure with nested classes.) From andy.mckay at merlinsoftech.com Wed Mar 6 14:28:57 2002 From: andy.mckay at merlinsoftech.com (Andy McKay) Date: Wed, 6 Mar 2002 11:28:57 -0800 Subject: Web scripting with Python (1st post here, also :-) In-Reply-To: <40c3f5da.0203061114.18f7fea6@posting.google.com> References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: <200203061928.g26JSoq09361@mail.merlinsoftech.com> On March 6, 2002 11:14 am, Julio Nobrega wrote: > Well, enough is enough, isn't? Where do I start? It's for a weblog > (Kuro5hin-like) system. Its all been done before so it depends how much work and reinventing you want to do. Squishdot will get you up and running in the time it takes you to read all these emails. -- Andy McKay From psage at ncaustin.com Thu Mar 21 16:53:52 2002 From: psage at ncaustin.com (Paul Sage) Date: Thu, 21 Mar 2002 15:53:52 -0600 Subject: TKinter Question Message-ID: <03F53405C6ED434A986221919785A6A7106BE1@nca-postal.ncaustin.com> Hi all. I am new to the list; the impetus for my signing up is a roadblock. :-) I am currently working with a quick and dirty little App for learning Python. I am using Tkinter because the app really needs a GUI. Global variables within the module: pointsAvailable = 5 currentPointsToSpend = "Current Points left to spend: %s"%pointsAvailable Inside the class definition of an object that is the GUI window: self.pointsLeftToSpend = Label(root, relief = RIDGE, borderwidth = 1, anchor = N, justify=CENTER, textvariable = currentPointsToSpend).pack() My problem is with textvariable. No matter what I seem to do, it just won't show up. Is this because it falls out of scope somehow? It doesn't happen with all of the other Tkinter variables. It just won't show up. So I am in desperate need of some help. I don't want to spend all day with this. :-( Sorry, I don't have anything positive to provide with my first post. Just problems. - As for me? Make mine Marvel! -------------- next part -------------- An HTML attachment was scrubbed... URL: From -$P-W$- at verence.demon.co.uk Wed Mar 27 10:59:14 2002 From: -$P-W$- at verence.demon.co.uk (Paul Wright) Date: 27 Mar 2002 15:59:14 -0000 Subject: visual python References: <20020327104352.12035.00000368@mb-mk.aol.com> Message-ID: In article <20020327104352.12035.00000368 at mb-mk.aol.com>, Marxdormoy wrote: >downlaod visual python ? website? Search engine? Google? -- Paul Wright | http://pobox.com/~pw201 | From peter at engcorp.com Sun Mar 24 17:31:52 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 17:31:52 -0500 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> Message-ID: <3C9E53D8.4FA20F3D@engcorp.com> holger at trillke.net wrote: > > > "The network"? Which one? The Internet, or an internal > > network over which you have full control? Who controls > > the servers on which these agents will be running? > > well. at the moment the servers are under my control. > but this is hopefully going to change. So is your purpose in shutting down threads that you want to prevent agents written by others from running forever? Or can you count on the good behaviour of those writing agents to run on these servers? > In fact it is quite hard to group the agent-threads because they are very > autonomous (and btw quite cooperative with other agents). "Cooperative"? As in, working together on problems? Or working on their own individual problems without any interference or perhaps interaction? -Peter From rnd at onego.ru Sat Mar 9 11:42:48 2002 From: rnd at onego.ru (Roman Suzi) Date: Sat, 9 Mar 2002 19:42:48 +0300 (MSK) Subject: Aplython Message-ID: Can't wait for April 1 season. Does anybody works on such a beast as APL<->Python+Numeric code converter? ;-) Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Saturday, March 09, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "And now for something ruder..." _/ From deathtospam43423 at altavista.com Sat Mar 9 07:02:33 2002 From: deathtospam43423 at altavista.com (Flavian Hardcastle) Date: 9 Mar 2002 12:02:33 GMT Subject: Q: How can I lock a file in Windows? References: Message-ID: Graham Ashton wrote in news:XBli8.5326$OP.143152 at stones: > On Sat, 09 Mar 2002 10:06:08 +0000, A.Newby wrote: > >> Is there another way I can lock the file in Windows? > > Yes. Try this: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 > Thanx! That should work, except I don't seem to have the following extension modules ... win32con, win32file, and pywintypes. Any idea where I can get them? -- "You can tell whether a man is clever by his answers. You can tell whether a man is wise by his questions." Naguib Mahfouz netvegetable at dingoblue.net.au From jeff at ccvcorp.com Wed Mar 27 14:10:26 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 27 Mar 2002 11:10:26 -0800 Subject: turning a python script to windows service References: <3CA014BC.6090204@skippinet.com.au> Message-ID: <3CA21921.833C3FB1@ccvcorp.com> kedai wrote: > is there anything special that i need to do if i wanted to do more > stuff; for example, i tried copying files but nothing was copied. > > snippet: > os.system('copy file filedst') #instead of print statement This *should* work if you specify the fully qualified pathnames for the files involved. One of the things to watch out for with services (in my *very* limited experience), is that it's not safe to assume much of anything about your environment (including current working directory, etc). If you want to test it, I'd change the above statement to this: cmdline = 'copy file filedst' print cmdline output = os.popen(cmdline) for line in output: print line This will, first off, print (to the trace window) the command that you're intending to run. Then it runs the command in a pipe, giving you the output of that command, which is printed to the trace window. This should help you to see what, if anything, is happening -- if you're getting an error from Windows for that command, this should display that error in the trace window. Of course, for small files, I'd be more likely to copy them using this: open(filedst, "wb").write( open(file, "rb").read() ) rather than using the os.system() call. Jeff Shannon Technician/Programmer Credit International From peter at engcorp.com Sat Mar 23 02:09:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 23 Mar 2002 02:09:04 -0500 Subject: circular imports (don't yell!) References: Message-ID: <3C9C2A10.E54A917B@engcorp.com> Sean 'Shaleh' Perry wrote: > > > > > Also, do you realize that "from X import *" is a bad idea > > in general? I'll assume that was just something you did > > to try to reproduce the problem in a small sample program... > > > > in his defense, the gui libs often expect you have done a from X import *. > otherwise your commands are fiendishly long and ugly. > > win = gui.create_window(gui.top_level, gui.foo, gui.bar) If he's writing the equivalent of the GUI libs, I take your point. Though I admit there are specific cases where that's a valid thing to do (I did say "bad idea _in general_", not "bad idea always"), I suspect this is not one of those cases. Or at least I was just trying to caution him in case he didn't know about that guideline. -Peter From timr at probo.com Sun Mar 3 19:09:03 2002 From: timr at probo.com (Tim Roberts) Date: Sun, 03 Mar 2002 16:09:03 -0800 Subject: Minor, minor style question References: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: <7le58u86cc6u7ibsdobuj7jk8gqobuluq5@4ax.com> claird at starbase.neosoft.com (Cameron Laird) wrote: >Why would I prefer > string = "" > string = string + "abc " > string = string + "def " > string = string + "xyz" >over > string = "abc " + \ > "def " + \ > "xyz" >? I see a lot of the former in contexts I associate >with Visual Basic- or JavaScript-majority folkways. >Is there an attraction to the redundancy (and fragil- >ity!) I'm missing? Are \-s *so* deprecated? Visual Basic programmers write things this way because VB didn't support line continuation characters until relatively recently. Until then, you either had to write your concatenated strings as one VERY long line, or via your first method. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From spencer at efn.org Fri Mar 1 17:56:44 2002 From: spencer at efn.org (Spencer Ernest Doidge) Date: Fri, 1 Mar 2002 14:56:44 -0800 Subject: Windows Memory Mapped Files Message-ID: Is there a way, running a Python script in a console window, to read/write Memory Mapped files? Spencer Doidge www.spencerdoidge.com From martin at v.loewis.de Fri Mar 8 04:09:52 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 08 Mar 2002 10:09:52 +0100 Subject: Returning strings from DLLs written in Delphi References: Message-ID: tkeon0 at netscape.net (Trevor Keon) writes: > I have been trying to get a DLL written in Delphi 5 to return a string > to Python 2.1.2 (i use windll to access the dll), and all I get is a > bunch of numbers(the numbers stay the same too). [...] > Does anyone have any ideas how to get around this problem? I recommend to not use windll, but to write an explicit wrapper instead (in C or Pascal, at your option). To my knowledge, PASCAL strings start with a length indication. I doubt that this is a data type supported by windll. Regards, Martin From brueckd at tbye.com Wed Mar 27 12:08:13 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 27 Mar 2002 09:08:13 -0800 (PST) Subject: instrumenting Python code In-Reply-To: <15521.59902.657216.982543@12-248-41-177.client.attbi.com> Message-ID: On Wed, 27 Mar 2002, Skip Montanaro wrote: > > Dave> The hotshot module doesn't appear to have any documentation > Dave> yet. > > That's true. Here's my simple usage scenario: > > import hotshot > profiler = hotshot.Profile("/home/skip/tmp/csv2csv.prof") > profiler.run("main()") > profiler.close() > stats = hotshot.Stats("/home/skip/tmp/csv2csv.prof") > stats.print_stats() Thank you! This is way cleaner than what I posted! Now, about profiling multithreaded applications. Do you have any suggestions? -Dave From andy.elvey at paradise.net.nz Sat Mar 2 21:59:57 2002 From: andy.elvey at paradise.net.nz (Andy Elvey) Date: Sun, 3 Mar 2002 15:59:57 +1300 Subject: PEP 262 (database of installed Python packages) Message-ID: <3wgg8.685$Qo2.70120@news02.tsnz.net> Hi all. I've just been mulling over this (_very_ good and welcome!) PEP. In fact, this suggestion is _so good_ that I'd like to "widen" it somewhat. Allow me to explain .... (and please forgive the slight diversion past "Rubyland" .... :-) I've spent a _frustrating_ amount of time with a _Ruby_ package that can't find various files. Now, I knew about PEP 262, so I was thinking in general terms, it would be *truly* wonderful if there were a (standard?) database of *all* installed packages (Python, Ruby, and whatever else) - maybe in a directory called "search". In Linux, this could be "/search" , in Win32 "C:\search". ( I'm just trying to get maximum value for any effort put into the search area , as this _really_ is a bugbear for most prog languages ..... :-) . I'm mulling over putting in a RCR (Ruby change request) , with the possibility of that being co-ordinated with PEP262. If this were to be done (an all-in-one database), it would certainly take a fair amount of coordination, with say Matz and a few others . In Linux, maybe the creation of a standard "search" directory and database would fall into the LSB (Linux Standard Base) area - I'm aware that v1 of that has just been done, so this may take a while. Windows may be more problematic ..... Anyway - just thought I'd test the waters on this - is there anyone else out there who'd love to see a single "search database"? ( Imagine - no more fiddling with this path, or that path , blah blah .... ) Thanks for your time, and for your comments ! From ggerrietts at yahoo.com Sun Mar 3 17:01:24 2002 From: ggerrietts at yahoo.com (Geoff Gerrietts) Date: Sun, 3 Mar 2002 14:01:24 -0800 Subject: new images from strings using PIL In-Reply-To: <3C828D16.9020201@mxm.dk> References: <3C828D16.9020201@mxm.dk> Message-ID: <20020303220124.GB12980@isis.gerrietts.net> Quoting Max M (maxm at mxm.dk): > BL wrote: > > >pixels = "1 2 3 4 5 6" //test pixels > >im = Image.fromstring("I", (2,1), pixels) //create a 3x2 image from pixels > >These values are obviously wrong. Why isn't my 3x2 image being created > >with the proper pixel intensities? I can't answer this question exactly, because I'm not familiar with the "I" image format. However, I can offer some insight into what "fromstring" and "tostring" expect to do. The string is straight binary data. Max is right about that. But it's not stored as a particular file format. The string needs to be represented more or less like it will be internally stored. (This isn't entirely true, because PIL does some padding of bytes in its internals, but it's mostly true.) RGB and RGBA are what I'm most familiar with, because that's what I generally work with. For those formats, you're looking for a sequence of 3 or 4 bytes per pixel, respectively. For instance, your 3x2 image in all white might look like: s = "\xFF" * 3 * 6 p = Image.fromstring("RGB", (3,2), s) Again, I'm not sure how the "I" format works, but my guess is that you're going to want to pack your integers into a string. Thanks, --G. -- Geoff Gerrietts -rw-rw-rw-: permissions of the beast From sholden at holdenweb.com Thu Mar 7 10:01:25 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 7 Mar 2002 10:01:25 -0500 Subject: create zip archive References: Message-ID: "99miles" wrote in message news:f5adfd88.0203061519.608151a7 at posting.google.com... > hi- > i am creating a zip file from a directory. it is working great, but > the files in the subdirectories get put into the top level directory > in the zip file. I want the directory structure to remain intact when > i extract the zip file. > How can I do this? Any ideas? thanks a lot- > Mac > > I am using this code, currently: > > for name in glob.glob("mypath/*"): > if os.path.isfile(name): > file.write(name, os.path.basename(name), > zipfile.ZIP_DEFLATED) Seems like all you have to do is remove some of the stuff you already put in . The second (arcname) argument to the zipfile.write() method assigns the path within the archive with which the named file's content will be associated). so, if your last line became :: file.write(name, name, zipfile.ZIP_DEFLATED) I'm guessing you'd be in better shape . Tips: for testing, just omit the last argument to .write() -- it still works. It may even work out faster given the defaults and your environment. WinZip et al should be able to handle the resulting files. You can even compress them! The code looks OK, though I guess you are aware that it only goes one level deep in the directory hierarchy. You only have to ask and you will get several brilliant suggestions as to how to generalize your perfectly adequate algorithm (none from me, BTW ). You may already know that PythonTime, the universal standard on c.l.py, sometimes gets manipulated in ways we only become aware of later. To save you some time, here's a synopsis of the next seven days on this thread. Twenty-four hours after your original posting the discussion turns to suggestions for recursive solutions of your problem. A further twenty-four hours sees the focus change to whether recursive methods are better generally (for several different values of "generally"). Several people nostalgically remark how like their favorite LISP Python is, and they'll still be talking about LISP in another thread in another ten years. They will be right. After three days, someone complainsthat the interpreter still doesn't optimize tail recursion. A day later, when a mild flurry of "this has been discussed many times before" and "have you never used Google" postings has died down, people are talking about how the zipfile is the salvation of the import world. Nobody will ever ask you whether you got your original problem solved, and after two weeks the thread becomes a discussion on how distutils could import modules from XML namespaces with authenticated access. But we'll love it when you tell us how you did solve your problem. Especially as a HOWTO. Welcome to c.l.py in-the-spirit-of-less-is-more-ly y'rs - steve FRED - THIS ONE'S COMING THROUGH ON A FAT PIPE YOU MAY HAVE TO PULL THE PLUG From thibaut.leduc at ac-lille.fr Fri Mar 15 05:54:38 2002 From: thibaut.leduc at ac-lille.fr (tleduc) Date: 15 Mar 2002 02:54:38 -0800 Subject: converting reference name to string ? Message-ID: <14b2057b.0203150254.2480f7ae@posting.google.com> example: def a(): print 'hello' ==> string is a.__name__ but for instances: class myclass: ....etc.... b = myclass() c = myclass() in execution of this script, how do i get reference string 'a' 'b' or 'c' ? Thanks in advance. Thibaut From anthony at ekit-inc.com Sun Mar 3 23:03:06 2002 From: anthony at ekit-inc.com (Anthony Baxter) Date: Mon, 04 Mar 2002 15:03:06 +1100 Subject: what I would like to see in python to make a better "glue" language (Newbie) In-Reply-To: Message from anthony_barker@hotmail.com (Anthony_Barker) of "26 Feb 2002 13:25:15 -0800." <899f842.0202261325.6ff3dd54@posting.google.com> Message-ID: <200203040403.g24436x04613@burswood.off.ekorp.com> [sorry about the delay in responding, my email access is somewhat sporadic at present] >>> Anthony_Barker wrote > 1. LDAP module should be included in the base distro. Active Directory > is already available via com (nice) I'm not convinced that this should be in the base distribution. Aside from anything else, it often requires particular LDAP libraries to install. I do think it should be easier to find and auto-install packages, but the standard answer to this is, as ever, "send code". > Important: > 2. DNS really should be included in the base library, I emailed > Anthony Baxter and he replied, saying it was almost done. It is a > hassle to parse the dig (nslookup) output as I ended up doing, as it > is not portable. Yep. I'm still waiting for my bloody ADSL connection so I can pick this up and run with this. > 3. Telnet Library is great - including an SSH module would be a nice > addition. There's two sourceforge projects for this: http://sourceforge.net/projects/pyssh1/ http://sourceforge.net/projects/pyssh/ I've not compared the two, though. > Less important: > 4. Include an SNMP implementation, there are several around, but a > pure python one as a library would be nice Again, not really suitable for the base install, but as an added extra it would be nice. > 5. RRDTOOL - a nice wrapper would be nice ( there may be one already) Not sure. > One more idea for Administrators/Glue Implementers; lots of code > examples is key. Someone needs to write these examples. This is a non trivial amount of work. Anthony -- Anthony Baxter It's never to late to have a happy childhood. From phr-n2002a at nightsong.com Mon Mar 4 20:51:50 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 04 Mar 2002 17:51:50 -0800 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: <7xvgcblr2h.fsf@ruckus.brouhaha.com> Tim Peters writes: > I don't understand your "no": the output shows that Python was built using > GCC 2.95.2, yet you're claiming this does *not* use glibc? gcc and glibc go > together like Guido and Van Rossum . The BSD-based distributions generally use the BSD C library (done at Berkeley) rather than glibc, in order to avoid the GNU GPL/LGPL affecting the compiled/linked binaries. From James_Althoff at i2.com Fri Mar 1 18:57:26 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 15:57:26 -0800 Subject: Status of PEP's? Message-ID: [Jim] > In other words, if I want to iterate up (smaller up to larger) I need to > write the for-loop as > for smaller <= i <= larger: # can *only* iterate up > but if I want to iterate down (larger down to smaller) I need to write the > for-loop with the reverse relational operators > for larger >= i >= smaller: # can *only* iterate down > > So if you want/need "from/to" functionality for an "interval" using the > suggested for+relational idiom, you need to have two for-loops at hand, > test the bounds, *and* pick the corresponding, correct for-loop (whose > relational operators are in the correct direction). > > Note that the existing range and xrange functions (when used in a > for-loop), although requiring a test on the bounds in order to determine > the correct order of the args, do *not* require the use of two for-loops in > this context. > for i in range(n,m,step): # can iterate up or down depending on > n,m,step [David Eppstein] > Ok, I missed your point that the iteration order and not just the > endpoints are important in your example. > > But I think the current range system does too require two loops. I guess I was still a little fuzzy in my explanation. I meant this: (ignore open/closed stuff) >>> >>> def printFromTo(start,end): ... # only dealing with step == 1 or -1 ... step = 1 ... if start > end: ... step = -1 ... for i in range(start,end,step): # up or down ... print i ... >>> printFromTo(5,10) 5 6 7 8 9 >>> printFromTo(10,5) 10 9 8 7 6 >>> > Anyway, while you may need two ranges, you don't have to have two > separate for-loops over those ranges: > if from <= to: range = [x for from <= x <= to] > else: range = [x for from >= x >= to] > for x in range: > ... I agree that if you actualize the ranges using list comp.s as shown, then your one final for-loop is enough. I was counting list comp.s as "for loops", also. But your example shows what I was trying to say. In this case you need one list comp for the "up" case and one for the "down" case. That is the limitation that I was trying to point out. Jim From emile at fenx.com Fri Mar 1 14:11:34 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 1 Mar 2002 11:11:34 -0800 Subject: __abs(self)__? References: Message-ID: "Mike Carifio" wrote in message news:f3Qf8.2391$26.139172 at typhoon.maine.rr.com... > I'm reading about special method names. __abs__(self), which maps to the > abs() method seems unneccessary(?). compare: From amckay at merlinsoftech.com Mon Mar 11 13:14:49 2002 From: amckay at merlinsoftech.com (Andy McKay) Date: Mon, 11 Mar 2002 10:14:49 -0800 Subject: Zope stdin In-Reply-To: References: <3C8BECF0.30207@void.si> Message-ID: <200203111814.g2BIEKq26225@mail.merlinsoftech.com> On March 11, 2002 06:17 am, you wrote: > Are you sure? My echo is not working properly in ZCGI. > BTW, I dont want to run a separate process, i just want to read() > posted data AS in CGI. Why can you not do this in Zope as Python Script, External Method or even DTML? The Zope mailing lists are normally a good place for answers BTW. -- Andy McKay From tejarex at yahoo.com Fri Mar 15 08:58:52 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 15 Mar 2002 13:58:52 GMT Subject: does Python support some kind of "casting" References: Message-ID: "Tino Lange" wrote in message news:a6shn9$9l6$1 at crusher.de.colt.net... > Duncan Booth wrote: > > Yes, that will make a copy. But copying a list is a pretty efficient > > operation, so no, it isn't really horribly inefficient. Have you tried it > > and identified this as a bottleneck? How long are your lists anyway? > > 3600 Elements each. The copy requires 4*3600+10(about) bytes - about 15000 - and less than a millisecond with two allocations for header and list of pointers and two machine-code memmove instructions. Probably not a bottlenect operation on any modern machine. Terry J. Reedy From akuchlin at ute.mems-exchange.org Wed Mar 6 12:24:38 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 06 Mar 2002 17:24:38 GMT Subject: Flushing stdout with raw_input - BUG References: Message-ID: In article , Michael Hudson wrote: >> I did a semi-thorough investigation on the matter, and there really isn't >> much information on how I make the move from being a python user to a >> developer. Apparently it's by invitation only. Do I just keep submitting >> bugs and patches and opinions and eventually someone will notice me > > More or less, yes. I once started a document describing how Python is developed, and how to help. A draft is at http://www.amk.ca/python/writing/python-dev.html . What this thread shows is that the section on reporting bugs should be expanded before calling it complete... --amk (www.amk.ca) Beware the devious Calib. One day he'll get so cunning even he won't know what he's planning. -- Leela, in "The Face of Evil" From eti_antoniutti at hotmail.com Mon Mar 25 06:17:38 2002 From: eti_antoniutti at hotmail.com (etienne) Date: 25 Mar 2002 03:17:38 -0800 Subject: python cgi problem Message-ID: <1573b893.0203250317.693ef1dc@posting.google.com> hi there ! I'm programming such a cgi: step 1- user submits some data step 2- cgi validates data step 3- outputs a html file telling the user to wich url point to find output step 4- do the hard work. the reason for step 3 is that step 4 needs to dig in a very large database, and may take lot of time everything woks fine but output of step3 comes when step 4 is over and user needs to wait up to some minutes for his response. cgi schema is as follow: def main(): # 2 params = validate_params() # 3 htm_out = generate_output() print htm_out # 4 os.system(" python my_module.py params &") I can see results of print htm_out when os.system(" python my_module.py params &") is over can i force htm_out output somehow ??? any suggestion tnxs in advance etienne From gjlap at yahoo.com Fri Mar 1 01:10:41 2002 From: gjlap at yahoo.com (Gil) Date: 28 Feb 2002 22:10:41 -0800 Subject: python and eroaster Message-ID: <1eed326b.0202282210.2ba54f24@posting.google.com> I've installed eroaster-2.0.11-0.7.noarch.rpm with no problem on my RedHat 7.1 box. I chose noarch because it seemed to be the only stable version that wasn't i586 or i686. I used the 'extra' verbose switch with rpm and it gave a complete run down of the install. It's all there. But when I try to run it, bash: /usr/bin/eroaster: No such file or directory It even finds the dir! The executable shows up in kde with the proper permissions but not as an icon of a gear but as a piece of paper with a question mark on it. Hmmm, something not right here ;-) I'm running Python2.2 and it gets along OK with my Pygame stuff. Thanks in advance for any help in this matter. -Gil From peter at engcorp.com Mon Mar 4 19:02:42 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 04 Mar 2002 19:02:42 -0500 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> <3C837DD1.2007DFA0@engcorp.com> <3C838BD4.5A5D9298@kfunigraz.ac.at> Message-ID: <3C840B22.A30CD7AE@engcorp.com> Siegfried Gonzi wrote: > > Peter Hansen wrote: > > > > Siegfried Gonzi wrote: > > > As far as absolute time goes, don't use a tool for that. Just > > run the program and ask yourself "was that fast enough for my > > needs?". If your program runs once a day, even 70 sec is fast > > enough. If you run it every thirty seconds, I guess you have > > to go with the Clean version after all. :-) > > Please: Do not use Clean! [...] Trust me, no risk of that happening. Python serves all my programming needs, and then some, except for the embedded work I do. C handles all my programming needs there, except for a little bit of low-level embedded work I do. Assembly handles all my programming needs there... I'm just happy that after twenty years of programming I actually have so few languages to serve all my needs. Pretty amazing, really, when I think about it. (Thanks, Guido. ;-) -Peter From peter at engcorp.com Fri Mar 15 08:17:38 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 15 Mar 2002 08:17:38 -0500 Subject: does Python support some kind of "casting" References: Message-ID: <3C91F472.FB2B67C7@engcorp.com> Tino Lange wrote: > > > Yes, that will make a copy. But copying a list is a pretty efficient > > operation, so no, it isn't really horribly inefficient. Have you tried it > > and identified this as a bottleneck? How long are your lists anyway? > > 3600 Elements each. > > No I didn't check if it's a bottleneck. But I immediately didn't feel good > when writing "return list(newlist)" (the list contains a list of strings > itself - so it's much stuff to copy) Get over it. 3600 elements is nothing, especially once you realize that the strings themselves are not duplicated, just the references. Anyway, the "immediately didn't feel good" thing is probably a feeling you'd best learn to ignore more. :-) Only optimize when you have actually identified a bottleneck by profiling. And a "bottleneck" is not something that runs "slow", but something that runs "too slow" which means you also need to have a specific requirement in mind before spending your valuable time optimizing. Once I learned this it has made my programming life much easier. -Peter From logstx at bellatlantic.net Tue Mar 5 21:31:55 2002 From: logstx at bellatlantic.net (logistix) Date: Wed, 06 Mar 2002 02:31:55 GMT Subject: Nested scopes: design or implementation? Message-ID: Is the following code operating this way by design or is it just implementation? It seems to indicate that the nested function is redefined each time the parent function is called. Is this necessary or desirable? Just wondering what other people think. >>> text = "random text" >>> def function(): def attribute( bindNow = text): print bindNow function.attribute = attribute ... >>> function.attribute() Traceback (most recent call last): File "", line 1, in ? AttributeError: attribute >>> function() >>> function.attribute() random text >>> text = "new random Text" >>> function.attribute() random text >>> function() >>> function.attribute() new random Text >>> -- - From garret_mcgraw at yahoo.com Mon Mar 18 19:34:49 2002 From: garret_mcgraw at yahoo.com (Garret McGraw) Date: Mon, 18 Mar 2002 19:34:49 -0500 Subject: Digest Number 868 Message-ID: <20020318193449.A1716@wood.mcgraw.org> Hi- Does any know a good way to talk to a mysql database besides depending on the fact that the computer might happen to have that mysql module installed? I guess I could just figure out how the protocol works and access it by opening a socket to it and interpert what it gives me...... but I would like to know if someone has already done that and see if i could download it. It can be very simple...just as long as its there and it will do simple things. If there is no such thing then does anyone just think this is a project that could not done right? Let me know what you think about it. GEM From peter at engcorp.com Tue Mar 12 19:38:11 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 12 Mar 2002 19:38:11 -0500 Subject: NormalDate 1.2 released References: Message-ID: <3C8E9F73.E03FD8D4@engcorp.com> "Delaney, Timothy" wrote: > > 13 x 28 day (4 week) months = 364 days. [...] > IIRC this is the system that the shire hobbits used. > > Why was this simple system never adopted? I'm pretty sure it's because the hobbits were all wiped out after Sauron rose again and conquered Middle Earth, imposing the Unified Mordorian Calendar system across much of the planet until the changes made by Pope Gregory in 1582. -Peter From rs96057 at hotmail.com Mon Mar 25 19:34:44 2002 From: rs96057 at hotmail.com (Dimitris Garanatsios) Date: Tue, 26 Mar 2002 02:34:44 +0200 Subject: pythonwin and raw_input References: Message-ID: > > Does anyone know how to access the builtin raw_input function in pythonwin? > Pyhtonwin overrides it with a dialog box. This doesn't work out too well > with the following: > The same problem used to torture me but i think the most proper solution is just to ignore it... You could make a shortcut to run your program or run it from a Command prompt, in which case everything should work fine (as far as the "raw_input" part is concerned...) In general i try to avoid running programs from within IDEs, such as IDLE or PythonWin, and the reason is that initialisation of the interpreter after the program exits cannot be done, leading someone to problems and mischief... (for example if you had imported a module from the interactive window of PythonWin, then the module would be available in the namespace of module __main__ of any loaded script even without a direct import statement from within your program!) I also have noticed problems when running wxPython applications from within PythonWin... So unless you can't avoid it, don't use the "Run" command (although it is still useful for small scripts and for testing purposes...) Dimitris From jjb5 at cornell.edu Fri Mar 22 15:32:34 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Fri, 22 Mar 2002 15:32:34 -0500 Subject: New SIG on logic/CLP programming in Python References: Message-ID: > I am looking for interested people to form a Logic-SIG or CLP-SIG. Count me in. > I'll try to post an example here this week-end. Looking forward to it, I'll have a counter example on Monday. :-) Joel From bokr at oz.net Tue Mar 19 21:52:17 2002 From: bokr at oz.net (Bengt Richter) Date: 20 Mar 2002 02:52:17 GMT Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> Message-ID: On 19 Mar 2002 16:17:15 -0800, jriveramerla at yahoo.com (Jose Rivera) wrote: >Hi... > >Thanks in advance for any help... > >I want to retrieve data from the web for historic research >about real state prices, fetching the info from a newspaper page, >for personal use, loading this to MySQL DataBase for later study on >trends, but I don't want to be doing this procedure manually every >day. > >But this routine just gives me an error, please try it >and see whats wrong?, I have not found what am I missing. > >When I try the address genereated by the code directly on the >iExplorer.EXE, it works... but not on Python... > >This is the routine: >-------------------- >import os >import urllib > >params={} >params["pagina"] = 1 >params["Presentacion"] = "Tabla" >params["Tipo"] = "CASAS" >params["Order"] = "Order By Fecha Desc" "order by colonia" if you want to duplicate the address below [1] >params["id_inmueble"] = "3" >params["zona"] = "0" >params["COLONIA"] = "0" >params["RECAMARAS"] = "0" >params["BANOS"] = "0" >params["dia"] = '' >params["PLANTAS"] = "0" >params["Constr_i"] = "-1" >params["constr_f"] = "-1" >params["Terreno_i"] = "-1" >params["Terreno_f"] = "-1" >params["Precio_i"] = "-1" >params["Precio_f"] = "-1" >params["fotos"] = "0" > ># This is the address calculated >#http://avisos.elnorte.com/casa_venta_result.asp?fotos=0&Order=order+by+colonia&Precio_i=-1&Presentacion=Tabla&Precio_f=-1&PLANTAS=0&pagina=1&id_inmueble=3&dia=&RECAMARAS=0&constr_f=-1&COLONIA=0&BANOS=0&Tipo=CASAS&Constr_i=-1&Terreno_i=-1&Terreno_f=-1&zona=0 ^...[1] > That is not the address calculated. The difference (other than upper case HTTP://AVISOS.ELNORTE.COM) is Order=order+by+colonia Order=Order+By+Fecha+Desc >pms=urllib.urlencode(params) >direccion="HTTP://AVISOS.ELNORTE.COM/casa_venta_result.asp?%s"%pms >#print direccion >f=urllib.urlopen(direccion) > >ff=open('xc.htm','w') >ff.write(''+direccion+'<\br>') ^^^^^^^ '' ?? >ff.write(f.read()) >ff.close > I think you may need a del ff after ff.close to let go of xc.htm so start can use it, though I think that's a bad idea. In general this would be dangerous, since it will make the browser think the page is safe (to it, it's coming from your disk this way). >os.system('start xc.htm') Better to look at it with a non-html-executing editor, e.g., os.system('start write xc.htm') I haven't a clue as to what parameter formats are for that site, but it returns ---------------

    Microsoft VBScript runtime error '800a000d'

    Type mismatch: '[string: ""]'

    /barra.asp, line 87 --------------- And when I paste your original address line into IE5, it also returns --------------- Microsoft VBScript runtime error '800a000d' Type mismatch: '[string: ""]' /barra.asp, line 87 --------------- So maybe the site has a problem, or some parameter is the wrong format. I can't help you there, unless you have a definition of the format. An exact copy of an URL that works from the browser would help. The one in the comment is not it. Regards, Bengt Richter From jimd at vega.starshine.org Fri Mar 22 06:02:02 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 22 Mar 2002 11:02:02 GMT Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: In article , Jim Dennis wrote: >In article , Nick Arnett wrote: >>> I don't know what you're really trying to do, but I decided to >>> code up a quickie "word counter" for the hell of it. >>Wow -- thanks. I'm going to ask questions more often now! >>Nick > I deliberately made it a class so you could instantiate > multiple word counts on different blocks of text to compare them > or whatever, and so you could import it into other programs and > use other methods (i.e. a web spider with urllib and a "text" extractor > with htmllib) to get your text. So, in my ongoing effort to bolster my Python programming skills, I decided to add PostgreSQL support to my word frequency counter. This is my first bit of SQL RDBMS programming. In this case it was pretty simple (the hardest part was convincing Debian to re-install postgresql cleanly in my user chroot jail, that's a wrinkle that need not be elaborated upon here). I only had to add five lines of code (including the import directive) to make this dump the words and word frequencies into a database table. (The import is the first line in "__main__" and the the work is all in the last four lines. A comment shows the DML to create the table). (I also had to re-write a few lines where I was flagging the "known words" in my output). However, my approach is pretty crude; I should be querying the db to update words that are already in the table, and only inserting new rows for new words. Maybe I'll do that for version 0.3 Here's the updated version: #!/usr/bin/env python2.2 """ Word Frequency Counter """ import sys, string author="James T. Dennis " version="0.2" changelog=""" Fri Mar 22 02:52:28 PST 2002 added support for dumping results into database """ bugs=""" Will create duplicate words in the table, I should query the list into a dictionary, class Wordcount: """Keep a count of all unique "words" in text Maintain a dictionary or words, each with a count of the number of occurences, Add arbitrary text to it, return the dictionary on demand Generator for most/least frequent words ??? Options for allowed charset, and case sensitivity ???""" # for words like isn't and O'Holloran and fiddle-faddle # what should we do about contractions? # ditto possessive forms? tr = string.maketrans('','') rm = string.punctuation + string.digits rm = string.translate(rm, tr, "'-") # Don't remove apostrophes and hypens from "words" knownWords = {} knownWordsRead = 0 def __init__(self): self.words = {} self.count = 0 # total words processed self.nword = 0 # number of words in our instance dictionary self.known = 0 # number of our words found in the class dict. # Each instance gets its own word list and total count if not Wordcount.knownWordsRead: # We'll try to create the "known words" dictionary # But we only do that on first instantiation # since all instances share this one dictionary try: Wordcount.knownWordsRead = 1 wlist = open('/usr/share/dict/words','r') for i in wlist: i = i.lower().strip() if not i in Wordcount.knownWords: Wordcount.knownWords[i] = 0 except: pass # but we won't try very hard # print "debug: ", word def add (self,text): for each in text.split(): word = string.translate(each, Wordcount.tr, Wordcount.rm).lower() word = word.strip() while word.endswith("'"): word = word[:-1] # strip quotes while word.startswith("'"): word = word[1:] # if word.startswith('-'): continue if word.endswith('-'): continue if word.endswith("n't"): word = word[:-3] # can't include these if word.endswith("'ll"): word = word[:-3] # or you'll wonder if word.endswith("'s"): word = word[:-2] # who's if word == '-' or word == "'" or len(word) < 1 : continue self.count += 1 if not word in self.words: self.words[word] = 1 self.nword += 1 else: self.words[word] += 1 if word in Wordcount.knownWords: self.known += 1 def dump (self): self.items = [ (y,x) for x,y in self.words.items() ] self.items.sort() self.items.reverse() return self.items if __name__ == '__main__': import psycopg wcount = Wordcount() for i in sys.argv[1:]: file = open(i,"r") for line in file: wcount.add(line) # handle hyphenation? ## poss. by cutting last word IFF ends in hyphen ## and prepending to next line. print wcount.count, wcount.known, wcount.nword, \ wcount.known/float(wcount.count), wcount.nword/float(wcount.known) l = [] for count, word in wcount.dump(): if count > 1: # Skip "unique" words if word in Wordcount.knownWords: f = '*' t = (word,count,'true') else: f = '' t = (word,count,'false') l.append(t) print "%7d %s%s" % (count, word, f) print wcount.count, wcount.known, wcount.nword, \ wcount.known/float(wcount.count), wcount.nword/float(wcount.known) ### Dump into database: db = psycopg.connect('dbname=test user=jimd') ## db.execute('''CREATE TABLE word_frequencies ## (word text, count integer, known boolean'''') cursor = db.cursor() cursor.executemany("insert into word_frequencies values (%s, %d, %s);", l ) db.commit() One thing confuses me a bit. I'd always heard that database cursors are an extemely limited resource and that the use of them is best avoided, yet the DB-API docs(*) seem to suggest that you usually use cursors with Python db connections but that one could do .execute() function on db connection *WITHOUT* the cursor. """ Next, you should create a cursor object. A cursor object acts as a handle for a given SQL query; it allows retrieval of one or more rows of the result, until all the matching rows have been processed. For simple applications that do not need more than one query at a time, it's not necessary to use a cursor object since database objects support all the same methods as cursor objects. We'll deliberately use cursor objects in the following example. (For more on beginning SQL, see At The Forge by Reuven Lerner in LJ, Octoboer, 1997.) """ * ( http://www.amk.ca/python/writing/DB-API.html ) Yet, I can't seem to find those in psycopg. Is psycopg DB-API 2 compliant? Is this feature there? Or does DB-API not require this feature? From peter at engcorp.com Sun Mar 24 13:13:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 13:13:14 -0500 Subject: Stopping threads from the outside References: Message-ID: <3C9E173A.88BBDBB4@engcorp.com> holger at trillke.net wrote: > > > >how could you stop a running threading.Thread from the *outside*? of > > >course i could introduce some kind of flag into the event loop of the > > >Thread.run-method, but i really would prefer to have a non-instrusive > > >way for several reasons. > > > > > >Any way to do this? > > > > Not really. Why do you want to do it? > > You really want to know it? I am currently working > on (coded) agents which move through the network. "The network"? Which one? The Internet, or an internal network over which you have full control? Who controls the servers on which these agents will be running? > But of course i'd sometimes like to shut down some or > all agent-threads. Run them in a separate process and kill the process when it's "sometime"? If you can live without individual control. Maybe you can identify groups of them? > Is the questions actually strange in any way? Like something > you wouldn't usually like to do? Yes, that's the case. It's generally considered to lead to undefined behaviour if you do manage to kill a thread from the outside, because of resource locking issues and such. Maybe you can get by with Stackless Python? The microthreads provided there ought to be more easily killable, though I haven't tried it myself. -Peter From graz at mindless.com Fri Mar 15 16:20:28 2002 From: graz at mindless.com (Graham Ashton) Date: Fri, 15 Mar 2002 21:20:28 +0000 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: On Fri, 15 Mar 2002 18:49:09 +0000, Skip Montanaro wrote: >>>>>> "Joe" == Joe Grossberg writes: > > Joe> Is there any effective difference between the two? > > Nope. I read somewhere (don't ask me where) that != is preferred. -- Graham From arturs at iidea.pl Wed Mar 6 06:28:06 2002 From: arturs at iidea.pl (Artur Skura) Date: Wed, 6 Mar 2002 11:28:06 +0000 (UTC) Subject: [ANN] istring 1.0.1 released; announce list created References: Message-ID: Steven D. Arnold wrote: > Neosynapse has released istring 1.0.1, a module for interpolating > strings in Python. String interpolation means you can put variables > directly in strings, like this: > >>>> from neo.istring import istring as i >>>> n = 100 >>>> s = i("Value is $n") >>>> s > "Value is 100" Seems a nice feature - maybe you can consider fighting for inclusion in standard Python distribution? Regards, Artur -- http://www.wolneprogramy.org From ponderor at lycos.com Mon Mar 4 15:06:11 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 4 Mar 2002 12:06:11 -0800 Subject: Time to rename Stackless? References: Message-ID: Tim Peters wrote in message news:... > [Christian] > > Not bad! > > Should I start a contest? > > I vote for "Christian Python". "CrisPy" sounds good to me.. ..could you get Forrest Gump to to the pronounciation sound file? -Dean From logstx at bellatlantic.net Wed Mar 20 18:17:51 2002 From: logstx at bellatlantic.net (logistix) Date: Wed, 20 Mar 2002 23:17:51 GMT Subject: How to delete/mainpulate global variables ?? References: Message-ID: If the statement 'del val' isn't doing what you need, store the variable in a global list or dictionary. That way all references will point to the same underlying object. A modification in one place will show up everywhere. -- - "Berenike Loos" wrote in message news:mailman.1016653600.19685.python-list at python.org... Hi I am using two function in my program. The first one reads out some text of an TK entry field and puts it into a global variable. The other function has to read out the global variable and has to print out the text. Now the global variable should be deleted, so if I call the second function again without calling the first, NO text will be displayed. thx a lot -------------- next part -------------- An HTML attachment was scrubbed... URL: From janez.jere at void.si Mon Mar 11 17:41:24 2002 From: janez.jere at void.si (Janez Jere) Date: Mon, 11 Mar 2002 23:41:24 +0100 Subject: Zope stdin References: <3C8BECF0.30207@void.si> Message-ID: <3C8D3294.704@void.si> > > Why can you not do this in Zope as Python Script, External Method or even > DTML? The Zope mailing lists are normally a good place for answers BTW. I dont know how to write it in python script, I waste a lot of time without any progress, ok i learned something about security model, get familiar with some Zope source code. Then I gave up and wrote it with mod_python in a hour. I know that mod_python is not an app server, so I will have to join yet-another-mailing list, but I am not sure that this is posible with zope. Thanks, jj From cbbrowne at acm.org Sun Mar 10 19:21:08 2002 From: cbbrowne at acm.org (Christopher Browne) Date: Sun, 10 Mar 2002 19:21:08 -0500 Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: In an attempt to throw the authorities off his trail, philh at comuno.freeserve.co.uk (phil hunt) transmitted: > On 10 Mar 2002 10:15:06 -0800, Aahz Maruch wrote: >>In article , >>phil hunt wrote: >>>On Sat, 09 Mar 2002 22:57:42 -0500, Peter Hansen wrote: >>>> >>>>I agree with much of what you say, especially the "consider skipping >>>>C++ and just learn C part", but _what_ pragmatic point of view is it >>>>that has one learning Perl, Java, or C++ when one uses Python already? >>>>Not dissing those languages, but when would you really need them? >>> >>>I can think of several tasks for which C++ is better than Python, >>>e.g. writing operating systems, network stacks, windowing systems, >>>run-time interpreters, crypto algorithms, etc. >> >>But are there any tasks for which C++ (or C++/Python) is really better >>than C/Python? > > Any task for whiich OO is useful, which means essentially all > programs >5000 lines (and most smaller ones), will benefit from C++ > over C. Would that include the implementation of runtime code for an at-the-bare-iron OS kernel to support: a) vtables, and b) memory management? Remember, when you're sitting at that level, you have no runtime support code, and so can make no use of: - Virtual functions - Constructors - Destructors I would tend to think that figuring out the usable subset of C++ would become painful enough to discourage its use. And this seems to be a factor strongly correlated with the relative rarity of OS kernels written in C++ as compared to C, in which there is little in the _language_ that requires runtime support... -- (reverse (concatenate 'string "ac.notelrac.teneerf@" "454aa")) http://www.ntlug.org/~cbbrowne/advocacy.html Rules of the Evil Overlord #150. "I will provide funding and research to develop tactical and strategic weapons covering a full range of needs so my choices are not limited to "hand to hand combat with swords" and "blow up the planet"." From martinkaufmann at yahoo.com Wed Mar 13 07:08:34 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Thu, 14 Mar 2002 01:08:34 +1300 Subject: Question about scientific calculations in Python References: Message-ID: <19gu8u499o38h8kvegufd7tcupjni0pucb@4ax.com> On Tue, 12 Mar 2002 23:36:05 -0600, "Jason Orendorff" wrote: >I benchmarked it; results: > > plain Python: 8.557 sec > optimized Python: 2.325 sec > Numeric Python: 0.753 sec That looks really promising! Thanks & Regards, Martin From store_li at sina.com Mon Mar 4 10:38:38 2002 From: store_li at sina.com (Ricky) Date: Mon, 4 Mar 2002 23:38:38 +0800 Subject: Is there any wxPython turtor? Message-ID: I have downloaded wxPython 2.3. But, I found that the document come with it is not well enough. Is there any recommended good tutor of wxPython itself?? BTW: I don't know why I can't connect to www.wxpython.org, is it still alive? From kragen at pobox.com Thu Mar 21 02:56:53 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 21 Mar 2002 02:56:53 -0500 Subject: For loops with explicit indices -- again References: <3c9789ed$0$29676$ba620e4c@news.skynet.be> Message-ID: <833cyucq0q.fsf@panacea.canonical.org> "Armin Rigo" writes: > For example, to decrement all positive integers in a list, modifying > it in-place: > > it = iter(lst) > for x in it: > if x>0: > lst[it.count-1] -= 1 I wish people would stop asking for requirements to be added to the iterator protocol. I think there are good reasons for compliance with it to be trivially easy. Maybe we should start asking for features to be added to variables instead. With my tongue firmly in my cheek, I propose the following new language constructs: onchange expr: suite --- runs suite whenever the location (variable, mapping item, sequence item, attribute, whatever) named by 'expr' changes, like Tcl's variable traces; requires user-implemented containers to call the new itemchanged(self, itemname) function whenever an item changes; requires __setattr__ implementations to call the new attrchanged(self, attrname) function whenever they deem that an attribute has changed. Under the covers, this is implemented in terms of new onitemchange(container, name, thunk) and onattrchange(object, name, thunk) functions. onrefcountchange expr: suite --- likewise, but runs suite whenever the reference count of the value 'expr' presently evaluates to changes. whentrue expr: suite --- uses the onchange machinery to arrange for 'suite' to be run as soon as 'expr' becomes true (by testing 'expr' and establishing onchange handlers for every elementary subexpression of it; obviously this won't work if non-functional functions are involved) number_of_times_written(expr) --- looks like a function, but "expr" is a generalized location, just like the arguments to 'del' or the left operand of '='. Returns the number of times the location named by the expression has changed. number_of_times_read(expr) --- likewise. previous_values_of(expr) --- returns a list of all previous values that had been stored in the location named by 'expr'. number_of_bytecodes_run_since_last_change(expr) --- self-explanatory. From jeff at ccvcorp.com Mon Mar 25 14:56:05 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 25 Mar 2002 11:56:05 -0800 Subject: Replacing excel: but with what ? References: <3C9CCF6C.F1099089@vip.fi> Message-ID: <3C9F80D4.3D37A117@ccvcorp.com> Dale Strickland-Clark wrote: > I would still recommend wxPython. It is a top bit of software. > > Get youself on the mailing list and if you experience problems I am > confident that it will get sorted there. I agree. I haven't used wxGrid myself, but judging from what I've seen on the mailing list, they are both very powerful, and sometimes tricky to get right. The wxpython-users list is very helpful, however. If you post any problems you're having there, you'll probably get a useful reply very quickly. Jeff Shannon Technician/Programmer Credit International From grante at visi.com Fri Mar 8 14:15:48 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Mar 2002 19:15:48 GMT Subject: Turn string into function call References: <1f5252d4.0203080545.3861adec@posting.google.com> Message-ID: In article <1f5252d4.0203080545.3861adec at posting.google.com>, N Becker wrote: > What's the best way to turn a string naming a function into a function call? > > I used this: > eval (funcname + '()') This really ought to go into the FAQ. It's been asked (and answered) at least 3 times in the past week or so. -- Grant Edwards grante Yow! Yow!! That's a GOOD at IDEA!! Eating a whole FIELD visi.com of COUGH MEDICINE should make you feel MUCH BETTER!! From christophertavares at earthlink.net Mon Mar 18 17:51:05 2002 From: christophertavares at earthlink.net (Chris Tavares) Date: Mon, 18 Mar 2002 22:51:05 GMT Subject: Problems embedding with win2k References: <3a7925ca.0203181215.626e8ea3@posting.google.com> Message-ID: "Mark" wrote in message news:3a7925ca.0203181215.626e8ea3 at posting.google.com... > I need to embed a python interpreter in C++ applications in both Win2K > and Linux environments. I have started to work the embedding examples > and have run into problems on the windows side, here is my setup and > problem: > > Environment: > > Win2K Pro, VC6 SP4 > > Problem 1-Very High Level Embedding Example: Access violation in > msvcrtd in debug mode > I work the first example from the Python docs-extending and embedding > sec 5.1. When I build this in release mode the application runs fine. > When I compile and run in Debug mode I get an access violation in > msvcrtd.dll. When the program is run the following two asserts fail: > > Dbgheap.c line: 1044 > _CrtIsValidHeadPointer(pUserData) > Dbgheap.c line: 1050 > _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) > > When I look back through the trace, this error occurs when in > Py_Initialize() when the site module is being imported. I am using > the debug multithreaded dll runtime for debug and the multithreaded > dll runtime for release. I am sure I must have a project setting > wrong but I can't figure out exactly what. > This is most likely a symptom of mismatched debug vs. release libraries. Is the *python* dll you're using compiled for debug mode? If it's not, that would explain the access violations. You'll need to grab the python source tree and compile a debug version on your win32 box. -Chris From duncan at NOSPAMrcp.co.uk Wed Mar 20 09:05:30 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 20 Mar 2002 14:05:30 +0000 (UTC) Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in news:7xk7s7mpiy.fsf at ruckus.brouhaha.com: > Geez, I find all this pseudo-HTML horrendous. Why not just embed > normal looking code in tags the way PHP does it? Do WYSIWYG > editors have a problem with that? If worse comes to worse, embed > the Python code with the kinds of tags used for Javascript. The > WYSIWYG editors should be used to Javascript by now. I think you are missing the point. With or javascript, the remaining HTML in the file very often isn't valid HTML. In particular you very often get situations where the opening and closing tags don't match. Consider with your scheme how you might alter the attributes on the tag while leaving exactly one body tag visible for the wysiwyg editor? ZPT makes this easy provided (and it is a big provided) the wysiwyg editor both preserves and ignores unknown attributes. -- 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 joonas at olen.to Sun Mar 17 15:44:02 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Sun, 17 Mar 2002 22:44:02 +0200 Subject: a text processing problem: are regexpressions necessary? References: Message-ID: <3C950012.514470DC@olen.to> Sandy Norton wrote: > > Hi, > > I thought I'd share this problem which has just confronted me. > > The problem > > An automatic way to tranform urls to articles on various news sites to > their printerfriendly counterparts is complicated by the fact that > different sites have different schemes for doing this. (see examples > below) > > Now given two examples for each site: a regular link to an article and > its printer-friendly counterpart, is there a way to automatically > generate transformation code that is specific to each site, but which > generalizes across all article urls within that site? > > Here are a few examples from several online publications: > > http://news.bbc.co.uk/hi/english/world/africa/newsid_1871000/1871611.stm > http://news.bbc.co.uk/low/english/world/africa/newsid_1871000/1871611.stm > > http://www.economist.com/agenda/displayStory.cfm?Story_ID=1043688 > http://www.economist.com/agenda/PrinterFriendly.cfm?Story_ID=1043688 > > http://www.nationalreview.com/ponnuru/ponnuru031502.shtml > http://www.nationalreview.com/ponnuru/ponnuruprint031502.html > > http://www.thenation.com/doc.mhtml?i=20020204&s=said > http://www.thenation.com/docPrint.mhtml?i=20020204&s=said > > I'm kinda heading in the direction of attempting to generate regular > expressions for each site... But I'm a bit apprehensive about doing > this. Is there a more pythonic way to approach this problem? I would create a dictionary where beginnings of the urls would be keys. Values of the dictionary would be tuples that contain a sting to be replaced and the replacement. replDict = {"http://www.economist.com/agenda/": ("displayStory", "PrinterFriendly.cfm"), "http://www.thenation.com": ("doc.mhtml", "docPrint.mhtml")} Then check what key matches the url and do the replacing with string.replace. From thoa0025 at mail.usyd.edu.au Sun Mar 24 07:06:04 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 24 Mar 2002 12:06:04 GMT Subject: module is in the folder - what am i doing wrong?? References: <3C9D975B.40600@SPAMnwinternet.com> Message-ID: Also forgot to mention, in the python interpreter i performed the following commands Python 2.1.2 (#2, Jan 18 2002, 11:23:35) [GCC 2.95.2 19991024 (release)] on sunos5 Type "copyright", "credits" or "license" for more information. >>> modname = "xml" >>> mod = __import__(modname) >>> mod >>> which shows, the module does exist and accessible from the interpreter.. but why when i run my code, it doesnt work?? hope someone knows :( im getting sad.. cheers trungie "Trung Hoang" wrote in message news:bajn8.5630$EE4.21273 at news-server.bigpond.net.au... > Thanks for your reply Jim, > > i have a file "xml.py" and it has a function named "getProjects()" and i > simply wish to access it from c. i have the source.... > > #include > > int main (int argc, char *argv[]) { > // declare variables > PyObject *modname = NULL; > PyObject *mod = NULL; > > // init > Py_Initialize(); > > modname = PyString_FromString("xml"); > mod = PyImport_Import(modname); > if (mod == NULL) printf("mod is null\n"); > > Py_XDECREF(mod); > Py_XDECREF(modname); > Py_Exit(0); > } > > but when i try to run it, it prints "mod is null", meaning it cant find the > module. but the module is named "xml.py" and is in the current folder!! what > am i doing wrong??? > > i dont see why it is so hard. it's just that ive fallen in a small hole > (idom).. just one of those things when you learn a new language... i just > need a little help. im sure someone knows :( > > ive thought of using exec, but this way is far more elegant.. so i've read. > but not proven. > > Please HELP! > Cheers > Trung Hoang > Final year Undergraduate of Computer Science and Technology > University of Sydney, Australia. > > From holger at trillke.net Mon Mar 25 06:18:37 2002 From: holger at trillke.net (holger at trillke.net) Date: Mon, 25 Mar 2002 12:18:37 +0100 Subject: Stopping threads from the outside In-Reply-To: <3C9E7326.C3FD53DF@engcorp.com>; from peter@engcorp.com on Sun, Mar 24, 2002 at 07:45:26PM -0500 References: <3C9E173A.88BBDBB4@engcorp.com> <3C9E53D8.4FA20F3D@engcorp.com> <3C9E7326.C3FD53DF@engcorp.com> Message-ID: <20020325121837.J12768@prim.han.de> > Your "agents" sound a lot more like they are just threads, > but maybe I don't see the distinction. From the above > description, I think you'll have other problems on your hands > than just terminating the threads. You've got what appears > to be a very highly coupled system (...) In this case, yes. The point is that my agents don't need to behave to any framework. The only change in programming paradigms should be that you have to really think your Classes/Objects as "self-responsible". They can use the protocol of their choice (i provide a very simple one) to transfer themselves to other systems. Or someone else transfers them with a specific protocol. The Agent "servers" don't do much on themselves but instead leave it to agents to provide "framework" and protocol capabilities. So to decouple the agents i would probably introduce a "RelationShip"-Agent managing couplings between them. In the mentioned case the agents work as threads because that makes sense for their task. There are also some "passive" agents which don't "live" on their own (thread). For example the "Config-Agent" or the "scanning directories" agent :-) These are quite similar to "modules". > The approach I suggested in my other reply would still work > nicely if you can ensure the threads call through an intermediary > instead of directly into each other. You might also try > a low-performance hack until you have time to implement the > modification in the interpreter :-), which would be to > stick a flag check into a routine inserted with sys.settrace(). > Have that routine raise the exception if the flag is set for > the current thread... interesting suggestion! Doesn't this cause a lot of overhead unless done in C? (checking for thread_id and if there is a flag set for it for each python-instruction) thanks again, holger From emile at fenx.com Tue Mar 5 21:53:29 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 5 Mar 2002 18:53:29 -0800 Subject: Nested scopes: design or implementation? References: Message-ID: "logistix" wrote in message news:vcfh8.405$tL.70 at nwrddc02.gnilink.net... > Is the following code operating this way by design or is it just > implementation? It seems to indicate that the nested function is redefined > each time the parent function is called. Is this necessary or desirable? > It is both. In particular, if the outer function builds and returns a curried function, you likely want it redefined each time the outer function is called. -- Emile van Sebille emile at fenx.com --------- From gerhard at bigfoot.de Thu Mar 21 22:55:08 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 22 Mar 2002 03:55:08 GMT Subject: How Can I Determine the Operating System with Python? References: Message-ID: In article , hdiwan420 at speakeasy.net wrote: > ingo writes: >> >>> os.environ['OS'] >>'Windows_NT' > If you have nmap or queso installed, you can always do: > % sudo nmap -v -v -v -sS -O localhost > or > % sudo queso localhost I take it that wasn't meant seriously. > Ok, so it's not exact, but it's just as good as any other way and both exist > on Windows and Unix. The probability of queso or nmap, let alone sudo being installed on Windows is probably of about the same order of magnitued as that the newsreader I'm currently using on win32 (slrn) is installed there. And nmap isn't a standard Unix tool either. On Unix, the only thing you can depend on is the presence of "uname", which exactly the right tool for the task. Only I don't know of an "uname" equivalent for Windows or Mac. Besides, "nmap -O" (I take it queso is just an alias for that), gives this on my FreeBSD 4.5-STABLE: ... No exact OS matches for host (If you know what OS is running on it, see http://www.insecure.org/cgi-bin/nmap-submit.cgi). ... which I of course did. Gerhard From jgardn at alumni.washington.edu Wed Mar 13 20:17:48 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Thu, 14 Mar 2002 10:17:48 +0900 Subject: [OT] Making the move (to Linux/*BSD/real OS) References: Message-ID: Sandy Norton wrote: > Jonathan Gardner wrote >> If you want to customize your mail client, you're using the wrong OS. All >> the customizability is over here in Linux, with procmail and sendmail and >> fetchmail and all sorts of great stuff that you've never even dreamed of >> - even in those really wild dreams where you use your computer for a >> month and it doesn't crash once. > > Your point is well taken. Actually, I've had the move in mind for some > time, and am hoping to ease the transition by getting used to the > cygwin environment, and using cross platform tools as often as I can. > However, I don't think I'm quite ready yet, and if I do make the move > I don't know whether it will be to linux or to Mac OS X. > There was a challenge posted by a journalist (not a programmer) who uses Linux quite readily for all his journalistic needs. He said something like "Try it out for 2 weeks, and by the end of the 2 weeks, you won't be able to go back." After all, it is habits you are going to change, and those habits have to be broken the hard way. I don't suggest Mac OSX because it is still not really in-your-face unix. Cygwin is great, but it is mostly a crutch for those who already use Unix systems, but are forced to work on a windows box. You won't really be exposed to the power of Unix until you learn all the simple commands that you normally do with Explorer and other tools. I wish you luck in the switch. I switched by wiping windows from my home computer and trying to get Red Hat installed. It wasn't pretty, and I didn't have a LUG to help me out. But thanks to Linuxdoc and google, I got thing working. Eventually, I felt so restricted in windows at work, that I convinced my boss to get me another box to put Linux on. It only cost a couple of hundred dollars, and since we were using Linux for our servers, it really made me much more productive. BTW, the bane of non-MS users is the doc format. It drives me nuts that people think it is portable. That and newer Adobe PDF files. And HTML mail. Oh well... =( Jonathan From mkingston at -at-shaw.ca Thu Mar 7 01:49:13 2002 From: mkingston at -at-shaw.ca (Mark Kingston) Date: Thu, 07 Mar 2002 06:49:13 GMT Subject: Python on W2K server and dos batch files? References: <3c866f0c$1_2@axion.net> <899f842.0203062032.75b219a7@posting.google.com> Message-ID: Thanks Anthony. I downloaded the ActiveState and it has very good documentation. Can you please tell me what TK is? I would definitely like to rewrite those dos batch files in Python. Also, yes, please send me some sample scripts as I have only programmed in Object Pascal and VB. Python seems more C like but I like what I've seen so far. Thanks again. -- Mark. mkingston at -at-shaw.ca Please remove '-at-' from email if replying directly to me. "Anthony_Barker" wrote in message news:899f842.0203062032.75b219a7 at posting.google.com... > "Mark Kingston" wrote in message news:<3c866f0c$1_2 at axion.net>... > > Hello Experts, > > > > I've been looking into the possibility of using Python as a scripting > > language for use on our Windows 2000 Server with Terminal Services and > > Citrix Metaframe XPa. The reason I'm looking into a scripting language > > instead of a compiled program is that I need to add new functionality to the > > programs often. The scripting program will also serve as a "launch pad" for > > other DOS batch files and compiled console applications. > > Works fine - I wrote some scripts to monitoring some servers at a > Canadian Bank.I recommend the ActiveState distro as you will be using > windows, I found it includes more 'extras'... Also checkout their > website for some sample scripts. > > > > 1. Create a GUI (wxPython?) which will be used for server administration > > purposes such as automatically displaying a list of NT users on a form and > > allowing the user to select which user to enable or disable. > TK may be better for a quick gui. You can access the NT directory via > COM or do LDAP lookups. > > > 2. Create a GUI which will allow a user to launch other scripts such as DOS > > batch files, Windows programs and console programs. > > No problem... But you may end up wanting to rewrite the batch files in > python as it is more flexible. I can send you some example scripts if > need be. Use windows 'Pipes'. > > > > 3. The GUI should also be able to capture the output of console programs and > > display it on it's own text box or panel. > fine > > > 4. Perform advanced text file manipulation. > Excellent From daniel.dittmar at sap.com Wed Mar 13 11:17:51 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 13 Mar 2002 17:17:51 +0100 Subject: Why I think range is a wart. References: Message-ID: > for index in range(len(mylist)): > several solutions: # if whatever contains only refs to mylist [index] for element in mylist: # if you really need the index def listIndices (list): return range (len (list)) for index in listIndices (mylist): # my favourite class IndexAndElement: def __init__ (self, list): self.list = list def __getitem__ (self, index): return (index, self.list [index]) for index, element in IndexAndElement (mylist): There's more than one way to heal a wart. Daniel From geoff at gerrietts.net Sun Mar 10 18:07:01 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Sun, 10 Mar 2002 15:07:01 -0800 Subject: Modulo operator : differences between C and Python In-Reply-To: <3C8BE537.74E55963@mega-nerd.com> References: <3C8BE537.74E55963@mega-nerd.com> Message-ID: <20020310230701.GM8360@isis.gerrietts.net> Quoting Erik de Castro Lopo (nospam at mega-nerd.com): > Just recently I prototyped a relatively complex algorithm in Python > before converting it to C. During this conversion I noticed that > the modulo operator returns different results in C and Python if > the numerator is negative. For positive values they produce the same > result. I ran into this very same thing the other day. I was setting my expectations of how a C expression would evaluate by testing it in the python shell, only to discover that it evaluated quite differently. I don't think it bothered me. Just surprised me. Turns out what I really wanted was the Python answer anyway. I'm not sure the answer I got in C is actually the modulo, if I understand the mathematical concept "modulo" properly. -- Geoff Gerrietts "I am always doing that which I can not do, in order that I may learn how to do it." http://www.gerrietts.net --Pablo Picasso From p.magwene at snet.net Sun Mar 24 09:11:19 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sun, 24 Mar 2002 14:11:19 GMT Subject: Need help with plotting References: <3c9cd61e.8124286@news> Message-ID: On Sat, 23 Mar 2002 14:24:32 -0500, brobbins333 wrote: > I'm new to Python and doing pretty well with it so far. One thing that > has me stumped is finding an "easy" way, or any way, for that matter, to > plot simple graphs. I haven't gotten into Tkinter yet and I'm not sure > if there is another way to make plots. I have scipy and Numeric and I > can see that there are graphing modules there but I have not been able > to access them with something like: from scipy import *. This always > fails with "not there" or "can't import." > > I've tried to do my homework on this but can't find anything that works > for me. Can anybody point me in the right direction? > > Thanks, > Bruce Robbins Depending on your needs you might want to try disipyl - a Python interface to the DISLIN plotting library, available here: http://pantheon.yale.edu/~pmm34/disipyl.html Cheers, Paul From kragen at pobox.com Mon Mar 25 04:36:26 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 25 Mar 2002 04:36:26 -0500 Subject: using os.execl to call a java application References: <3C9D66E9.4070802@northwestern.edu> Message-ID: <83663l56qt.fsf@panacea.canonical.org> Louis Luangkesorn writes: > File "C:\docs\gmcode\prob4.py", line 74, in findrqsim > os.path('c:\\docs\\ibmmodelswitch') > TypeError: object of type 'module' is not callable os.path is a module. I think you meant os.chdir, not os.path. You should consider writing your paths as 'c:/docs/ibmmodelswitch' so you don't have to double backslash. From amuys at shortech.com.au Sun Mar 3 20:56:49 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 3 Mar 2002 17:56:49 -0800 Subject: Stedents Question References: <3c80126f_1@news.iprimus.com.au> <3c811073@nntp.server.uni-frankfurt.de> Message-ID: <7934d084.0203031756.4a11d7b2@posting.google.com> Michael Janssen wrote in message news:<3c811073 at nntp.server.uni-frankfurt.de>... > Tony K wrote: > > > The question below is a tutorial question that stumps me. Any suggestions > > would be appreciated. > > Tony > > > > Write a Python function findABBC which takes a single string as parameter > > and returns all substrings thereof which match the regexp pattern ab+c. > > You are NOT allowed to use the re module. > > def findABBC(str): > a=0 > b=0 > while str: > for n in str: > if n=="a": > a=1 > break > if a==1 and n=="b": > b=b+1 > break > if a==1 and n=="c": > print "a"+"b"*b+"c" > a, b = 0, 0 > break > if n!=[a-c]: > a, b = 0, 0 > break > str=str[1:] > > produces every ab+c-string in str. But there must be something easier. > Something smaller ;-) > Probably, but given that this is someones homework we probably shouldn't discuss this until next week (presumably after the tutorial's due). Andrae From martinkaufmann at yahoo.com Tue Mar 12 17:13:40 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Wed, 13 Mar 2002 11:13:40 +1300 Subject: Question about scientific calculations in Python References: Message-ID: On Tue, 12 Mar 2002 12:32:03 GMT, Michael Hudson wrote: >Martin Kaufmann writes: > >> Now my questions: Would it be best to >> >> (a) write the whole program in C/C++ (I know only the basics of C but >> it would be a good "excuse" to learn it...)? > >Well, you're unlikely to get advised to do this here :) You're probably right... Is there a group about general scientific programming where I could get an unbiased answer? :-) >> (b) write the main program in Python but the heavy calculations in C >> (I played today with scipy.weave -- the speed is much better but I >> didn't really understand what I was doing...)? > >This is probably the better option, but first... > >> (c) program it in Python and don't care about speed (or buy a new >> workstation...)? > >... I'd do this. Write your algorithm in Python. Run it on small >examples to test. See if it's fast enough to run your real problems. >If it's not, go for (b). It may be possible that modules already >exist to do the heavy lifting -- e.g. Numeric. It's hard to say for >certain without knowing more about your algorithms. OK, I post a code snippet here. Comments are welcome -- there is certainly a better solution. If somebody wants to see the whole code, I can put it on a webpage. This is the first raw version without histograms. s_vector is an array with all the scattering parameters, f_s_vector the respective scattering factors, and r_vector an array with all the distances between the atoms. The equation is the Debye equation, so no fancy integrals... for s in s_vector[1:]: sum = 0 for r in r_vector[1:]: x = 2 * pi * r * s sum = sum + (2 * (sin(x))/x) intensity = atoms * pow(f_s_vector[n], 2) * (1 + sum / atoms) i_vector.append(intensity) n = n + 1 Now the histogram code where the radii are binned in the histogram hist and only the bins with a value are used: for s in s_vector[1:]: sum = 0 for entry in hist[1:]: if entry[1] == 0: continue x = 2 * pi * s * entry[0] sum = sum + (2 * entry[1] * (sin(x) / x)) intensity = atoms * pow(f_s_vector[n], 2) * (1 + sum / atoms) i_vector.append(intensity) n = n + 1 The main difference here is that in the second solution I don't have to calculate the sin term for every radius. >Things like weave and PyInline may help. Do you know a tutorial about weave or SWIG that is understandable without much C knowledge? >Maybe you could submit better code to the SciPy project? Maybe I'm not exactly the right person... But I read last autumn a long discussion about the merging of all the scientific libraries (the Grand Unified Scientific Library GUSL...). What about the implementation? Many Thanks, Martin From philh at comuno.freeserve.co.uk Wed Mar 27 08:21:53 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Wed, 27 Mar 2002 13:21:53 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: On Tue, 26 Mar 2002 20:23:44 +0000, Dale Strickland-Clark wrote: >"Dean Goodmanson" wrote: > >>"The joy of coding Python should be in seeing short, concise, readable >>classes that express a lot of action in a small amount of clear code -- not >>in reams of trivial code that bores the reader to death." Guido van Rossum >> > >I didn't see the original post but I *really* hope this was said in >jest. I would very much hope not. And Guido's statement supports my suggestion that pass be made optional in Python. Consider, when someone is designing a class, one could write an outline like this: class BaseClass: class MyClass(BaseClass): def __init__(self): def method1(self, a, b, c): def method2(self, d, e): def method3(self, f): It is perfectly clear what this means. But unfortunately, as Python stands today, it is syntactically invalid, one would have to say: class BaseClass: pass class MyClass(BaseClass): def __init__(self): pass def method1(self, a, b, c): pass def method2(self, d, e): pass def method3(self, f): pass And then, when you begin to flesh out your code, you would have to get rid of the extraneous passes you didn't want to add (assuming you are like me) in the first place. So the with-pass version requires more effort, and is more verbose, for no good reason. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From JeffH at ActiveState.com Mon Mar 25 18:20:20 2002 From: JeffH at ActiveState.com (Jeff Hobbs) Date: Mon, 25 Mar 2002 15:20:20 -0800 Subject: Replacing excel: but with what ? References: <3C9CCF6C.F1099089@vip.fi> <3C9CF7A6.51F112EC@olen.to> Message-ID: <3C9FB0B4.9B20C638@ActiveState.com> Cliff Wells wrote: > > On Sat, 23 Mar 2002 23:46:14 +0200 > Joonas Paalasmaa wrote: > > > Does Tkinter meet your needs? You can create a spreadsheet by griddinng > > Entry widgets. There is an example in Lutz's Programming Python 2'nd > > Edition, if you happen to owe it. > > Doing this was exactly what moved me to wxPython a couple of years ago. > This approach will work, but it will be extremely slow for even a > moderately large spreadsheet. I even tried writing a spreadsheet widget > from scratch using Tkinter and although it was much faster, it was still > too slow (unfortunately I no longer have the code or I'd send it to you > =P). Something like this needs be written in a compiled language. Missed the original post on this (shi!!y news server), but if you are looking for a robust spreadsheet-like widget for Tkinter, you should look at tktable: http://tktable.sourceforge.net/ It provides all sorts of fancy features, and definitely handles 100,000+ elements without sweating (I've run tests with 500,000 elements - it's coded as a C widget extension to Tk). It's not a "spreadsheet" per se, but it does provide the basis for one. It is written just as a Tcl/Tk extension though. I got mail once from someone that had used it with Tkinter, but I can't find that now. From what I understand of Tkinter, it should be pretty easy to use as it just loads dynamically into Tk. IOW, I don't know what the "out-of-box" experience would be for a Tkinter user, but it is the table widget of choice for Tk. Tix is a set of widgets for Tk that does have a proper Tkinter port, and also provides a "tixGrid" widget. It doesn't have the features of tktable, but if you are doing mostly read-only stuff, it may suffice. -- Jeff Hobbs The Tcl Guy Senior Developer http://www.ActiveState.com/ From gerhard at bigfoot.de Mon Mar 25 07:38:44 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 25 Mar 2002 12:38:44 GMT Subject: [albatross-users] Re: Python embedded like PHP References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> <1016822750.495.34.camel@localhost> Message-ID: In article , Duncan Booth wrote: > Microsoft Frontpage Ayee!! > It would be nice though if the HTML editor could somehow be told to make the > rest of the template readonly. Dreamweaver can do that. Gerhard From pedronis at bluewin.ch Tue Mar 5 15:04:44 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Tue, 5 Mar 2002 21:04:44 +0100 Subject: Status of PEP's? References: <3C844811.AEC974E3@cosc.canterbury.ac.nz> Message-ID: <3c8527d4$1_1@news.bluewin.ch> Just another contradictory *datapoint* (I have personally lost the illusion to be able to tell what is newbie friendly or not, without field-experimentation) Everything is an object is as much a CS abstraction as functional programming is a mixed CS/mathematics abstraction. It is not totally clear to me whether when they are pushed to the extreme they are friendly. Are they? Smalltalk try to deal with such corners compesating vaguely mimicking english: 1 to: 20 do: [...]. 10 timesRepeat: [...]. These forms in some sense (my very personal impression) try to hide that 1 is an object here, not to underline that. What about "for i in 10" from this angle of view ? regards, Samuele Pedroni. From imcmeans at home.com Sun Mar 17 00:46:11 2002 From: imcmeans at home.com (Ian McMeans) Date: Sun, 17 Mar 2002 05:46:11 GMT Subject: mixing regular expression Message-ID: How should go I about nesting regular expressions in python? I want one huge regular expression to be composed of a bunch of others - is there some way I can include a regular expression inside another? Or should I do it with strings - just save each regular expression's string, and then compile each combination separately? What I mean is this: foo = re.compile("someregexcode") bar = re.compile("moreregexcode") big = re.compile("foo|bar") is that possible at all? To combine regular expression objects? Or do you suggest that I just make strings for foo and bar, and then compile the combined strings into big? From pearu at cens.ioc.ee Tue Mar 26 15:50:14 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Tue, 26 Mar 2002 22:50:14 +0200 Subject: Most efficient unzip - inverse of zip? Message-ID: Hi, What would be the most efficient way to unzip zipped sequences in Python 2.2? For example, consider a_b = zip(a,b) # where a and b are some sequences a_b.sort() a,b = unzip(a_b) For a start, I have def unzip(seq): ns = range(len(seq[0])) r = [[] for i in ns] [r[i].append(s[i]) for i in ns for s in seq] return tuple(r) Is there any better algorithm for unzip? Regards, Pearu From grey at despair.dmiyu.org Mon Mar 4 19:30:16 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Tue, 05 Mar 2002 00:30:16 -0000 Subject: Reorganizing python.org (was: Why isn't pychecker...) References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> <3C841006.634D0059@tds.net> Message-ID: On Tue, 05 Mar 2002 00:23:37 GMT, Edward K. Ream wrote: > I find this error all over the web: we try to cram too much onto a > single page, You mean like the old ICQ main page? *shudder* > Another example, the otherwise superb intro to Tkinter, > http://www.pythonware.com/library/tkinter/introduction/index.htm > would be vastly more useful if it fit on a single page. Define "page". If you say 800x600 you'd lose. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From tchur at optushome.com.au Tue Mar 12 04:39:40 2002 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 12 Mar 2002 20:39:40 +1100 Subject: Has Mark Hammond attained pariah status yet? Message-ID: <3C8DCCDC.328D0DD0@optushome.com.au> So asks an article on Mark in the IT section of today's Sydney Morning Herald - see http://www.it.mycareer.com.au/news/2002/03/12/FFXMFP3LOYC.html Personally I think that integrating Python into .NET is really important. But try as I might, I just can't get too enthusiastic about anything controlled by Microsoft, no matter how cool it is. I think a photo which appeared in a recent issue of Scientific American sums it up - see http://www.sciam.com/2002/0102issue/010250100.html Tim C Sydney, Australia From mertz at gnosis.cx Fri Mar 8 19:11:25 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Fri, 08 Mar 2002 19:11:25 -0500 Subject: PEP 284, Integer for-loops References: <3C87680D.CC8A546C@engcorp.com> Message-ID: Roy Smith wrote previously: |I just took a look at some random collection of python code I've got laying |around, totaling 6100 lines. I've got 85 for loops, 12 of which use range, |the other 73 don't. What's even more interesting is that of the 12 ranges, |11 of them are in a single file; the only file of the collection which I |didn't write (and which I consider pretty ugly code). I decided to do the same test (more or less). A current snapshot of my "Gnosis XML Utilities" has 3100 lines (written largely by me, with various contributors). There are *4* uses of [x]range() in 'for' loops. One is a test case that just uses 'range(500)' to do something "a bunch of times". One of the remaining three is 'range(1,len(fields),2)', which doesn't lend itself easily to the integer-iterator proposal. There are *two* occurrences of 'range(len(member))', which I agree are slightly awkward to write and read. There are actually more uses of the range() function to indicate ranges of ASCII values than in the loop context, in this particular lump of code. From mickey at tm.informatik.uni-frankfurt.de Sun Mar 24 19:32:36 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 25 Mar 2002 02:32:36 +0200 Subject: 2.2.1c1 platform experiences References: <3c9e2442@nntp.server.uni-frankfurt.de> Message-ID: <3c9e7e33@nntp.server.uni-frankfurt.de> Skip Montanaro wrote: > > >> I've attempted to summarise the reports of people using 2.2.1c1 on > >> various platforms here: > > Mickey> Speaking of foreign or unusual platforms... does anyone have a > Mickey> reliable build-script for building python on arm-linux ? > > No, but if "./configure ; make && make test" doesn't work for you, it would > be helpful if you file a bug report at SF identifying what didn't work. Ahh sorry, of course it builds fine _on_ arm-linux, I wanted to request a build-script for building python _for_ arm-linux - that is cross-compiling. Yours, :M: From sholden at holdenweb.com Wed Mar 27 15:55:11 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 27 Mar 2002 15:55:11 -0500 Subject: new to python... References: Message-ID: "wilby31" wrote in message news:mailman.1017259391.21846.python-list at python.org... > Im running Linux and I would like to run a filename.py file..how do I > go about running this program? through the command line ? I have > version 1.5.2 and I do not have the control to upgrade it. thanks > Either: 1: python filename.py arg1 arg2 ... or 2: make sure your Python file begins with #!/usr/bin.env python then % chmod +x filename.py % filename.py arg1 arg2 ... regards Steve From mwh at python.net Thu Mar 14 06:20:27 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Mar 2002 11:20:27 GMT Subject: zlib vulnerabilities and python References: Message-ID: Tim Peters writes: > [Michael Hudson] > > But because mail from the sf tracker seems to be hitting the bit > > bucket, noone knows about this. sf support believe this is now fixed, btw. -- But since I'm not trying to impress anybody in The Software Big Top, I'd rather walk the wire using a big pole, a safety harness, a net, and with the wire not more than 3 feet off the ground. -- Grant Griffin, comp.lang.python From max at alcyone.com Sun Mar 31 14:04:12 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 31 Mar 2002 11:04:12 -0800 Subject: PEP 285: Adding a bool type References: Message-ID: <3CA75DAC.17647CEA@alcyone.com> Ralph Corderoy wrote: > Terry Reedy wrote: > > > C. Anyone learning Python has some idea of truth and truth values. > > But I am sure there are some with no idea of what 'bool' means and > > only a vague idea about 'Boolean'. Better formalizing Python truth > > values should make them even easier to learn; why not call them what > > they are? > > That's an excellent point, as are the others you make. My Mum would > understand true but not bool or Boolean. I'm not really sure how beneficial this would be. In the real world, not everything about a programming language -- even a low-overhead language like Python -- can be instantly intuited by non-programmers. After some elementary level they're going to have to start reading. That bool (or boolean) is a Boolean type is not a hard concept to get across, and I don't see how calling it "truth" is really all that much more helpful. It's far better, in my opinion, to give it a standard name from computer science (bool or boolean) and let new programmers take the tiny little steps (in this case) to add a new word to their vocabulary -- a word that will help them in future explorations of programming and computer science, no less. Excessive attempts to make terms more approachable can lead to disaster in the degenerate case, resulting in just a new form of terminology that now nobody understands. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From just at xs4all.nl Sun Mar 17 04:56:33 2002 From: just at xs4all.nl (Just van Rossum) Date: Sun, 17 Mar 2002 10:56:33 +0100 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: In article , danb_83 at yahoo.com (Dan Bishop) wrote: > Even for complex numbers, for which "less than or greater than" is > meaningless? It doesn't have that meaning for me anymore, it simple means "not equal" to me. It is an abstract symbol. I really don't believe we can discuss this on any other level than "I prefer x because I'm used to it", which seems a little, erm, pointless... Just From nhodgson at bigpond.net.au Mon Mar 11 17:51:14 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Mon, 11 Mar 2002 22:51:14 GMT Subject: Is Python an object based programming langauge? References: Message-ID: Graz Bukanoff: > Is Python an object based programming langauge? Python is most often described as an object-oriented language. Some people use the term 'object-based' to refer to languages that can use objects but can not define new objects. Examples are HyperTalk and some versions of Visual Basic. Neil From aahz at pythoncraft.com Tue Mar 26 16:51:55 2002 From: aahz at pythoncraft.com (Aahz) Date: 26 Mar 2002 16:51:55 -0500 Subject: The Python Way References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> Message-ID: In article , Dale Strickland-Clark wrote: >"Dean Goodmanson" wrote: >> >>"The joy of coding Python should be in seeing short, concise, readable >>classes that express a lot of action in a small amount of clear code -- not >>in reams of trivial code that bores the reader to death." Guido van Rossum > >I didn't see the original post but I *really* hope this was said in >jest. > >Or is Guido getting writing software and writing novels confused? Not in the slightest. Guido was responding to constructs like this: lock.acquire() try: code code code code code code code code code code code code finally: lock.release() In any large application, it gets *tiresome* to see this, particularly if you add another layer of nested try/except. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From paul at boddie.net Wed Mar 6 14:00:49 2002 From: paul at boddie.net (Paul Boddie) Date: 6 Mar 2002 11:00:49 -0800 Subject: [ANN] istring 1.0.1 released; announce list created References: <3C86047F.1080601@stroeder.com> Message-ID: <23891c90.0203061100.654426ee@posting.google.com> Gerhard H?ring wrote in message news:... > > There's a reason for cursor.execute(query_string, parameters) being in > the DB-API. Only the DB module can know how to put the parameters > there correctly with quoting and all. Well, that remark should, in a just world, kill the almost inevitable thread about adding SQL quoting to some part of the standard library. Unfortunately, dubious SQL practices will probably persist until SQL is just a memory. Paul From chris.gonnerman at newcenturycomputers.net Sun Mar 3 02:04:28 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 3 Mar 2002 01:04:28 -0600 Subject: Can somebody kill getpathp for me? References: <3C81C613.8000409@skippinet.com.au> Message-ID: <009f01c1c281$b19cd660$0101010a@local> ----- Original Message ----- From: "Mark Hammond" > Tim Peters wrote: > > [Chris Gonnerman] > > >>What I want is a version of either python.exe or python21.dll > >>(whichever contains the offending getpathp.c module) with the > >>registry-probing code disabled. > >> > > > > If that's what you really want, you'll have to edit getpathp.c and compile > > your own Python. > > Or, use MSVC or some other resource editor to change the single string > resource in the compiled Pythonxx.DLL (ie, no need to rebuild the DLL). > This will cause a different registry key to be used (by the core, and > also by extensions that are registry aware). If I had MSVC I'd build from source. I work in a mixed Linux/Windows environment, and use Python for just about everything. My days as a C programmer are probably mostly in the past. Wonder if I can find some other resource editing tool... time to STFW. From peter at engcorp.com Sun Mar 10 19:34:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 10 Mar 2002 19:34:36 -0500 Subject: range Failure? References: <3C8B84B6.DB3F8E9A@sympatico.ca> Message-ID: <3C8BFB9C.1EF90FAB@engcorp.com> Bengt Richter wrote: > > On Sun, 10 Mar 2002 11:07:18 -0500, "Colin J. Williams" wrote: > [...] > >It might say: > > > > range([start= 0,] stop[, step= 1]) > > Still, the two optional []'s are not valid in all combinations, > (which is what you fix with your improved text ;-) > so maybe it should say something like: > > range([start= 0,] stop) # where step defaults to 1, or > range(start, stop [, step= 1]) Why not be very explicit, rather than fancy and confusing? The above is an improvement over the original, but perhaps this is better? range(stop) # start is 0, step is 1 range(start, stop [, step=1]) Answering my own question: the first of the three is pretty bad. The second one suffers from implying that Python can have optional positional arguments which come before non-optional ones. The third suffers from implying (perhaps?) that Python can have overloaded methods. Since range() doesn't take keyword arguments, even my second one above could be considered a little bit confusing, if you think that implies you can say range(1, 6, step=2) which you cannot. -Peter From Ken.Peek at Engineer.com Fri Mar 29 17:35:25 2002 From: Ken.Peek at Engineer.com (Ken Peek) Date: 29 Mar 2002 14:35:25 -0800 Subject: Another stab at a "switch/case" construct (new proposal): References: Message-ID: [Steve Holden]: "Your example uses only constant (literal) values. This obviously makes it possible to guarantee that the tuples do not overlap at compile time, but is very restrictive. Was this intentional..."? [Ken Peek]: No-- that was not my intent at all. Dynamic objects could be used as well, with the compiler optimizing the 'literal only' cases. [Steve Holden]: "You will find there is considerable resistance to adding new keywords, due to their propensity to break existing code (for example, I have some programs that use match as a variable name, and the re module uses it as the name of a method)." [Ken Peek]: As to the considerable resistance-- I think that is a good thing, but no reason to never discuss language enhancements. Who knows? Maybe some day, someone will come up with a really good enhancement to Python that has a huge upside, and very little downside. You note about the 'match' keyword is well taken. [Dale Strickland-Clark]: "You *have* to allow variables in the match list, however, plus objects that evaluate to a suitable value or sequence of values. There's no reason why the compiler couldn't detect and optimize the case where only constants are used." ... "I prefer 'else' to 'any' - a lot. I makes more sense and doesn't need a new keyword." [Jeff Shannon]: "I think that if we're going to add a keyword for this, that "switch" is a good choice. It's familiar to C/C++ programmers (at least), it's reasonably intuitive, and it avoids capitalization monstrosities. ;) It does risk breaking old code, of course, but then, *any* keyword change does that." "I do prefer the re-use of "else" instead of adding "any", though. A lot." "I don't think I like this re-use of the 'continue' keyword -- it seems to me that the sense, in this context, is considerably different than the sense of its use in a loop. In a loop, it means 'start over from the top', where here, it means 'run this one next bit too, but not anything else'." "I'm not sure that falling through is a necessary idiom to accommodate...." [Ken Peek]: Yes-- a keyword to fall through a matched case body to the next is ESSENTIAL to efficiency and readability. Also, this fall through capability is one of the most powerful aspects of the switch/case construct. [damien morton]: "You could go a lot further with this case statement. First thing is to allow for variable length list unpack..." [Ken Peek]: Interesting idea. I don't think I'm smart enough to use that level of complexity though... [Bengt Richter]: "case: Don't like it. We already have means to do what a case does and do it more elegantly. It would add a needless redundant portion to the language." [Ken Peek]: Thanks for your opinion! Well, I think the most important thing about Python is that it encourages a programmer to write code that is both readable and maintainable. I think I said in my post that you COULD do the same thing with if/elif/else clauses, but that this construct is more readable. Python is not about minimizing the number of keywords or keystrokes-- it is about READABILITY and MAINTAINABILITY. I think a switch/case type of construct would go a long way towards this goal. [Laura Creighton]: "I don't like the overloading of continue. I'd go for a new keyword, fallsthrough myself." [Ken Peek] (see new proposal below) ================================== [switch/case keyword selection]: Many people have expressed that they don't like the use of the keyword 'match', and others have also taken issue of my overloading the of the keyword 'continue', so I have thought of some alternatives: ['match']: search, find, seek, branch, branchon, switch, switchon, pick, choose, select, multibranch ['continue']: fall, fallthrough, sink, descend, proceed After hearing the comments of the folks on this news group, I now think that the use of tuples in this construct was a big mistake-- I should have proposed the use of lists instead. Below is a "new improved version" of the 'switch/case construct, along with my preference for the new keywords: ##### Another Example ##### from __future__ import multibranching MyObject = Something # The "==" test will be used to determine if a match occurred. # The type, size, number of elements, keys (if any) and values # of the object being compared must all match exactly for a # clause to be declared as equal. The lists of the clauses are # examined recursively. If "MyObject" is itself a list, then # the first matching list terminates the recursive examination # of the values in the clauses. The values in the clauses are # examined exactly in the order as written (top to bottom, # left to right), and the first matching value terminates the # examination, causing the matching clauses body to be # executed. If the last statement in a clause body is a # "fallthrough", then the body of statements in the following # clause are also executed: branchon MyObject: [Object_1, Object_N, (99,98,MyVar), 42]: # do something # do more fallthrough # (fall through to next clause body) [[1,2,3], "hello", MyDynamicObject, MyList]: # do something # do more []: # this matches if "MyObject" is an empty list # do something # do more else: # we did not have any matching clauses # do something # do more ================================== OK-- please send in the next barrage of critisism... From jjb5 at cornell.edu Fri Mar 22 00:28:16 2002 From: jjb5 at cornell.edu (Joel Bender) Date: Fri, 22 Mar 2002 00:28:16 -0500 Subject: Python2.2 Installation References: Message-ID: > make install > > ? > > -Andy Curiously, that seems to do more than "python2 setup.py install" that I did before. Thanks for your help, now I can dance the usual dance. Upon more investigation a comment such as "read the rest of the README, it's in there" would also have been appropriate. I stopped reading at the end of the "platform specific notes" just before "Configuring threads" figuring the rest of the document didn't apply. Joel From Gabe.Newcomb at noetix.com Mon Mar 11 21:12:15 2002 From: Gabe.Newcomb at noetix.com (Gabe Newcomb) Date: Mon, 11 Mar 2002 18:12:15 -0800 Subject: newbie-ish question on exec statement Message-ID: <0C7CA8D8DF75494EB09AB6016990107FF08312@NOXMAIL.noetixad.com> Hi all: I'd appreciate any comments people might have on the limitations of using exec. Specifically, what I want to do is build function names dynamically and call them (don't ask why). The function I'm using is one that accepts 3 arguments, the second and third of which have default values. The function returns a tuple of 2 values. I'm calling the function with only one argument, e.g., def my_function(arg1, arg2="", arg3=""): blah blah exec "t = my_" + "function('\\\\machine\\share')" I have a feeling that something unexpected (by me anyway) is happening with the string I'm trying to pass in as the arg to my_function()--this is based on the response I'm getting from my function. When I type the same text (t = my_" + "function('\\\\machine\\share')) into the interpreter directly, everything's fine. Is this perhaps only an issue with the interpreter, where I'm testing this? Thanks in advance, Gabe Newcomb From tejarex at yahoo.com Sat Mar 30 15:52:47 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 30 Mar 2002 20:52:47 GMT Subject: PEP 285: Adding a bool type References: Message-ID: "Guido van Rossum" wrote in message news:mailman.1017466974.6751.python-list at python.org... > I offer the following PEP for review by the community. If it receives > a favorable response, it will be implemented in Python 2.3. > 1) Should this PEP be accepted at all. +0.8 -- as long as it is not a first step in de-arithmetizing truth values. Proposed amendment: call the new type 'truth' instead of 'bool' and change the title of the PEP to "Formalizing a Python truth type". A. This PEP formalizes existing Python practice in regards to truth values. The 'new' type is not really new. The main visible effect is to change the display of the doubleton values. The existing magic method is __truth__(). Better to call the new type and constructor truth() than to change __truth__ () to __bool__(). B. 'bool' is an abbreviation of Boolean, the adjectival form of Boole, an English mathematician. I agree with the philosophical argument for nomenclature that is descriptive rather than 'nymic' (named after persons -- I forget the formal linguistic term for such). All other Python terms that I can think of (except for the name Python itself) follow this sensible principle. To me, naming one particular type after a person is somewhat jarring, especially when it is not necessary. C. Anyone learning Python has some idea of truth and truth values. But I am sure there are some with no idea of what 'bool' means and only a vague idea about 'Boolean'. Better formalizing Python truth values should make them even easier to learn; why not call them what they are? D. The word bool(ean) carries a lot of baggage in terms of expected behavior and *limitations* on behavior. At least half the debate on this PEP revolves around the fact that Python truth values act differently from 'proper' boolean values. The title of this PEP, "Adding a bool type", is arguably misleading since the newly formalized type will not be boolean as many understand the term. If we do not call Python truth values what they are not quite, or rather what they are more than, we avoid the mismatch between expectation and reality (and years of requests to change reality to match expectation). In other words, the critics are partly right; however, my solution is to drop the slightly misleading word bool (and its associated baggage) instead of changing current (and proposed) behavior (which I think is pretty good). > 2) Should str(True) return "True" or "1": "1" might reduce > backwards compatibility problems, but looks strange to me. > (repr(True) would always return "True".) I can see it either way. > 3) Should the constants be called 'True' and 'False' > (corresponding to None) or 'true' and 'false' (as in C++, Java > and C99). + 1 for True/False to corresponding to None, etc. Do true/false work *exactly* the same way in all three other languages? Will Python True/False be exactly the same? (I suspect not but simply do not know.) > True+1 == 2 must hold, else reams of existing code would break. yes, yes, yes. While this may not be 'proper' boolean behaviour, it is current Python truth value behaviour. > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that e.g. True+1 > would eventually (e.g. in Python 3000 be illegal). no, no, no. Eliminating useful polymorohic behavior is hardly Pythonic. If the new type were called 'truth' (as suggested above, or 'binary') instead of 'bool', this question would hardly arise. The behavior of Python truth values is, for the most part, a *superset* of some preconceived notions of allowed 'Boolean' operations. So what? This is true of any type which inherits methods from two base types (see below). > I think we shouldn't; 28+isleap(y) seems totally reasonable to me. Forcing this and all similar constructions to be written as '28+int(isleap(y))' gains nothing and goes against general Pythonic polymorphism. Why should one be able to add instances of arbitrary user-written classes to 28 but not instances of bool/truth? I understand OO purist objections, but Python is simply not an OO-purity language. Documentation makes no claim about what one 'ought' to be able to do with instances of derived classes versus instances of super-classes. > 5) Should operator.truth(x) return an int or a bool. Tim Peters > believes it should return an int because it's been documented > as such. I think it should return a bool; most other standard > predicates (e.g. issubtype()) have also been documented as > returning 0 or 1, and it's obvious that we want to change those > to return a bool. I think I would find it odd as new learner to have this one 'logical' function not return bool. > Note that subclassing from int means that True+1 is valid and > equals 2, and so on. This is important for backwards > compatibility: because comparisons and so on currently return > integer values, there's no way of telling what uses existing > applications make of these values. > Because of backwards compatibility, the bool type lacks many > properties that some would like to see. ?? Because of backwards compatibility, the bool (Python truth) type will have properties that I *want* to keep. > For example, arithmetic operations with one or two bool arguments > is allowed, treating False as 0 and True as 1. suitibility = has_a(x) + is_b(x) + does_c(x) Again, wrapping each term in int() in the service of pedantry does not strike me as Pythonic. Admittedly, I could define class mybool(int) (using the reference implementation given in PEP + whatever needed to make mixed expressions work) and have all predicates I write return mybool instead of bool(truth). But having to do seems worse that present situation. > Also, a bool may be used as a sequence index. (option_a, option_b)[binary_switch] # can be quite useful > I don't see this as a problem, and I don't want evolve the > language in this direction either; I don't believe that a stricter > interpretation of "Booleanness" makes the language any clearer. Completely agreed. Again, these issues seem to arise from calling Python truth values 'bool'. Conceptually, they inherit behavior from both int and bool (in the strict sense). > Another consequence of the compatibility requirement is that the > expression "True and 6" has the value 6, and similarly the > expression "False or None" has the value None. The "and" and "or" > operators are usefully defined to return the first argument that > determines the outcome, and this won't change; in particular, they > don't force the outcome to be a bool. Some languages use 'cand' and 'cor' to differentiate short-circuiting 'conditional' and/or from strictly logical and/or, but I am glad Python does not. In any case, Pythons and/or are Python truth value operators, not Boolean operators. About deriving bool from int: a couple of years ago, I followed a looooong thread on comp.object about the relationship of circles and ellipses and which should be derived from which. The problem for oo theory, it seems to me, is that specialization can take place either by addition -- a bird is a vertebrate that can fly -- or by subtraction -- a ratite is a bird that cannot fly. Evolution does not follow substitutivity rules. Neither do mathematicians and programmers. Terry J. Reedy From peter at engcorp.com Fri Mar 29 17:16:38 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 17:16:38 -0500 Subject: List problem References: Message-ID: <3CA4E7C6.EDE85B98@engcorp.com> Jon Cosby wrote: > > Can anyone se why this is coming up empty in the "cols" list? I've tried > something similar in the interpreter, and everything here looks right. For > some reason, it isn't finding any matches here. > > ######################################################################## > # WordSquare > # Build word squares from initial word > # > > # Word dictionary > dict = "c:\data\dict.txt" > > firstword = input("Enter first word (enclosed in quotes): ") > lword = len(firstword) > words = [] > cols = [] > rows = [] Comments might help a lot. For example, it's unclear what you are trying to accomplish here, but it doesn't look quite right: > f = open(dict, "r") > for line in f.readlines(): > if len(line[:-1]) == lword: > words.append(line[:-1]) > f.close() That finds the line matching lword and appends it to words, I think, which is another way of saying that every instance of lword in the dict.txt file will be appended to the words list. Strange... > for i in range(lword): > cols.append([]) > rows.append([]) > rows[0].append(firstword) For every character in lword, append an empty list to the rows and columns? If that's what you want, you need range(len(lword)) since range() takes an integer. Didn't you get an exception here? > # Generate an array of words with matching first letters > for i in range(lword): Same problem as above... use len() with range(). > for word in words: > if word[0] == firstword[i]: # Matches not found > cols[i].append(word) > > print len(words) > print cols Bad indentation here, but that's probably cosmetic. Try not to use tabs when posting source, since many newsreaders screw them up. Use spaces instead. Can you annotate your code so we know what you're trying to do? -Peter From j.bijsterbosch at hccnet.nl Mon Mar 18 04:35:46 2002 From: j.bijsterbosch at hccnet.nl (j.a. bijsterbosch) Date: Mon, 18 Mar 2002 10:35:46 +0100 Subject: Help Setting PATH w/Python and Win98 References: Message-ID: Hello Al, "Al" schreef in bericht news:b8245cf2.0203160920.2fe59c7b at posting.google.com... > Hi > > I am new to programming and am currently doing a Python Tutorial at > http://softwaredev.earthweb.com/sdopen/article/0,,12382_626311,00.html > > On that page it says I must set the path in Windows to the directory > where the Python.exe is located so that I can execute Python script. > I can get around DOS a bit to do this but not sure how to do it > exactly. Could someone tell me what I must do? Hmm, beiing a beginner with Python too, I had the same problem getting things organised after installation on the W98se platform. A look in the faq however did give a solution, overlooked in the accompagning tutorial. (at least I didn't find it) Create the following line in your autoexec.bat and reboot your system. SET PYTHONPATH=D:\Python21;D:\Python21\Lib;D:\Python21\Scripts Obviously you have to change some, to point to your used root directory/folder... Hope this helps...;-)) > Al -- Greetings from rainy Amsterdam Jan email: bijster at worldonline.nl http://home.worldonline.nl/~bijster From mhammond at skippinet.com.au Thu Mar 14 05:09:48 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 14 Mar 2002 10:09:48 GMT Subject: Has Mark Hammond attained pariah status yet? References: <3C8E7E90.6000608@skippinet.com.au> Message-ID: <3C907711.4030004@skippinet.com.au> Patrick wrote: > "Mark Hammond" wrote in message > news:3C8E7E90.6000608 at skippinet.com.au... > > >>[...] The book I am working on now is *not* Python for .NET, >>but just .NET. Python doesn't get much of a mention :( > > > Mark, out of curiosity: how did you conclude that the Python community is > not interested in .NET compatibility? Was it based on the lack of > contributions to your trial implementation? Or was it a perception that > Python *users* are not interested? I would describe it more as a healthy skeptisism towards .NET, but I see this starting to thaw slightly with the Open Source efforts. The Python community is not overflowing with Microsoft apologists or zealots ;) But if I combine this with the fact that new .NET beta releases often breaks the Python compiler but I have only received 2 complaints in a year, I concluded that interest is not yet high :) Don't forget .NET 1.0 has only recently been released into production - the "wait and see" attitude is quite prudent for many Python users. Mark. From bokr at oz.net Wed Mar 27 20:28:03 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Mar 2002 01:28:03 GMT Subject: instrumenting Python code References: <15521.50103.968819.131319@12-248-41-177.client.attbi.com> Message-ID: On Wed, 27 Mar 2002 09:49:18 -0600, Skip Montanaro wrote: > > Dave> The hotshot module doesn't appear to have any documentation > Dave> yet. > >That's true. Here's my simple usage scenario: > > import hotshot > profiler = hotshot.Profile("/home/skip/tmp/csv2csv.prof") > profiler.run("main()") > profiler.close() > stats = hotshot.Stats("/home/skip/tmp/csv2csv.prof") > stats.print_stats() > >-- Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import hotshot >>> hotshot.Stats Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Stats' What version/platform are you running? Regards, Bengt Richter From david.abrahams at rcn.com Sat Mar 30 11:11:29 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sat, 30 Mar 2002 11:11:29 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net><008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com><200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net><014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com><200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: <01b401c1d806$378aa100$0202a8c0@boostconsulting.com> ----- Original Message ----- From: "Andrew Koenig" > Liskov substitutibility would seem to suggest deriving int from bool, > not the other way around. That is: If I have a program that uses bool > values, I can change it so that it uses int values without affecting > the behavior of the program. The reverse is not true. Even that won't work, because of the different repr/str behavior... one reason I don't like the inheritance relationship. > I wonder if this is the circle-ellipse problem over again? square-rectangle-ly y'rs, dave From max at alcyone.com Sat Mar 30 17:18:54 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 30 Mar 2002 14:18:54 -0800 Subject: PEP 285: Adding a bool type References: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Message-ID: <3CA639CE.C3F2D7CB@alcyone.com> Paul Rubin wrote: > I don't see much need for it. There's no need to turn Python into > Java. > Python, C, and Lisp have all done fine without bools. What kinds of > programming tasks in Python are bools supposed to make easier? Comparing Python's lack of a Boolean type to C (which _does_ have one in the latest C99 Standard, so I'll presume you mean C89) and Lisp seems somewhat unfair, since their conceptions of what is true and false are much simpler than Python's. In C, any non-zero value (integral or floating point) or null pointer is true; in Lisp, any non-nil value is true. Lisp even has a special symbol for representing explicit truth: t. Python's non-bool concept of truth is much more complicated, as many things can be false: 0, 0.0, 0-as-rational (when and if that happens), empty strings, empty lists, empty tuples, empty dictionaries, and -- more importantly -- any class instance that implements the __nonzero__ method to return one of the above values. I'd say that C and Lisp lacking a Boolean type is in a different category of language design than Python lacking one. Truth testing is so simple in C and Lisp that you can get away with not having one pretty easily. I don't think that's the case for Python; Python's lack of a Boolean data type is one of the few things I think is truly missing. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From aahz at panix.com Wed Mar 6 20:37:35 2002 From: aahz at panix.com (Aahz Maruch) Date: 6 Mar 2002 17:37:35 -0800 Subject: [OSX] pthread problem References: <644f6688.0202061141.25ac2ef2@posting.google.com> Message-ID: [reposting this to see if it gets more response] In article <644f6688.0202061141.25ac2ef2 at posting.google.com>, rdack wrote: >osx 10.1.2, sendmail-8.12.2, milter-0.3.9, python2.1 > >when i try to run the sample.py milter i get: >dyld: python Undefined symbols: >_pthread_sigmask >_sigwait > >i see postings saying pthread support is built-in to osx, but they say >support for those two symbols is missing. it looks like python itself >is referencing those symbols. i don't those symbols referenced >anywhere in the module code. > >i don't think rebuilding with -lpthread will help. pthreads exist in >general, just not those two symbols. i don't know what to change to >get it to run. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From mcherm at destiny.com Mon Mar 11 10:26:27 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 11 Mar 2002 10:26:27 -0500 Subject: PEP 284, Integer for-loops (code bash?) Message-ID: <3C8CCCA3.6090200@destiny.com> > 1. Michael! Your Computer thinks its April! You are making > python archives one month ahead of yourself! > (see: http://mail.python.org/pipermail/python-list/2002-April/091714.html) Yipes! Thanks. Someone's idea of an april fools joke on me maybe? Anyway, thanks for point it out. > 2. Haskell, which I mispelt, shame on me, I know better, is a > functional language. I certainly know of the language and didn't even notice the misspelling. > It has functional syntax - don't go there looking > for a 'for loop'. However, it also has list comprehensions, (which is > where we got them from, I think). So, what I meant was 'I wish that > Guido had used Haskell's syntax for arithmetic sequences in Python's > for loops'. That is as follows: I figured you meant something like that. > [1..10] => [1,2,3,4,5,6,7,8,9,10] > [1,3..8] => [1,3,5,7] > [1,3..] => [1,3,5,7,9, ... (infinite sequence) Aha! Abundantly clear. > 3. Make the time to learn Haskell. It is simply too much fun. It's next on my list. Thanks! -- Michael Chermside From just at xs4all.nl Thu Mar 7 07:10:51 2002 From: just at xs4all.nl (Just van Rossum) Date: Thu, 07 Mar 2002 13:10:51 +0100 Subject: PEP 276 -- What else could iter(5) mean? References: <6qpu2gzktu.fsf@abnoba.intevation.de> Message-ID: In article <6qpu2gzktu.fsf at abnoba.intevation.de>, Bernhard Herzog wrote: > With iterable integers: > > >>> list(4) > [0, 1, 2, 3] > >>> tuple(4) > (0, 1, 2, 3) > >>> max(4) > 3 > >>> min(4) > 0 > >>> filter(None, 4) # also for map and reduce > [1, 2, 3] > >>> L = [] > >>> L.extend(3) > >>> L > [0, 1, 2] > >>> zip(3) > [(0,), (1,), (2,)] > > Do we really want all of these new behaviors? I don't want any of these, but then again, I don't want "for i in 4" either. I think it's an awful idea. Just From tdi01fhu at syd.kth.se Wed Mar 27 07:38:30 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Wed, 27 Mar 2002 13:38:30 +0100 Subject: Primes.... Message-ID: I should have been more specific, yes I am talking about cryptology, and sadly enough I am runnign win2k, the unix stuff goes out the window. As for how large of numbers I am looking for, I'd say about 512bit numbers should do it(perhaps larger, depens on how slow it becomes). Got any URLs that explain Fermat/Miller-Rabin tests? /Fredrik >>> Paul Rubin 03/26/02 21:43 PM >>> "FREDRIK HULDTGREN" writes: > I am looking for a way(either by finding a module online, or by getting > some helpfull hints on how to write this myself) to generate **large** > prime numbers. All help is appreciated(Id rather write the code myself > since I tend to like understanding the code that I use, but if the math > is too heavy I'll have to use other code...) How large is large? If you're trying to do cryptography, just generate random odd numbers of the size you want, do some trial divisions to eliminate candidates with small divisors, then do a few Fermat or Miller-Rabin tests, til you get a prime. Of course if you have gmpy, just do this: import gmpy,secrand def getprime(nbytes): while 1: p=secrand.getlong(nbytes) | 3 if gmpy.is_prime(p): return p where secrand.py (for unix/linux) is as follows: # Secure random number generator # Copyright 2001 Paul Rubin, Fort GNOX Cryptography # Copying permissions: GNU General Public License version 2. # $Id: secrand.py,v 1.5 2001/09/21 07:10:44 phr Exp phr $ class _secrand: def __init__(self): self.__f = open("/dev/urandom") def getbytes(self,nbytes): return self.__f.read(nbytes) def gethex(self,nbytes): import binascii return binascii.hexlify(self.getbytes(nbytes)) def getlong(self,nbytes): return long(self.gethex(nbytes), 16) secrand = _secrand() If you're trying to break the world record for finding the largest known prime, you'd normally look at special types of numbers (Mersenne numbers) and use some special algorithms for recognizing them and doing the arithmetic. It's not really practical to do that in Python. -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Fri Mar 29 17:08:53 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 17:08:53 -0500 Subject: [XP] Code Complete: Things were Scary Back Then References: Message-ID: <3CA4E5F5.70B5A7E5@engcorp.com> David Brady wrote: > > > -----Original Message----- > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > I don't remember any of the BASICs that I used, > > whether Apple II, PET, C-64, MS, or other having modules > I did this a lot. There was no enforcement of > "modules" in BASIC, but you could still do modular > programming. You only had the one big program to work > with, but you mentally divided it up into sections. Well, I used reserved blocks of line numbers in the same way, but I'd hardly deign to call that "making a module". And I didn't call the use of GOTO "sending a method to another object" either. ;-) -Peter From python at rcn.com Fri Mar 8 16:21:45 2002 From: python at rcn.com (Raymond Hettinger) Date: Fri, 8 Mar 2002 16:21:45 -0500 Subject: PEP Parade References: Message-ID: "Skip Montanaro" wrote in message news:mailman.1015592594.15478.python-list at python.org... > > Roman> Just one comment about > > Roman> PEP 270 - uniq method for list objects > Nothing new is necessary since 2.2 was released: > > >>> mylist = [1,2,3,5,6,6,9,9,1,2,3,4] > >>> mydict = dict(zip(mylist,mylist)) > >>> mydict > {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 9: 9} > >>> mydict.values() > [1, 2, 3, 4, 5, 6, 9] Here's a one-liner version that works for all iterables (using mylist only once): >>> print map(None, dict(map(None, mylist, (None,)))) [1, 2, 3, 4, 5, 6, 9] Raymond Hettinger From thomas at gatsoft.no Tue Mar 26 03:51:38 2002 From: thomas at gatsoft.no (Thomas Weholt) Date: Tue, 26 Mar 2002 08:51:38 GMT Subject: Difference between eval and exec ?? Message-ID: Eval and exec seem to have the same effect. What's the real difference? In this case : docs != enlightenment. Best regards, Thomas Weholt From aahz at pythoncraft.com Wed Mar 13 14:44:47 2002 From: aahz at pythoncraft.com (Aahz) Date: 13 Mar 2002 14:44:47 -0500 Subject: Python on Windows soon forbidden by Micro$oft? References: <20020313170608.GB2611@lilith.hqd-internal> Message-ID: In article , Cliff Wells wrote: > >As an aside, if I were on life-support, I'd rather have it run by a Gameboy >than a Windows box. May I use this quote as a .sig like this: "...if I were on life-support, I'd rather have it run by a Gameboy than a Windows box." --Cliff Wells, comp.lang.python, 3/13/2002 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. From martin at v.loewis.de Sun Mar 17 16:57:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Mar 2002 22:57:47 +0100 Subject: Windows NT shell + extended characters. Bug or what? References: Message-ID: Wolfgang Strobl writes: > >- as you point it, it fails for the raster fonts (for no apparent > > reason) > > Carefull. The problem applies to _SetConsoleOutputCP, the reason being > "SetConsoleOutputCP() is designed to change the mapping of the 256 > 8-bit character values into the glyph set of a fixed-pitch Unicode > font, rather than loading a separate, non-Unicode font for each call to > SetConsoleOutputCP(). " according to the Knowledge Base entry mentioned > above. I can appreciate the desire not to load a new font each time. However, I still think that the console could perform the conversion to the OEMCP on output, displaying the replacement character for unsupported characters. > AFAIK there is no function OutputConsoleW. Do you mean WriteConsoleW? Oops, yes. > >- it is tricky to determine reliably that a file descriptor is > > connected to a terminal. > > I wouldn't want the python interpreter become dependent on whether the > stdout file descriptor is connected to a console window or not. > Either always use the CPs of the console window associated with the > current process, or never. It wouldn't be that, but "either always use OutputConsoleW, or never". I don't know what OutputConsoleW does when the file descriptor is not a terminal. > IMHO, a standard module which allows more control over platform > specific parameters (like the code pages of the console window, if > there is one) would be my prefered solution to this class of > problems. Certainly. The questions then are "what precisely is more control", and "what precisely is this class of problems". I believe Python should use Unicode API if it has a Unicode input. On Win32, this applies to various situations: file names, registry, environment variables, console output, and Tk output. Converting to some codeset if the underlying environment converts it back to Unicode is a stupid thing to do. Regards, Martin From kjones at docstrategies.com Thu Mar 21 11:07:22 2002 From: kjones at docstrategies.com (Keith Jones) Date: Thu, 21 Mar 2002 11:07:22 -0500 Subject: Python & IRC References: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> Message-ID: <3c9a0349$1@buckaroo.cs.rit.edu> This is kind of unrelated to your question, but if you really like both Python and IRC, you may be interested int moobot, an IRC bot written in python... http://sourceforge.net/projects/moobot/ From grante at visi.com Thu Mar 21 21:17:13 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 22 Mar 2002 02:17:13 GMT Subject: Why do Windows sockets break after exactly 4 minutes? References: <3C9A7C83.F61ECDD1@engcorp.com> Message-ID: In article <3C9A7C83.F61ECDD1 at engcorp.com>, Peter Hansen wrote: > Geoffrey Talvola wrote: >> >> I've noticed that Windows sockets seem to close all by themselves if there >> is no activity for 4 minutes. Does anyone know why? > Haven't run your tests, but isn't this what SO_KEEPALIVE is used for? No. If SO_KEEPALIVE is set, then the TCP layer will send "pings" (which are actually just bogus ACKs, IIRC) back and fourth to make sure the link is still there. If the cable is pulled or the interface goes down, then the SO_KEEPALIVE option will detect this and shut down the socket. It will only close the socket if the link is physically broken. It doesn't care whether or not there is user data going back and forth. -- Grant Edwards grante Yow! Where's the Coke at machine? Tell me a joke!! visi.com From aahzpy at panix.com Thu Mar 21 10:21:13 2002 From: aahzpy at panix.com (Aahz) Date: 21 Mar 2002 10:21:13 -0500 Subject: multithreading and Tkinter References: Message-ID: In article , Arcady Genkin wrote: > >I have a separate thread, responsible for graphical stuff, which >displays a bunch of objects as "Tkinter.Lablel"s. Then, I have a >buhch of separate threads, which collect information about the >objects over the network, at specified intervals. > >How do I signal the GUI thread that new information for a particular >object has arrived? Currently I'm using after() method of the Tkinter >object to update info for *all* objects every second, but that is >hardly a good design, since there may be 500 of them, and the new info >can be arriving once every 15 minutes. The key is to use Queue.Queue() and stuff the queue with both info and the object to be updated. You'll still need to use the after() method, but you'll only do screen updates when info arrives, and you'll only need to update the changed objects. For a simplistic example, see my home page. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From netzapper at magicstar.net Sun Mar 31 20:24:44 2002 From: netzapper at magicstar.net (A. Jones) Date: Mon, 01 Apr 2002 01:24:44 GMT Subject: Cannot find what I'm sure is a simple command... please help. References: <3ca7978b.251291804@mammoth.usenet-access.com> Message-ID: <3ca7b638.259145474@mammoth.usenet-access.com> On Sun, 31 Mar 2002 19:39:45 -0500, "John Roth" wrote: > >"Aahz" wrote in message >news:a886fp$sq1$1 at panix1.panix.com... >> In article <3ca7978b.251291804 at mammoth.usenet-access.com>, >> A. Jones wrote: >> > >> >I seem to have either overlooked, or completely missed a function >that >> >allows one to open a specific line of a file. >> >> There isn't one, unless every line of your file is the same length >> (fixed-length records). You need to read one line at a time until you >> get to the correct line. > >If you read the file into a list using readlines(), you can then >access each line by the index into the list. Unfortunately, that >doesn't get you one line without reading the entire file up to >that point... > >John Roth Right, I knew I could do that. However, when I did that, it causes a meltdown when I index from that list, owing to the large size of the file (it's a database, with each entry on a separate line, but with an arbitrary line size). -----------== Posted via Newsfeeds.Com, Uncensored Usenet News ==---------- http://www.newsfeeds.com The Largest Usenet Servers in the World! ------== Over 100,000 Newsgroups - Ulimited downloads - 19 servers ==----- From robin at jessikat.fsnet.co.uk Fri Mar 8 17:46:46 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 8 Mar 2002 22:46:46 +0000 Subject: Autodiscovery of proxy settings from a python script References: Message-ID: In article , Andy Robinson writes >Thanks to several people. I am once again stunned by how >good the Python standard library is. I spent an afternoon >surfing and assumed I'd have to write code, but urllib does >most of what I want by default :-) > >Idiot's guide to proxy discovery and use: > >1. if hacking at home, get a working proxy server. I found this >which compiled fine and "sort of" works - dislikes GIFs >but can receive plain pages: > http://www.codeguru.com/internet/http_proxy.shtml > > >2. Thereafter, set the proxy in IE and you can do this: >>>> urllib.getproxies() >{'ftp': 'ftp://matterhorn:5060', 'http': 'http://matterhorn:5060'} >>>> > >3. Thereafter, calls to urllib.urlopen(myURL) seem to go through >the proxy by default. > >- Andy .... IE also uses this wpad scheme, but I'm not sure if that also affects the registry settings. -- Robin Becker From James_Althoff at i2.com Wed Mar 13 14:00:44 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 13 Mar 2002 11:00:44 -0800 Subject: Why I think range is a wart. Message-ID: [David Eppstein] > Perhaps we should use > for (i,x) in list.iteritems(): ... > (analogous to dictionaries) instead of PEP 279's indexed(list). That would be my vote, too. Of course, being not fond of "range(len(", I would throw in list.iterkeys() or list.iterindices() -- or whatever name -- also. jim From James_Althoff at i2.com Tue Mar 5 17:41:04 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 14:41:04 -0800 Subject: Status of PEP's? Message-ID: [Tim Delaney] > From: James_Althoff at i2.com [mailto:James_Althoff at i2.com] >> >> [snip] >> being sequences . >> [snip] >> back at ya ). >> [snip] >> And keep on writing code . > > You've really taken to heart Tim Peter's comments about looking > more favourably on those who know how to , haven't you? ;) No. Actually, I just have some dirt in my eye. (Ok, that was pathetic). But if I had some pictures or other, uh, useful material I would use that, too. Unfortunately, the pictures that my P.I. turned up of a nice, adoring dad feeding a baby aren't that big a score. And I've been told that images of the T-bot aren't possible because he carries in his front shirt pocket an unusual rock from his home planet that wrecks film and memory sticks. (I *really* have a compulsive urge to type a you-know-what right about now In my school I'm using a Web-server called Zope, which is Python-based, for inhouse use only. What I wanna do is for example, based on the REMOTE_ADDR field, resolve that to the currently logged in username, look it up in a database and for example display a birthday greeting where appropriate. So far I've found sockets.gethostbyaddr(ip) which gives the computer's name. In my opinion this is way too slow. Something like 3-5 seconds. Is there a function or something that is like getuserbyaddr(ip)? I don't think I've found anything I can use. The Web-server is on the same server they log on to. (Which by the way is a Win2k server with DHCP) Thanx in advance Tom Halvorsr?d Oslo From graz at mindless.com Sat Mar 16 06:12:48 2002 From: graz at mindless.com (Graham Ashton) Date: Sat, 16 Mar 2002 11:12:48 +0000 Subject: Optimising list comparison References: Message-ID: On Fri, 15 Mar 2002 21:41:46 +0000, Skip Montanaro wrote: > Psyco . I added these lines at > the end of your benchmark script: > > import psyco > psyco.bind(attempt1) > psyco.bind(attempt2) > benchmark(attempt1) > benchmark(attempt2) > > and ran it again. Bloody hell. That's seriously impressive. I re-ran the script that I posted in response to Tim's post, but changed the loop at the bottom to: import psyco for f in (attempt1, attempt2, attempt3, attempt4, attempt6): benchmark(f) psyco.bind(f) benchmark(f) print Now I get: ratchet% python listmatch.py 100000 iterations of took: 3.357856 secs 100000 iterations of took: 0.657385 secs 100000 iterations of took: 7.630363 secs 100000 iterations of took: 7.676283 secs 100000 iterations of took: 4.892329 secs 100000 iterations of took: 0.646776 secs 100000 iterations of took: 3.406146 secs 100000 iterations of took: 0.624154 secs 100000 iterations of took: 4.721051 secs 100000 iterations of took: 2.805202 secs Thanks Skip (and to everybody else who posted suggestions). It's been a very interesting little discussion. -- Graham From owen_stevens at hotmail.com Tue Mar 12 12:32:08 2002 From: owen_stevens at hotmail.com (Owen Stevens) Date: 12 Mar 2002 09:32:08 -0800 Subject: new to python - please help Message-ID: <9e629c01.0203120932.5b3eae15@posting.google.com> (apologies for last post) i made a dictionary (mydict) with the following structure: mykey=(list1:list2) i overwrote list1 inside the dictionary with a new list templist1=[mydict[mykey][0] templist.append(new_values) mydict[mykey]=(templist,templist2) i then tried to retrieve list1 for i in mydict[mykey][0]: print i it comes out like this: [[[[[['value1'], "['value2']"], "['value3']"], "['value4']"], "['value5']"], "['value6']"]['value7'] which is pretty useless, as len[list1] returns 2 instead of 7 can anyone point me in the right direction? From tdi01fhu at syd.kth.se Mon Mar 25 12:52:25 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Mon, 25 Mar 2002 18:52:25 +0100 Subject: Random... Message-ID: I want to generate random numbers, very large random numbers. If I use randrange() I get an out of bounds error since it only supports numbers up to (2**31)-1. However, I can use uniform(), but then I get the number returned in 7.9655120654553743e+018 or something simaler, and I would rather have it in a "L" format(796551206545537430183218312890381031L). How do I do this? thanx /Fredrik From tiberius at ms28.hinet.net Fri Mar 15 09:09:12 2002 From: tiberius at ms28.hinet.net (Tiberius Teng) Date: 15 Mar 2002 06:09:12 -0800 Subject: Using cgitb under mod_python Message-ID: <6c92a8bc.0203150609.3b62aef8@posting.google.com> Recently I'm writting a program using mod_python and want it to have a pretty printed error message page, and I find that cgitb probably helps me. But unfortunately I can't get it work under mod_python, although I imported it and called it's enable() function but my script still sends ordinary traceback info (I use 'raise ValueError' to test it out). Any ideas ? From ron at ire.org Fri Mar 1 08:37:12 2002 From: ron at ire.org (ron nixon) Date: 1 Mar 2002 05:37:12 -0800 Subject: ASV module, CVS modules References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: <61ff32e3.0203010537.79082e89@posting.google.com> sjmachin at lexicon.net (John Machin) wrote in message news:... > ron at ire.org (ron nixon) wrote in message news:<61ff32e3.0202281525.3e9bb102 at posting.google.com>... > > Hello, I'm trying to use either of these two modules ASV by Laurence > > Tratt at http://tratt.net/laurie/python/asv/ and CSV by Dave Cole at > > http://object-craft.com.au/projects/csv/. I tried both of these and > > get this error: > > > > Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 > > Type "copyright", "credits" or "license" for more information. > > IDLE 0.8 -- press F1 for help > > >>> import ASV > > >>> my_data = ASV.ASV() > > >>> my_data.input_from_file("c:\test_data.csv", ASV.CSV(), > > has_field_names =1) > > Traceback (most recent call last): > > File "", line 1, in ? > > my_data.input_from_file("c:\test_data.csv", ASV.CSV(), > > has_field_names =1) > > File "C:\PYTHON22\ASV.py", line 222, in input_from_file > > file = open(input_file, "rb") > > IOError: invalid argument: rb > > >>> > > > > I get a similar message from CSV module. Anyone use either of these > > and can tell me what's wrong? > > > > Wow. You have two problems. Bill Gates has one. And one of either you > or Dave Cole will get busted real soon now if you keep smoking that > stuff :-) > > To be more explicit: > > You 1: Don't clutter the root directory of your C: drive with anything > other than "necessary" directories, and files other than what Bill & > other software providers dump in there. > > You 2: On Windows, either use forward slashes "c:/test_data.csv" (it > works!) -- recommended -- or use raw strings r"c:\test_data.csv" if > you must. The problem is that Python's escape handling intervenes; > what Bill's software got to see in your case was equivalent to "C:" + > a_bloody_tab_character + "est_data.csv" !!! > > Bill behaving badly: Seems like Bill chucks a wobbly if there is > a_bloody_tab_character in a file name. I could be maligning Bill > unjustly; could be GvR & Co -- I'll have a look at the Python source > in a minute -- but I'd bet a couple of pots of beer that it's down to > Bill. > > You and/or Dave in peril of the law: Last time I saw Dave's module it > didn't presume to read files at all, it expected you to read lines and > pass them to it one at a time. So either Dave has had a very recent > rush of blood or something worse to the head and released unbeknownst > to me a file-handling version of his module, or you are gravely > mistaken when you assert "I get a similar message from CSV module". > > Hope this helps, > John John: Thanks a bunch. Let me try you suggestions and see if they work. It was late at night while I was trying this :). Maybe I should have had a beer. You're right about the CSV module, I didn't look at it carefully. Again, lack of beer. Ron From bokr at oz.net Tue Mar 26 22:57:49 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Mar 2002 03:57:49 GMT Subject: seek in a file References: Message-ID: On Wed, 27 Mar 2002 00:00:40 +0100, "Andreas Penzel" wrote: >Hello NG! > >How to jump to a specified line in a file which is read-opened? >With seek() I can jump to an exact position of the complete file in >"byte-steps". >Is seek able to jump to a line-number? >If not, what else can I do? > Others have mentioned that in general lines are variable length, etc. If you have a huge file, it's not practical to read it all into memory and select various lines from the list, but if you need random access to lines of a big file, you can solve the problem by making a list of line start positions as seen if you open the file in binary. I cobbled together a class to do the basic work. Here's it's use, followed by the code (for huge files, you might want to have a loadIndex and a storeIndex as well, so as to be able to load a pickled index instead of re-indexing the actual file. For small files you might as well use readlines). Below, I print a test file sequentially, and then access it randomly. Because of the binary mode, you get \r\n uncooked and included. You could modify the class to exclude them. This is only tested far enough to get the result below ;-) >>> import LineFile >>> lf = LineFile.IndexedLineFile('test.txt') >>> lf[0] Traceback (most recent call last): File "", line 1, in ? File "LineFile.py", line 24, in __getitem__ raise IndexError,'"%s" is not indexed yet.' % self.theFile IndexError: "test.txt" is not indexed yet. I expected that ;-) >>> lf.initIndex() >>> len(lf) 8 >>> for i in xrange(len(lf)): print 'lf[%d]: %s' % (i,lf[i].rstrip()) ... lf[0]: Line zero. lf[1]: A longer line, this is line one. lf[2]: Line with index two. lf[3]: 3 lf[4]: 4 (the next is blank) lf[5]: lf[6]: and 6. The next will be the last, with no EOL. lf[7]: This is the last line (index 7). >>> lf[2] 'Line with index two.\r\n' >>> lf[1] 'A longer line, this is line one.\r\n' >>> lf[7] 'This is the last line (index 7).' >>> lf[8] Traceback (most recent call last): File "", line 1, in ? File "LineFile.py", line 28, in __getitem__ return self.f.read(self.positions[i+1]-self.positions[i]) IndexError: list index out of range I expected that too ;-) >>> lf[0] 'Line zero.\r\n' ======== LineFile.py =========== class IndexedLineFile: def __init__(self, afile): self.theFile = afile self.positions = [0] self.isIndexed = 0 self.f = None def initIndex(self): self.f = file(self.theFile,'rb') MAXINT = int(2**31-1) while self.f.readline(): pos = self.f.tell() # save EOL position (last will be EOF position). # save space using integers vs longs from tell() self.positions.append(pos<=MAXINT and int(pos) or pos) # last will be EOF position self.isIndexed = 1 def close(self): try: if self.f: self.f.close() except IOError: pass self.f = None def __getitem__(self, i): if not self.isIndexed: raise IndexError,'"%s" is not indexed yet.' % self.theFile if not self.f: self.f = file(self.theFile,'rb') self.f.seek(self.positions[i]) return self.f.read(self.positions[i+1]-self.positions[i]) def __len__(self): return len(self.positions)-1 ====================================== Regards, Bengt Richter From MaximilianScherr at T-Online.de Sun Mar 24 18:09:41 2002 From: MaximilianScherr at T-Online.de (maximilianscherr) Date: Sun, 24 Mar 2002 23:09:41 -0000 Subject: Client/Server Tutorial? In-Reply-To: Message-ID: it's good, but i'm not sure if that can do what i want:) though i probably asked the wrong question. i need a tutorial for a server (not only a simple one, one with client handlers, and info on clients..., like in games) cause i want to create a server emulator for an online game, and therefor i need at first a 'server engine' to accept the packets handle them... --- In python-list at y..., "Irmen de Jong" wrote: > > Is there any good tutorial for creating advanced client/server apps > > (like online games) out there? i tried to make one 2 times, and both > > May I suggest you take a look at Pyro; http://pyro.sourceforge.net > It may be just what you want/need for easy distributed application development. > You don't have to do any network programming when using Pyro. > > Irmen de Jong > > > > -- > http://mail.python.org/mailman/listinfo/python-list From edream at tds.net Mon Mar 4 19:11:03 2002 From: edream at tds.net (Edward K. Ream) Date: Tue, 05 Mar 2002 00:11:03 GMT Subject: Why isn't pychecker mentioned prominently? References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> Message-ID: <3C840D15.6DE23E12@tds.net> Neal Norwitz wrote: > In the meantime, I suppose the best approach is to add some doc > (both in Python and Pychecker). I added a Python FAQ entry (4.101) > a while ago. What are some suggestions for where best > to update documenation, provide links, etc. > including specific pages or files? Good question. I think a link to pychecker is worth a link in the Special Topics panel at python.org/. Another possibility is py-howto.sourceforge.net/ A short paragraph there could cover tools such as pychecker, idle, pyunit. IMO, the python web site could profitably be reorganized. I'll discuss this in a new thread called "Reorganizing python.org (was: Why isn't pychecker...)" Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From fperez528 at yahoo.com Mon Mar 4 08:59:25 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 04 Mar 2002 13:59:25 +0000 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> Message-ID: Siegfried Gonzi wrote: > > I wrote this all, because I have sometimes seen people in comp.lang.lisp > which are saying that they come > from Python and want to use Lisp because Python is very slow. Surely, a > matrix-matrix multiplication of > the dimension 1024x1024 in Common Lisp (only a simple code without any > declarations) is about 5 to 10 > times faster than a native Python code with native Python arrays (a > Clean version is even about 100 > times faster). This is a??fact.?But?there?is?NumPy?out?there?and?most?of > the time a scientific data > evaluation does not include array handling ala matrix-matrix > multiplication. Often you steer through > your data sequentially. If you are really intersted in python for scientific computing, you need to look at scipy.org. There you'll find atlas-based matrix handling routines which will probably easily beat any lisp code you can come up with (atlas is optimized in assembly for your processor). But the high-level interface is still python, so you don't need to drop down to the assembly code ever. Cheers, f From anthony_barker at hotmail.com Thu Mar 7 17:10:32 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 7 Mar 2002 14:10:32 -0800 Subject: hotmail References: Message-ID: <899f842.0203071410.7a0895c4@posting.google.com> I use one written in perl (ya I know...) called gotmail.pl. It works great but uses curl under linux. You could easily rewrite it in python. Anthony "Bertrand Geston" wrote in message news:... > Seems to be magic, thanks for the question and for the response. Really > interesting. > I would like to retrieve mails from Hotmail and I wonder if it is not > 'better' to use COM/DOM on Outlook express that can, if I am not mistaken, > retrieve mails from Hotmail using http requests. By 'better', I mean less > linked to the hotmail site layout (but OK linked to the Oultook DOM > interface) and probably quicker. > > Any thought, idea, code snippets ? > > TIA. From amoustafa at pobox.com Tue Mar 19 01:33:48 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Tue, 19 Mar 2002 06:33:48 GMT Subject: Java and Python Message-ID: <3C96DBB4.6040109@pobox.com> 1. Where can I find an unbiased comparison between Java and Python? 2. Will Python dominate? 3. Who does support Python? Thanks a lot for your attention. Ahmed From gerhard at bigfoot.de Tue Mar 19 18:57:03 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 20 Mar 2002 00:57:03 +0100 Subject: [pygresql] Please suggest In-Reply-To: <20020319231043.58646.qmail@web10508.mail.yahoo.com> References: <20020319181506.8E7E757C6@smaug.vex.net> <20020319231043.58646.qmail@web10508.mail.yahoo.com> Message-ID: <20020319235702.GA4144@lilith.hqd-internal> Le 19/03/02 ? 15:10, Suraj Peri ?crivit: > Dear Group, > Please excuse me if my question is not appropriate > for this group. We are planning to make a public > object oriented database for genes and proteins ( > biological databases are generally huge and has lots > of inter-relationships). > While planning this, my friend is very much particular > about using Zope. > Our plan is using PostgreSQL-PHP tiers. > there will be many relationships between our objects. > Now the question is is Zope more sophisticated in > dealing with objects than PostgreSQL? if so is this > sophistication is in dealing with the complexity of > relationships between objects or something else? > > Please suggest is ZOPE a good and better choice that > PostgreSQL-PHP or PostgreSQL-JDBC-Java client > interface. Well, PHP, ZOPE and Java servlets are only technologies for the frontend. It doesn't matter much which one you choose - either one will work. But in IMO Python and Java better languages than PHP. And, compared to Java, Python is far easier to develop with. Btw. I've also seen some open-source computational biology libraries for Python mentioned on the comp.lang.python newsgroup. The much more important decision to make is which backend technology (database) to choose. AFAIK PostgreSQL is not really an Object Database, though it may have some features that go in this direction. I basically see two options 1) a relational database, like PostgreSQL 2) an object database, like ZODB (for Python, part of Zope). There are also several open-source object databases for Java But to say which one is more appropriate, we'd have to know more of the requirements. One more hint: if you want to reuse Java libraries from an easy-to-use language like Python, you can use Jython (http://www.jython.org/). It's a Python interpreter than runs in the JVM. As for a more perhaps more appropriate place to ask, I don't know a newsgroup that has this exact topic, but I think you might get value advice in the comp.lang.python newsgroup, or the Python mailing list, which is basically the same thing, just via email. Come to think of it, I'l just cc the Python mailing list. Have an eye there (or in the newsgroup, whichever you prefer). Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From akuchlin at ute.mems-exchange.org Thu Mar 21 15:22:13 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 21 Mar 2002 20:22:13 GMT Subject: Painful apache compilation References: Message-ID: In article , Giuseppe Ricioppo wrote: > /usr/src/Python-2.2/Python/thread_pthread.h:174: undefined reference to > `pthread_sigmask' > /usr/src/Python-2.2/Python/thread_pthread.h:176: undefined reference to > `pthread_create' Probably you need an additional library in order to get the pthreads functions; check if your system has a libpthread or libthread, and add -lpthread or -lthread to the link command. --amk (www.amk.ca) Abstraction is one of those notions that Python tosses out the window, yet expresses very well. -- Gordon McMillan, 6 Jan 2000 From m2 at plusseven.com Tue Mar 26 10:20:41 2002 From: m2 at plusseven.com (m2 at plusseven.com) Date: Tue, 26 Mar 2002 16:20:41 +0100 Subject: implementing a constant singleton In-Reply-To: References: Message-ID: <20020326152041.GA907@matijek> Without having really looked at your code I want to ask you if you've looked at: 1) Alex Martelli's Borg (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531) 2) Bruce Eckel's discussion of singeltons in "Thinking in Python" (http://64.78.49.204/TIPython.zip) -- o polite http://plusseven.com/gpg/ From martin at v.loewis.de Wed Mar 27 18:28:24 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 28 Mar 2002 00:28:24 +0100 Subject: unicode experiments + questions References: Message-ID: "Irmen de Jong" writes: > First, what is the best way to enter international and/or unicode characters > in your Python source? I can't just type the Euro sign and trust that it > is read as a Euro sign on another platform, because how does Python know > the character encoding of the source file! For Python 2.2 and earlier, I recommend to maintain the file in utf-8, and then do msg = unicode("", "utf-8") To view this source code properly, you need a UTF-8 editor; the same approach would work with any other encoding. Python will treat this code identical on all platforms. If you want the code to display properly on all editors, you can write msg = u"\N{EURO SIGN}" > So I'm using the unicode escape char syntax, but that is cumbersome > (where do I look up all my special characters?) and hard on the eyes. Numeric values are difficult to read, indeed - I recommend to use the symbolic values. On Windows, you can find those using charmap.exe; on Linux, /usr/share/i18n/charmaps/UTF-8{.gz} lists the character names. If neither is available, refer to unicode.org. > I also have the following question: > what exactly happens when I type "print u" in Python, where u > is a unicode string? It computes str(u), which in turn invokes u.encode(sys.getdefaultencoding()). > I'm on Win2000, so when I type > >>> print e.encode('cp1252') > I get the Euro symbol. What do you mean by that statement? Where do you "get" it? In the cmd.exe window? Unlikely, since that window uses the OEM encoding. Regards, Martin From paul at boddie.net Sun Mar 31 11:20:10 2002 From: paul at boddie.net (Paul Boddie) Date: 31 Mar 2002 08:20:10 -0800 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> <23891c90.0203290655.25bbcab9@posting.google.com> Message-ID: <23891c90.0203310820.60696fb1@posting.google.com> I wrote: > > In the Python community, there is obviously an intense interest in > > templating, but I haven't seen more than a handful of validation > > packages, and I can imagine that few of them actually integrate > > satisfactorily with template packages. Jon replied: > I'm not sure what you mean here. Can you give an example of what a > "validation package" might do? The way I see things, when developing Web applications, is as follows. First of all, developers need to present some state of the application, and this is where template systems first get used. Of course, as I noted in my previous response, it depends on the nature of the application (and how the development work on the application is organised) as to whether you prefer HTML-in-Python or Python-in-HTML or some "more neutral" template language. If the nature of the user responses to a particular "screen" are of more than limited complexity, it becomes tiresome to manually code HTML form tags, and this is where certain template solutions provide some help to developers. For example, JavaServer Pages provide "custom tags" which can be used to substitute commonly-used output into pages in a nicer way than "home-made" solutions (since the designers did think about the re-use of tags across applications, and there's a reasonably powerful object model for tags to plug into). The next problem, though, is coordinating the output with the input. One can invent a "custom tag" (or corresponding feature in one's framework of choice) which emits an HTML "input" field, but where is the code that checks the value returned by the user through that field, and how can we be sure that such code is validating and manipulating the same kind of data as that described by the "input" field? For example, I could invent a "custom tag" like this: This could result in the following HTML being generated: The intention might be that the contents of "someField" are in a particular format. Moreover, such data may be stored in a database system, and we might want to keep the "size" or "length" of a piece of data synchronized with the data type used in the database - it's not uncommon for such things to evolve as the requirements of an application change, but it would be very inconvenient to need to change HTML form descriptions, validation code, template system code, all in a number of different places. Template systems typically don't address these issues, whereas stand-alone validation systems address the nature of the input data but not how such data is "described" to the browser (and thus to the user). A coordinated approach which unifies input, output, and validation seems to be the logical next step in any significantly big or complex application. Paul From someone at microsoft.com Tue Mar 19 18:08:06 2002 From: someone at microsoft.com (John Smith) Date: Tue, 19 Mar 2002 15:08:06 -0800 Subject: socket.gethostbyname() AttributeError References: Message-ID: You are both right. It does work. It has to be a typo or the way that I am passing the host value into the program. Oh well... Ralph "Oleg Broytmann" wrote in message news:mailman.1016544391.11261.python-list at python.org... > On Tue, Mar 19, 2002 at 01:12:58PM +0000, Ralph wrote: > > I assumed that for scoket.gethostbyname(host), I was to pass a host of the > > type "theodore.chipmunks.com" and that I would get back an IP address as a > > doted quad. Obviously I am wrong about the form of the arguement I am to > > pass to the function, because I am getting an AttributeError message. > > > > Can anyone offer some insight? > > Python 2.2 (#1, Dec 24 2001, 17:25:15) > [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import socket > >>> socket.gethostbyname("www.python.org") > '194.109.137.226' > > Oleg. > -- > Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru > Programmers don't die, they just GOSUB without RETURN. > From rpalton at mac.com Mon Mar 11 09:02:46 2002 From: rpalton at mac.com (Ricks Palton) Date: Mon, 11 Mar 2002 10:02:46 -0400 Subject: Definition problem Message-ID: Hi, Here's a little program I found: from MMTK import * from MMTK import Bonds class MyMolecule(Molecule): def __init__(self, name, atoms, bonds): self.atoms = [] self.bonds = [] self.groups = [] self.name = name for element, position in atoms: self.atoms.append(Atom(element, position = position)) for i1, i2 in bonds: self.bonds.append(Bonds.Bond((self.atoms[i1], self.atoms[i2]))) self.bonds = Bonds.BondList(self.bonds) self.parent = None # top-level object self.type = None # no database type h2 = MyMolecule('h2', [('h', Vector(0., 0., -0.05)), ('h', Vector(0., 0., 0.05))], [(0, 1)]) h2.writeToFile('test.pdb') When I execute it, here's what I get: 09:51:06 [localhost:~/Documents] r1ck5p$ python mymolecule.py File "mymolecule.py", line 6 def init(self, name, atoms, bonds): ^ IndentationError: expected an indented block I'm on Mac OS X 10.1.3 What's the problem and what should I do? Thankx r1ck5p From abou at cam.org Sun Mar 31 14:46:26 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Sun, 31 Mar 2002 14:46:26 -0500 Subject: memory usage Message-ID: <3CA76792.589883A5@cam.org> Is there a specific way to clean the memory used by python scripts? While debugging my project, I always get a 'not enough memory to run this program' after running it a few times (Win98). I don't know if there's a "ps -aux"-like command on DOS, so I could see what's eating all the memory. I always c.close() after a c.open(), so I guess it's not because opened files are not properly closed. -- Zutroi Zatatakowski Commando PACU http://pacu.cjb.net From chris.gonnerman at newcenturycomputers.net Fri Mar 29 09:05:25 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 29 Mar 2002 08:05:25 -0600 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: <008201c1d72a$dc621be0$0101010a@local> ----- Original Message ----- From: "Steve Holden" > > "Benjamin Schollnick" wrote ... > > > The CASE is cleaner, and can only be used to compare a SINGLE variable > > with multiple values. And I believe it's easier to maintain.....(And > > can be optimized easier). > > > I don't. By the way, there's NO NEED TO SHOUT! ;-) I'm with Steve on this; but further, the reason not to add features to Python is always the same: you screw up the simplicity and cleanness. Sure, if you only add ONE of the things (sorry for shouting Steve :-) which is proposed each, oh, say each year, then the language wouldn't be screwed up. But how many things are recommended each year? A hundred or so reasonable suggestions? Even if each and every suggestion is reasonable, when you get done implementing all of them you have Perl. So, each suggested change must be weighed not only for reasonableness and utility, but also must have *really massive value* to overcome the don't-add-unnecessary-stuff rule. CASE closed. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From logstx at bellatlantic.net Sun Mar 24 19:32:40 2002 From: logstx at bellatlantic.net (logistix) Date: Mon, 25 Mar 2002 00:32:40 GMT Subject: forgetting state References: <98b6685d.0203231539.1459d00d@posting.google.com> Message-ID: > > This is a known, zero priority problem. See my recent posts on the > develop-test-debug cycle. > -- It's a feature, not a bug ;) One of the big bullet items for python is that it operates in a dynamic environment. The programmer can modify the environment at runtime. In a dynamic environment, you don't want to trust the system to decide what existing objects should be killed (other than gc) or what existing objects do or don't need to be fixed. It's up to the programmer to explicitly do this if he/she wants to. An even more unforgivable sin than not having the system "fix" broken objects/dependencies/etc is to allow the system to break currently functioning and running objects. It's very difficult (probably impossible) to write a general-purpose, "if-it-ain't-broke-don't-fix-it" algorithm. Given this, it makes sense that the only way to ensure that you've returned to the initial state of the environment is to kill it and create a new one. Now I'm not saying you need to agree with this (you obviously don't), but it is a genuine philosophical decision on how things should operate, as opposed to an oversight or bug needing to be corrected. There are probably lisp or smalltalk programmers at the other end of the spectrum who think that an image of the enviroment should be saved automatically when you shut down the interpreter. Then when you open it up again you're NOT in any sort of 'initial state', but right where you left off, bugs and all. There are also people who get very upset that 1) there is no mechanism for static typing in Python, 2) there are no plans to add it, and 3) (even worst of all!) noone cares. This is another philosophical decision and not an oversight. And, of course, with all philosophical decisions, it's really hard to prove who's right and who's wrong. [Except mob rule, and it looks like the mob has spoken.] From eric.brunel at pragmadev.com Wed Mar 6 13:04:45 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 6 Mar 2002 18:04:45 +0000 Subject: Tkinter: can widgets automatically resize to fit parent? References: Message-ID: Andy Gimblett wrote: > I want my Tk widgets (some of them, at least) to resize dynamically > with the window. > > Trivial example: > > #!/usr/bin/env python > > from Tkinter import * > > class Application(Frame): > > def __init__(self, master): > Frame.__init__(self, master) > self.action = Button(self.master, text="Go") > self.action.grid(sticky=N+E+W+S) Two reasons why it's not working: - you didn't actually display your Application in its master. The "Frame.__init__" stuff does not suffice: you should also do a pack or grid. Then, inserting the button in self.master rather than in self should be useless... - you configured your button to take the size of its parent cell using the sticky option, but you didn't tell the cell to take the whole space in its parent. This should be done via the grid_rowconfigure and grid_columnconfigure methods to set the weight option on the cell. So here is a code that does what you want: from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) ## Actually insert self in its master self.pack(fill=BOTH, expand=1) ## Configure cell at (0, 0) to take the whole space self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) ## Insert button in self rather than self.master self.action = Button(self, text="Go") self.action.grid(sticky=N+E+W+S) etc... HTH - eric - From miah at picsel.com Mon Mar 4 06:43:34 2002 From: miah at picsel.com (Miah Gregory) Date: Mon, 04 Mar 2002 11:43:34 GMT Subject: cross platform (linux/windows) problem References: Message-ID: In message Fernando P?rez wrote: > See if the following code helps. It does all the trapping of stdout/stderr > in a class, and you can then decide what to do with it. It doesn't address > the calling part of your problem, only the output part. -snip code- I tried a simple test of your code, not directly, but by hand, and although stdout /seemed/ to get trapped, it seemed to go to oblivion. stderr didn't work at all. I should note at this juncture that I'm working with python 1.5.2 from debian stable. The popen tactic works fine under windows now, as that's running python 2.0. Unfortunately, though, I can't upgrade my linux machine, as too much other stuff depends on this version of debian. Thanks for your reply, though.. I'll have another play around with it and see if I can persuade it to work. -- Miah Gregory From phlip_cpp at yahoo.com Wed Mar 27 09:26:48 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 27 Mar 2002 14:26:48 GMT Subject: Why does this work? References: <3CA1BB93.FC00D40D@pop.ntlworld.com> Message-ID: a.clarke11 wrote: > Hi > I defined a class, and made an instance. The class sis not have a > def__init__() line. In the class, I defined a function f(x) and an list > object X.tiles. Why can I later call instancename.f, and > instancename.tiles? > I thought the class had to have a def__init__() line in it for this to > work? I would be glad if somebody could spell this out for me, although > it is working perfectly well in the finished program! > The relevant code is: > class Player: > > import random > Tiles=[] > Sound="click" > Win="yippee" > playlist=[] Firstly, please push your code apart with more blank space, to make it readable. > def chooseTiles(x): > x.Tiles=[] That is called a "magic member". (At least I call it that.) Members don't only declare in the __init__, they declare anywhere you say a reference to the object, a dot, the member name, an equals =, and a value. MMs are a bad habit, because if later on you accidentally type... x.Tyles=[] ...you now have two members with similar names, and Python won't warn. We have a style guideline to only declare members in the __init__. That does very little to help this problem, but we go Test-First with PyUnit so our risk is very low. And we wrap all data members in get/set pairs, so the above would have been: x.setTiles([]) Because Magic Methods are impossible, we are covered. -- Phlip http://flea.sourceforge.net -- The plasma signature at the end of the wormhole is an approaching warbird -- From h_schneider at marketmix.com Wed Mar 20 05:51:40 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Wed, 20 Mar 2002 11:51:40 +0100 Subject: module for accessing dBase (.dbf) files? References: <3C725F2C.2020406@gncz.cz> Message-ID: "Ondrej Martinek" schrieb im Newsbeitrag news:3C725F2C.2020406 at gncz.cz... > Hi, > > anyone knows a python module for accessing dBase .dbf files. All > modules I've found so far didn't support index files. > > Regards > --ondra http://www.garshol.priv.no/download/software/python/ offers a dbfreader module, but that, too, works only for reading. http://www.fiby.at/dbfpy.html offers a link to a package that handles DBF files with Python, but it seems largely unsupported. Maybe that one can write the files, too. There's a project at http://sourceforge.net/projects/xbase-py/ but it doesn't seem to have done much. http://sourceforge.net/projects/xdb/ is a C++ library for dBase manips and advertises Perl and Python as languages too (presumably via wrappers), you may want to look at it. If you're willing to go commercial, http://mail.python.org/pipermail/python-announce-list/2001-January/000641.ht ml announces a wrapper for the Codebase library sold by Sequiter (www.sequiter.com) that should do what you want, but the wrapper doesn't include the library and you do have to pay for the latter (after a 30-days time to evaluate it). Bye, Harald From philh at comuno.freeserve.co.uk Wed Mar 20 15:48:58 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Wed, 20 Mar 2002 20:48:58 +0000 Subject: Popular style document? References: <1016641355.370859@cswreg.cos.agilent.com> Message-ID: On Wed, 20 Mar 2002 13:52:35 +0000 (UTC), Greg Weeks wrote: >Is there a popular style document for Python? I realize that there isn't a >whole lot of scope for such a thing, but I wondered because of certain >particular issues that came to mind. > > >1. I use "me" instead of "self" in method definitions. I mention this not >to ask what people think -- I have an unpleasant suspicion I think it's a good idea, if a bit unconventional. IMO the requirement to say self everywhere in methods is the worst feature of python. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From andreas at mtg.co.at Mon Mar 4 13:48:27 2002 From: andreas at mtg.co.at (Andreas Kostyrka) Date: Mon, 4 Mar 2002 19:48:27 +0100 Subject: Can Python do this? In-Reply-To: References: Message-ID: <20020304194827.42c60dd2.andreas@mtg.co.at> On Mon, 4 Mar 2002 12:51:13 -0500 "Robert Oschler" wrote: > Hello, Python newbie here. > > Let's say I'd like to build a method name into a string variable (e.g. > "FuncCall" + "1" to attempt to call "FuncCall1"). Can I then call that > method by somehow having the interpreter evaluate the string variable into a > call to the desired method? (I know this is usually done in a language like > Prolog or Lisp but I'm hoping Python can do it too.) > > If so, can you point me to a good article or example of such that would show > me the relevant Python syntax. Well, in Python your functions/methods are objects also ;) So the only tricky thing is to get the right dictionary where your objects are stored in: def func1(): print "func1" def func2(): print "func2" def func3(): print "func3" for x in xrange(1,4): globals()["func"+str(x)]() # for object methods this would be something like: # getattr(obj,"method"+str(x))() Hope this helps, Andreas From brobbins333 at shaw.ca Sat Mar 23 14:24:32 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Sat, 23 Mar 2002 19:24:32 GMT Subject: Need help with plotting Message-ID: <3c9cd61e.8124286@news> I'm new to Python and doing pretty well with it so far. One thing that has me stumped is finding an "easy" way, or any way, for that matter, to plot simple graphs. I haven't gotten into Tkinter yet and I'm not sure if there is another way to make plots. I have scipy and Numeric and I can see that there are graphing modules there but I have not been able to access them with something like: from scipy import *. This always fails with "not there" or "can't import." I've tried to do my homework on this but can't find anything that works for me. Can anybody point me in the right direction? Thanks, Bruce Robbins From rjones at ekit-inc.com Tue Mar 19 23:49:51 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Wed, 20 Mar 2002 15:49:51 +1100 Subject: bug tracking system In-Reply-To: <20020320042748.24672.qmail@web10507.mail.yahoo.com> References: <20020320042748.24672.qmail@web10507.mail.yahoo.com> Message-ID: <200203200450.EAA00166@crown.off.ekorp.com> On Wed, 20 Mar 2002 15:27, mohamed lazreg wrote: > Dear pythoners, > > Are you aware of any free bug tracking system written > in python? http://roundup.sf.net/ Richard From jeff at ccvcorp.com Thu Mar 14 14:18:27 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 14 Mar 2002 11:18:27 -0800 Subject: newbie-ish question on exec statement References: Message-ID: <3C90F783.96D0924D@ccvcorp.com> Gabe Newcomb wrote: > Hi all: > I'd appreciate any comments people might have on the limitations > of using exec. Specifically, what I want to do is build function names > dynamically and call them (don't ask why). Okay, I won't ask why. I'll just suggest another approach. (Wanting to dynamically select functions at runtime isn't odd or unusual; doing it with exec is.) Instead of calling function names via exec/eval(), build a dictionary of function objects. def my_func1(val1, val2 = "", val3 = ""): print "In func1" def my_func2(val1, val2 = "", val3 = ""): print "In func2" funcs = { "func1": my_func1, "func2": my_func2 } funcname = raw_input("Which function to call?") try: funcs[funcname](param) except KeyError: print "No such function!" You can dynamically add and remove functions from your dictionary, you can test to see if they're present before trying to use them if you wish (with the haskey() method), you can easily dynamically generate the funcname to look for, and many other benefits, all without resorting to the mess of using exec/eval(). (As a general rule of thumb, any time you're using exec or eval(), there's probably an easier/cleaner/better way of doing whatever it is you're doing.) Jeff Shannon Technician/Programmer Credit International From aahz at pythoncraft.com Thu Mar 14 18:23:03 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Mar 2002 18:23:03 -0500 Subject: new to python - please help References: <837koen7mq.fsf@panacea.canonical.org> Message-ID: In article <837koen7mq.fsf at panacea.canonical.org>, Kragen Sitaker wrote: >"Jason Orendorff" writes: >> >> Rule #1: Post real code. >> >> I can't make heads or tails of your post because all >> that code is so broken. :-/ It's got syntax errors. > >I feel like I just walked into comp.lang.perl.misc circa 1998. There's a critical difference: how do you tell when Perl has a syntax error? ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. --Aahz From aahz at pythoncraft.com Fri Mar 29 16:47:12 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Mar 2002 16:47:12 -0500 Subject: string copying References: Message-ID: In article , Robin Becker wrote: > >>>> s='abc' >>>> import copy >>>> s is copy.copy(s) >1 >>>> s is copy.deepcopy(s) >1 >>>> s is 'ab'+'c' >0 > >Is there some special reason why python inhibits string copying. I >suppose there's some attempt being made to make these constants. To make >differing versions of 'abc' one has to resort to silliness like 'ab'+'c' Why do you care? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From cfelling at iae.nl Thu Mar 28 17:48:37 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 28 Mar 2002 23:48:37 +0100 Subject: mutliple search and replace References: Message-ID: Trung Hoang wrote: > hey Gustavo, > actually i wished to do the replacement in one sweep and occuring in any > order.. to avoid problems.. is it easy? yes it is, use re.sub and remember the repl param to re.sub can be any Python callable too, like: >>> import re >>> def OneSweep(replacements, txt): ... def repl(match): ... return replacements[match.group()] ... matching = "|".join([re.escape(x) for x in replacements]) ... return re.sub(matching, repl, txt) ... >>> txt = "SPAM and eggs or spam and EGGS" >>> print OnesWeep({"SPAM": "spam", "spam": "SPAM"}, txt) spam and eggs or SPAM and EGGS -- groetjes, carel From peter at engcorp.com Fri Mar 15 19:10:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 15 Mar 2002 19:10:26 -0500 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: <3C928D72.165A89C9@engcorp.com> John Roth wrote: > > Putting an icon on the desktop is a bit more difficult. AFIK, that > has to go into the registry, and hacking the registry is not for the > faint of heart, especially if you're doing it remotely. Everything > else you said you want to do can be backed out manually, > with a little effort. Might not be the approved method, but you can just put a link in c:\windows\desktop (preferably finding the windows folder by referencing the proper win32api call first). -Peter From jeff at ccvcorp.com Thu Mar 21 17:48:01 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 21 Mar 2002 14:48:01 -0800 Subject: Develop-test-debug cycle References: Message-ID: <3C9A6321.9953DC71@ccvcorp.com> logistix wrote: > Like Tim said, the module is getting reloaded but instances aren't getting > re-instantiated. No, because Dale explicitly deleted and recreated the specific instances in question. Actually, what Tim was saying is that it's the from Wibblemodule import wibble that's the problem. Once this is done, reloading Wibblemodule will not change what wibble is bound to. Thus, calls to wibble() will still use the old definition, regardless of how many times Wibblemodule is reloaded. This is one more reason that I dislike using 'from import xxx', even when 'xxx' != '*'. One possible fix/workaround, though also possibly a huge pain in the posterior, is to simply change all references to wibble to use Wibblemodule.wibble. Another thing that might work: reload(Wibblemodule) from Wibblemodule import wibble By specifically re-importing wibble, this should (I think) re-bind the name to the new version. Jeff Shannon Technician/Programmer Credit International From nbecker at fred.net Fri Mar 8 08:45:52 2002 From: nbecker at fred.net (N Becker) Date: 8 Mar 2002 05:45:52 -0800 Subject: Turn string into function call Message-ID: <1f5252d4.0203080545.3861adec@posting.google.com> What's the best way to turn a string naming a function into a function call? I used this: eval (funcname + '()') From robin at jessikat.fsnet.co.uk Fri Mar 1 05:11:24 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 10:11:24 +0000 Subject: Aquisition Alert References: Message-ID: I thought we could just inherit, but if you say Acquisition is smarter I guess I have to try and understand it. -- Robin Becker From parker at gol.com Fri Mar 15 18:48:24 2002 From: parker at gol.com (Ian Parker) Date: Fri, 15 Mar 2002 23:48:24 GMT Subject: 15 minute presentation on python? References: Message-ID: In article , Michael Chermside writes >Ian Parker writes: >> I wow'd my audience by using Python with the win32 extensions to show >>simple it was to load data (proxy server log files) into MS Excel. > [...] > > >Congradulations! Glad it went so well. By the way, I'm doing a brief >Python presentation in a couple of weeks... would you be interested in >sharing your presentation? > >-- Michael Chermside > mcherm at destiny.com > > Michael I've sent you my notes, etc., on this by email. hope it helps. Regards Ian -- Ian Parker From bokr at oz.net Sun Mar 10 19:14:39 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Mar 2002 00:14:39 GMT Subject: Standalone Win32 wxPython apps? References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> <1a9n8us1629mrvei40hdkuuerc1j6p318m@4ax.com> <9okn8ucu390vhk8nfhvb98c3aqotm2dllu@4ax.com> Message-ID: On Sun, 10 Mar 2002 22:59:33 +0100, Wolfgang Strobl wrote: >Sun, 10 Mar 2002 20:05:24 GMT, grante at visi.com (Grant Edwards): > >>I would think that for an isolated app, .so's would slow down >>load times. With a statically linked program all you do is a >>single memmap() call (well, ignoring a few details). With >>.so's you've actually got to resolve all of the symbols and do >>the linking step (not required for statically linked images). > >Windows DLLs are already linked. > Although it is possible totally to defer loading particular dll's. E.g., consider what the VC++ debugger itself does, which doesn't know what you want to do until you tell it. You can set up automatic default loading or program controlled loading in apps too, AFAIK. Regards, Bengt Richter From brueckd at tbye.com Sat Mar 2 16:33:41 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sat, 2 Mar 2002 13:33:41 -0800 (PST) Subject: hotmail In-Reply-To: <200203020114.TAA76302@starbase.neosoft.com> Message-ID: On Fri, 1 Mar 2002, Cameron Laird wrote: > >> im just wondering whether it is possible to access hotmail thru python > >> so that i have a far quicker way of checking my emails. can telnetlib > >> do this? > > > >If you're on Windows (and have either ActiveState Python or Mark Hammond's > >win32all extensions) then you can use COM to create a web browser instance > >and use its DOM interface to navigate. I made a small script to retrieve > >my address book this way - I'll try to dig it up and post it, but it's > >pretty easy to do from scratch too. > > > >-Dave > > I'd like to see this. I don't know what I did with the original version I wrote, so I rewrote it. I don't know if I'm doing everything by the "officially correct" methods, but it works great. Here you go: ''' Example of using InternetExplorer COM/DOM interfaces to retrieve your Hotmail address book. Dave Brueck ''' import win32com.client, time def WaitForDoc(ie): 'Return the document once it is loaded' while ie.Busy: time.sleep(0.1) doc = ie.Document while doc.readyState != 'complete': time.sleep(0.1) return doc def ClickOn(ie, text): 'Follow a link and return the resulting doc' for link in ie.Document.Links: if link.href.find(text) != -1: link.Click() break return WaitForDoc(ie) # Start up a browser ie = win32com.client.Dispatch('InternetExplorer.Application.1') ie.Visible=0 # Change to 1 to see it in action ie.Navigate('http://www.hotmail.com') doc = WaitForDoc(ie) # Fill in the username and password doc.All('login').Value = 'USERNAME' # Insert your own here doc.All('passwd').Value = 'PASSWORD' # Ditto doc.Forms[0].Submit() # Click on the Address Book link doc = WaitForDoc(ie) doc = ClickOn(ie, 'addresses') # Find the correct table doc = WaitForDoc(ie) table = doc.getElementsByName('ListTable')[0] # Extract the rows (spruce up as needed) rows = table.rows for i in range(rows.length): cells = rows[i].cells for j in range(cells.length): print cells[j].innerText, '|', print # Logout doc = ClickOn(ie, 'logout') doc = WaitForDoc(ie) From shredwheat at attbi.com Thu Mar 28 12:11:04 2002 From: shredwheat at attbi.com (Pete Shinners) Date: Thu, 28 Mar 2002 17:11:04 GMT Subject: Image in a module question References: Message-ID: <3CA2E042.2080307@attbi.com> Christopher wrote: > A while back, I remember somebody mentioning a way to store image data > in a Python module. This is something I think I could really use (I > want to incorporate an image into an frozen exe that I am writing for > my coworkers). I would like to keep the installation nice and neat > (--onefile) and I figure the easiest way is to store the image in a > module, import it, then use the string (I am assuming this is what you > would get from the module, I can't remember what the post sais) e.g., i've got a working tool that does this. although it uses pygame to load and display the image (could probably be switched to PIL without too much effort) http://www.pygame.org/pcr/submissions/01142002b.html this will create a .PY file with an image in it. the PY file even has a small "bootstrap" code so running the script will display the image. it properly handles things like palettes and colorkeys From rjones at ekit-inc.com Wed Mar 13 20:16:16 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 14 Mar 2002 12:16:16 +1100 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: <20020313154713.A30850@ActiveState.com> References: <200203132236.WAA11518@crown.off.ekorp.com> <20020313154713.A30850@ActiveState.com> Message-ID: <200203140116.BAA01141@crown.off.ekorp.com> On Thu, 14 Mar 2002 10:47, Trent Mick wrote: > [Richard Jones wrote] > > > Have you investigated roundup recently? That is, since it was re-written > > from scratch using the spec from the Software Carpentry project? Or are > > you just making these statements based on several-year-old-knowledge? > > No I haven't looked at it recently. I was just giving my (FUD-y) experience > of the Roundup pre-Software-Carpentry. Yeah - a _lot_ has changed since then. This is yet another time that I regret not re-branding the tracker :( Can you attach files to issues/bugs > in the new Roundup? Yep - via the web or email interfaces. Richard From tony at lsl.co.uk Wed Mar 27 05:48:39 2002 From: tony at lsl.co.uk (Tony J Ibbs (Tibs)) Date: Wed, 27 Mar 2002 10:48:39 -0000 Subject: Python UK - April 4th and 5th In-Reply-To: Message-ID: <005901c1d57c$f4745450$545aa8c0@lslp862.int.lsl.co.uk> phil hunt wrote: > Perhaps I'm being a little obtuse here, but why would I want to pay > 260 quid to talk about Python? I can talk about it here for > nothing. > > I guess this is something intended to be funded by the delegates' > employers. Well, my employer *is* paying me to go to one day of the conference - but unfortunately, the first day, which is the day before the Python bit. I am then paying for an additional day so I can go to the first day of the *Python* conference (I can't spare more than two days away from home, so that simplifies decision making). Why bother? Well, first off, it's nice to *meet* people with a common interest [1]_. Broadcasting over an open medium like the Python list is nice enough (and a tremendously useful resource), but people's written skills are not necessarily terribly well related to their personal skills (for instance), and meeting people can give a lot more "feel" for them than just corresponding. .. [1] and I get to stay with friends, which is an additional bonus - Duncan, do I have to promise not to talk Python at home? Secondly, different people learn in different ways. It *can* be a serious advantage to sit through a presentation, over just reading the (essentially identical) text. And with a presentation, one can ask questions! And it's quite hard to do a workshop online. (and I actually *want* to play at being an EJB instance - I think) Thirdly, there's an element of potential serendipity at a conference that one doesn't have in the more formalised environment of a list or newsgroup. One can meet people by accident who apparently have nothing to do with one's direct interests, but who still cast light on those interests for reasons one could not have predicted. Or add new interests (and this in turn means that there are actually advantages in Python sharing space with another shared-set-of-interests). And lastly, for some people, just the getting away can be a perk - being in a different place, for different purposes. (I guess it's also worth saying that 130pounds per day is pretty cheap for a conference, especially one that has the calibre of people attending that this one does, so no, it probably is *not*, on the whole, intended only for people whose employers are paying.) Tibs -- Tony J Ibbs (Tibs) http://www.tibsnjoan.co.uk/ "I'm a little monster, short and stout Here's my horns and here's my snout When you come a calling, hear me shout I will ROAR and chase you out" My views! Mine! Mine! (Unless Laser-Scan ask nicely to borrow them.) From gerson.kurz at t-online.de Thu Mar 14 07:03:02 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Thu, 14 Mar 2002 13:03:02 +0100 Subject: Disabling rexec for ActiveScripting in Local Intranet Zone? Message-ID: When you do Client-Side ActiveScripting in Python, you cannot create win32com objects. If my understanding is correct, this is caused by rexec() limiting what you can do, for security reasons. However, over Client-Side Scripting languages such as JScript and VBScript allow you to create ActiveX objects, if IEs security settings allow that. Is there some trick to allow using ActiveX objects (if security is "properly" configured) for the local zone? The situation is this. I have a C++ written ActiveX object for scripting webpages that controls some kind of hardware. I want to be able to write test scripts in python, and not in Javascript. Test scripts that are run from the command line work just fine, only IE scripts don't, because of said limitations. Currently, I have to stick with Javascript for sample codes, which is (not surprisingly) a PITA. From rupert.kolb at med.uni-tuebingen.de Mon Mar 11 05:57:37 2002 From: rupert.kolb at med.uni-tuebingen.de (Rupert Kolb) Date: Mon, 11 Mar 2002 11:57:37 +0100 Subject: Homepage of Gadfly not available? Message-ID: <3C8C8DA1.5040901@med.uni-tuebingen.de> Hi, for weeks, I'm trying to reach the home page of the Gadfly DB. http://www.chordate.com/gadfly.html doesn't work. Is this my fault? -- Rupert Kolb From bokr at oz.net Tue Mar 26 16:48:07 2002 From: bokr at oz.net (Bengt Richter) Date: 26 Mar 2002 21:48:07 GMT Subject: reduce vs. for loop References: Message-ID: On Tue, 26 Mar 2002 08:07:09 -0800 (PST), "Sean 'Shaleh' Perry" wrote: > >On 26-Mar-2002 m2 at plusseven.com wrote: >> >> Just out curiosity, >> why is fact2 a bit faster than fact1? >> >> def fact1(n): >> return reduce (operator.mul, range(1L,n + 1)) >> >> def fact2(n): >> result = n * 1L >> for i in range(1 , n): >> result *= i >> return result >> > >bigger problem here. fact2 returns a long, fact1 returns an integer. So >fact1(100) fails. > Looking at '1L' in the range part of that, I was wondering how that would work. Well, >>> range(1L,2L) [1] >>> type(range(1L,2L)[0]) so I guess L's get demoted. I was a little surprised that range hasn't gotten the benefit of integer overflow handling to promote to longs in 2.2: >>> range(1L<<33,(1L<<33)+2L) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to int One thing leads to another: bitshift doesn't promote either. I guess I understand good reasons for this, but it makes the platform in/dependence of integer a bit blurry. >>> '%10x' % (15<<30) ' c0000000' >>> '%10x' % (15L<<30) ' 3c0000000' >>> '%10x' % (15*2**30) ' 3c0000000' Regards, Bengt Richter From herrn at gmx.net Wed Mar 6 10:25:45 2002 From: herrn at gmx.net (Marco Herrn) Date: Wed, 6 Mar 2002 16:25:45 +0100 Subject: how to give an object as argument for a method In-Reply-To: References: Message-ID: <20020306152545.GA2369@lurkabove.darkstar> Hi Bertrand, On Wed, Mar 06, 2002 at 03:07:53AM -0800, Bertrand Geston wrote: > If I understand your question correctly, you can do it like in java: > > >>> class Spam: > ... def sayYesBut(self, caller): > ... print "Yes %s, but I'm %s !" % (caller, self) > ... > >>> class Egg: > ... def __init__(self): > ... self.spam = Spam() > ... def saySomething(self): > ... self.spam.sayYesBut(self) > ... > >>> egg = Egg() > >>> egg.saySomething() Yes, that was the thing I was serching for. So it does have something to do with the 'self' statement. This statement is not a reserved word, so I have to implement it by myself by giving it as a parameter to the __init__() method. Am I right there? > - 'self' is used in Python in place of 'this' in java > - 'self' is mandatory (no implicit reference to the instance) > - 'self' is not a reserved word but a **STRONG** naming convention for the > first argument of every method that always refer to the instance hmm, do I have to implement that in _every_ method or just in methods who use the 'self' statement? I know, the methods work without self, but what is the convention? > > PS. Here is a way to do it magically. It comes from the excellent post 'Get > reference to "owner"' from ... yesterday ! This is powerfull and funny but > IMHO it hurts good principles of design. What does it hurt? It looks good to me. It is just the same as above and I think that is really good. [snip] > ... def sayNo(self): > ... caller = sys._getframe(1).f_locals['self'] this is the only line, that looks a bit ugly. It actually does the same as when giving caller as parameter. So what can be a reason to implement it this way? It looks much less readable to me. And I have to say I not even understand it fully.... So many thanks for your help Bye Marco -- If you didn't have to work so hard, you'd have more time to be depressed. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From lac at strakt.com Thu Mar 21 12:37:08 2002 From: lac at strakt.com (Laura Creighton) Date: Thu, 21 Mar 2002 18:37:08 +0100 Subject: "Zope-certified Python Engineers" [was: Java and Python] In-Reply-To: Message from Steven Majewski of "Thu, 21 Mar 2002 11:21:37 EST." References: Message-ID: <200203211737.g2LHb8rq003324@ratthing-b246.strakt.com> > ( Or maybe this begs for a Slashdot like system to > distribute the review, grading and selection of projects. ) > > > -- Steve You want something more like the scientific reviewing of a technical paper than slashdot's 'all you need to vote is a pulse'. Otherwise the most popular wrong way to do something will generate the highest marks. This is a very hard thing to do politically -- there is a tightrope between the sort of eletism which exists to keep a lid on new, good, creative endeavours (a flaw you can correct by inserting more democracy into your process)and pandering to the worst base instincts of humanity (a flaw you can correct by having higher standards in your selection committee). The best way to do this is to provide a certain amount of meta-data with your assessment -- so we can find out not only that Steven Majewski thinks that XXX is cool, but also that Steven Majewski has a reputation around here, and most people think that Steven Majewski's opinion of something is valuable. This doesn't stop Flaming Rabid Hamster from voting that Steven Majewski is a fool and that every project that Steven Majerski finds valuable is worthless, but if this is an minority opinion of 1, then people will know where to place their bets. Not only does this work when evaluating the worthless and the vital, but it is even more important when evaluating people and things that are in the middle. Some people know a huge amount about a few subjects but also shoot their mouths off about things they don't know anything about. Some pieces of code are terrific solutions for extremely hairy nasty problems -- but the real fix is not to have the problem in the first place. Some people will blast the code when they should be blasting the problem, and valuable workarounds can get lost in the 'Get a Real Operating System' votes. Some solutions are excellent -- provided you don't have It would be nice to be able to indicate this as well. I think that this sort of metadata belongs in the sort of cataloging system we should have to implement PEP 262, as well. Of course, I am biased -- AB Strakt is building something to do this, because we think that its a huge world problem that needs fixing. Laura Creighton From peter at engcorp.com Fri Mar 15 00:00:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 15 Mar 2002 00:00:43 -0500 Subject: should i learn it first ? References: Message-ID: <3C917FFB.25CA13A9@engcorp.com> "Qiang.JL" wrote: > > Do you guys not agree to master C/C++, a large amount of time will be > required (somewhere on the net i saw it's appro 3-4 years. whew!!) [...] > and one more question, what's you view of "you have mastered a language" ? > knowing syntax and grammer is the begining to master, then know how to use > them(wisely) and coding coding ... after certain long time , that you call > you master the language? Don't treat C and C++ together like that. It would *not* take three to four years to master C, although I suppose it might take that long (or longer :-) to "master" C++. As far as the definition of "master", I find that with any language that is similar to another language I know in basic style (e.g. having learned things like Pascal and C++, Delphi seemed quite similar) I can "master" it in a week or two if I'm actually using it. With C, you need to know that there is no I/O built in to the language, pointers are key, structs are the most complicated data type you can get, and assignment statements are expressions. Probably a half dozen other little tidbits. Nothing that hard. C++ is another story of course. -Peter From skip at pobox.com Fri Mar 15 11:57:58 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 15 Mar 2002 10:57:58 -0600 Subject: readline() blocks after select() says there's data?? In-Reply-To: References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> Message-ID: <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Rich> I don't really need select to block. I just want it to be Rich> accurate. If it returns a file object in the list of things which Rich> are available, why should then readline() block on it? Remember that select() is lower level than readline(). As someone else pointed out, select() may return because there is data available, but it makes no promises about what that data is. Calling readline() may then hang waiting for other conditions (presence of a newline in the input, for example). -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From skip at pobox.com Thu Mar 28 09:58:33 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 28 Mar 2002 08:58:33 -0600 Subject: Very small zlib/svg problem In-Reply-To: <20020328153415.D11101@phd.pp.ru> References: <15522.19213.655102.927935@12-248-41-177.client.attbi.com> <20020328153415.D11101@phd.pp.ru> Message-ID: <15523.12185.915711.200047@12-248-41-177.client.attbi.com> Oleg wrote: f = gzip.open("c:/test.svgz", "w") ^^ this suggests to use binary modes for binary files: f = gzip.open("c:/test.svgz", "wb") Patch submitted to force 'b'. Feel free to check it out and comment. In particular, since I don't run on Windows I can't really test it out where it matters. http://python.org/sf/536278 -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From mwh at python.net Fri Mar 22 06:47:16 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 22 Mar 2002 11:47:16 GMT Subject: 2.2.1c1 platform experiences Message-ID: I've attempted to summarise the reports of people using 2.2.1c1 on various platforms here: http://starship.python.net/crew/mwh/221c1-reports.txt Can people fill in gaps, confirm/deny rumours, dig into the mentioned problems? It might be best to email me rather than posting to the group, but I'll see it either way. TIA, M. -- SPIDER: 'Scuse me. [scuttles off] ZAPHOD: One huge spider. FORD: Polite though. -- The Hitch-Hikers Guide to the Galaxy, Episode 11 From tim.one at comcast.net Sat Mar 2 00:42:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 02 Mar 2002 00:42:49 -0500 Subject: Python 2.2 seriously crippled for numerical computation? In-Reply-To: Message-ID: [Huaiyu Zhu] > There appears to be a serious bug in Python 2.2 that severely limits its > usefulness for numerical computation: > > # Python 1.5.2 - 2.1 > > >>> 1e200**2 > inf A platform-dependent accident, there. > >>> 1e-200**2 > 0.0 > > # Python 2.2 > > >>> 1e-200**2 > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: (34, 'Numerical result out of range') That one is surprising and definitely not intended: it suggests your platform libm is setting errno to ERANGE for pow(1e-200, 2.0), or that your platform C headers define INFINITY but incorrectly, or that your platform C headers define HUGE_VAL but incorrectly, or that your platform C compiler generates bad code, or optimizes incorrectly, for negating and/or comparing against its definition of HUGE_VAL or INFINITY. Python intends silent underflow to 0 in this case, and I haven't heard of underflows raising OverflowError before. Please file a bug report with full details about which operating system, Python version, compiler and C libraries you're using (then it's going to take a wizard with access to all that stuff to trace into it and determine the true cause). > >>> 1e200**2 > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: (34, 'Numerical result out of range') That one is intended; see http://sf.net/tracker/?group_id=5470&atid=105470&func=detail&aid=496104 for discussion. > This produces the following serious effects: after hours of numerical > computation, just as the error is converging to zero, the whole thing > suddenly unravels. It depends on how you write your code, of course. > Note that try/except is completely useless for this purpose. Ditto. If your platform C lets you get away with it, you may still be able to get an infinity out of 1e200 * 1e200. > I hope this is unintended behavior Half intended, half both unintended and never before reported. > and that there is an easy fix. Sorry, "no" to either. From mickey at tm.informatik.uni-frankfurt.de Sun Mar 24 13:08:50 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 24 Mar 2002 20:08:50 +0200 Subject: 2.2.1c1 platform experiences References: Message-ID: <3c9e2442@nntp.server.uni-frankfurt.de> Michael Hudson wrote: > I've attempted to summarise the reports of people using 2.2.1c1 on > various platforms here: Speaking of foreign or unusual platforms... does anyone have a reliable build-script for building python on arm-linux ? Yours, :M: From graz at mindless.com Sat Mar 9 05:42:04 2002 From: graz at mindless.com (Graham Ashton) Date: Sat, 09 Mar 2002 10:42:04 +0000 Subject: Q: How can I lock a file in Windows? References: Message-ID: On Sat, 09 Mar 2002 10:06:08 +0000, A.Newby wrote: > Is there another way I can lock the file in Windows? Yes. Try this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 -- Graham From shalehperry at attbi.com Fri Mar 29 18:14:28 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 29 Mar 2002 15:14:28 -0800 (PST) Subject: IOError on file close In-Reply-To: Message-ID: > > That indeed appears to be the case, but it looks like a bug in the > kernel to me. > why? /proc/scsi/scsi is clearly marked 444 on my machine, not 644. From jiba at tuxfamily.org Wed Mar 27 15:07:31 2002 From: jiba at tuxfamily.org (Lamy Jean-Baptiste) Date: Wed, 27 Mar 2002 21:07:31 +0100 Subject: Q: Sound production with python? References: Message-ID: <20020327.210717.1542632526.2886@localhost.localdomain> Dans l'article , "A.Newby" a ?crit : > Being a beginner fiddle player, as well as a beginner python programmer, > I want to write a little prog that trains the sense of pitch. > > How envisage it working is thus... > > It plays a simple 4 note melody, then repeats the melody with one of the > notes (selected randomly) slightly off pitch ... say by 20% or 10% or > 5%. The user then has to detect which note was off. > > What modules and commands should I use to generate this sounds? What's > the best way to go about it? I am currently writing GTablature, a tablature editor for Gnome and it include a MIDI-file generation module (song.py). You can use it to generate to generate MIDI file, and then play them with an external app. Get it at : http://oomadness.tuxfamily.org/gtablature/en Jiba From bergeston at yahoo.fr Thu Mar 7 12:58:07 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Thu, 7 Mar 2002 18:58:07 +0100 Subject: hotmail References: Message-ID: Seems to be magic, thanks for the question and for the response. Really interesting. I would like to retrieve mails from Hotmail and I wonder if it is not 'better' to use COM/DOM on Outlook express that can, if I am not mistaken, retrieve mails from Hotmail using http requests. By 'better', I mean less linked to the hotmail site layout (but OK linked to the Oultook DOM interface) and probably quicker. Any thought, idea, code snippets ? TIA. B. wrote in message news:mailman.1015102571.6690.python-list at python.org... > On Fri, 1 Mar 2002, Cameron Laird wrote: > > > >> im just wondering whether it is possible to access hotmail thru python > > >> so that i have a far quicker way of checking my emails. can telnetlib > > >> do this? > > > > > >If you're on Windows (and have either ActiveState Python or Mark Hammond's > > >win32all extensions) then you can use COM to create a web browser instance > > >and use its DOM interface to navigate. I made a small script to retrieve > > >my address book this way - I'll try to dig it up and post it, but it's > > >pretty easy to do from scratch too. > > > > > >-Dave > > > > I'd like to see this. > > I don't know what I did with the original version I wrote, so I > rewrote it. I don't know if I'm doing everything by the "officially > correct" methods, but it works great. Here you go: > > ''' > Example of using InternetExplorer COM/DOM interfaces to > retrieve your Hotmail address book. > > Dave Brueck > ''' > > import win32com.client, time > > def WaitForDoc(ie): > 'Return the document once it is loaded' > while ie.Busy: time.sleep(0.1) > doc = ie.Document > while doc.readyState != 'complete': time.sleep(0.1) > return doc > > def ClickOn(ie, text): > 'Follow a link and return the resulting doc' > for link in ie.Document.Links: > if link.href.find(text) != -1: > link.Click() > break > return WaitForDoc(ie) > > # Start up a browser > ie = win32com.client.Dispatch('InternetExplorer.Application.1') > ie.Visible=0 # Change to 1 to see it in action > ie.Navigate('http://www.hotmail.com') > doc = WaitForDoc(ie) > > # Fill in the username and password > doc.All('login').Value = 'USERNAME' # Insert your own here > doc.All('passwd').Value = 'PASSWORD' # Ditto > doc.Forms[0].Submit() > > # Click on the Address Book link > doc = WaitForDoc(ie) > doc = ClickOn(ie, 'addresses') > > # Find the correct table > doc = WaitForDoc(ie) > table = doc.getElementsByName('ListTable')[0] > > # Extract the rows (spruce up as needed) > rows = table.rows > for i in range(rows.length): > cells = rows[i].cells > for j in range(cells.length): > print cells[j].innerText, '|', > print > > # Logout > doc = ClickOn(ie, 'logout') > doc = WaitForDoc(ie) > > > From hfoffani at yahoo.com Sun Mar 31 11:27:02 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Sun, 31 Mar 2002 18:27:02 +0200 Subject: Most important extensions? References: Message-ID: <20020331112707.353$Hl@news.newsreader.com> "Aahz" escribi? en el mensaje > .... > Pmw does, but that's the only one. Sorry for not making clear that I > was specifically referring to 3rd-party extensions. I'd think win32all may apply then. But you said OSCON, so.... ;-) Regards, -Hernan From logstx at bellatlantic.net Sun Mar 3 15:16:06 2002 From: logstx at bellatlantic.net (logistix) Date: Sun, 03 Mar 2002 20:16:06 GMT Subject: Can't seem to get it right: Win NT registry save and load References: <0aag8.8540$va.1091@nwrddc02.gnilink.net> Message-ID: Yeah, to do that in Python, you need to use RegOpenKey, and then crawl through the keys and values with RegEnumKeyEx and RegEnumValue and then Recursively crawl through all the subkeys you grabbed from RegEnumKeyEx or (the easier, but not totally pythonic way): distribute reg.exe with the source and use: os.popen("REG /EXPORT HKLM\Software\Classes filename.reg") # to make reg file and os.popen("REG /IMPORT filename.reg") # to apply to other machines. -- - "Matthias Janes" wrote in message news:d7d5ebdf.0203030726.49e10001 at posting.google.com... > Thank's alot - you pushed me in the right way - I actually do not > realy need to save whole hiv but just a few keys. > > Thanks - I thought this could work somehow like regedit's export > import feature > but properly it's not realy what I need. From eppstein at ics.uci.edu Mon Mar 4 23:30:15 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 04 Mar 2002 20:30:15 -0800 Subject: Status of PEP's? References: <3C8445FC.A1816810@cosc.canterbury.ac.nz> Message-ID: In article <3C8445FC.A1816810 at cosc.canterbury.ac.nz>, Greg Ewing wrote: > So it seems that the following would work: > > for_stmt: 'for' (exprlist 'in' testlist > | exprlist lt_op exprlist lt_op exprlist > | exprlist gt_op exprlist gt_op exprlist) ':' suite ['else' ':' > suite] > > lt_op: '<' | '<=' > gt_op: '>' | '>=' Yes, I have something much like this in the draft PEP I am working on. But the outer expressions should be or_expr to respect Python's precedence rules, and the inner one should be identifier. > Later phases of the compiler would be responsible for checking > that the exprlists in the new parts actually contain only one > item each, and that the middle one is a variable. Checking that the outer expressions contain one item rather than a tuple needs to be done at run time. Of course, the compiler can catch some instances where the expression is obviously non-single. From mwh at python.net Thu Mar 7 04:35:05 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 7 Mar 2002 09:35:05 GMT Subject: select.select() on Regular Files? References: Message-ID: jimd at vega.starshine.org (Jim Dennis) writes: > O.K. so what can I do for asynchronous I/O notification on > regular files? How can I efficiently block and wake up when > I/O is available on any of my file descriptors? > > Don't tell me I have to go into a sleep and poll stat() or > seek() loop! It's hard to imagine that UNIX got this far > without offering a better solution than that! OK, I won't tell you that. Cheers, M. -- 3. Syntactic sugar causes cancer of the semicolon. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From jeff at ccvcorp.com Fri Mar 22 19:17:19 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 22 Mar 2002 16:17:19 -0800 Subject: Copmlex structures.... References: Message-ID: <3C9BC98E.CB114614@ccvcorp.com> "Dmitry S. Makovey" wrote: > 01. >>> f={} > 02. >>> f['name']='dimon' > 03. >>> f['age']=20 > 04. >>> a=[] > 05. >>> a.append(f) > 06. >>> print a > 07. [{'age': 20, 'name': 'dimon'}] > 08. >>> f['age']=22 > 09. >>> print a > 10. [{'age': 22, 'name': 'dimon'}] > > I don't like result in the last like I've expected to have [{'age': 20, > 'name': 'dimon'}], how could i do this? > > I know that it must be as simple as using something like b[:], but what? When you append f to your list, you end up having *two* references to the same dictionary -- one of those references is f, and the other is a[0] -- but they both point to the *same* dictionary, meaning that changing it in one place affects it regardless of which way you access it. It's like you've given it a nickname. What you need to do, is add a *copy* of the dictionary to your list. import copy a.append( copy.copy(f) ) Now, the dictionary referred to by a[0] is independent of the dictionary pointed to by f, and you can change f without affecting the one at a[0]. There might be a slight complication if you have a mutable object (like a list or a class instance) as one of f's values, because f and f's copy will have references to a single copy of that object. (Same problem, one layer deeper.) This can be solved by using copy.deepcopy() instead of copy.copy(), which should recursively copy all of its argument's contents. Hope that helps... Jeff Shannon Technician/Programmer Credit International From guido at python.org Sat Mar 30 08:47:33 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 08:47:33 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type In-Reply-To: Your message of "Sat, 30 Mar 2002 05:57:39 EST." <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> Message-ID: <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> [David Abrahams] > 6) Should we eventually remove the inheritance relationship > between Int and Bool? > > I hope so. Bool is-a Int doesn't seem like the right relationship to > me, unless perhaps we make Int is-a Long... naah, not even then. Hm. In your favorite language bool is one of the integral types. Doesn't that imply pretty much the same thing? Anyway, do you have a use case where it matters? --Guido van Rossum (home page: http://www.python.org/~guido/) From robin at jessikat.fsnet.co.uk Mon Mar 4 13:36:46 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 4 Mar 2002 18:36:46 +0000 Subject: Win32 2.2 & 2.1.2 References: Message-ID: In article , Thomas Heller writes >"Robin Becker" wrote in message news:Uu$EsXAKB6g8Ew >Jf at jessikat.demon.co.uk... >> Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the >> default for a win32 box. It would allow us to dip a toe in the water >> without drowning. > >2 ways AFAIK: >1. Install 2.2, then 2.1.2 *again* > I guess that's the easiest way >2. Install 2.2, then change the file associations to use 2.1.2. > >Thomas > > -fumbling about in the dark-ly yrs- Robin Becker From donnal at donnal.net Tue Mar 12 13:52:31 2002 From: donnal at donnal.net (Donnal Walter) Date: 12 Mar 2002 10:52:31 -0800 Subject: Is Python an object based programming langauge? References: Message-ID: <918bc22f.0203121052.4e3a91c7@posting.google.com> drevenhaug at hotmail.com (Graz Bukanoff) wrote in message news:... > Is Python an object based programming langauge? I am a programmer by avocation only, not by profession or training, so you'll have to take this with a grain of salt. But I first started using object-oriented techniques nearly twenty years ago, implementing Object-Oriented Forth from Dick Pountain's book by the same name. I am currently working on a project in which I consider object-oriented principles (such as encapsulation and inheritance) to be crucial. Previously I tried to undertake this project in Visual Basic, Java with AWT, Eiffel, and Java with Swing in that order. I have accomplished more with Python and wxPython in six months than I did in six years with the other development environments. Does that make Python object-based or object-oriented? I don't know, but I know that I am happy with Python. Donnal Walter, M.D., Ph.D. Arkansas Children's Hospital From philh at comuno.freeserve.co.uk Thu Mar 28 20:55:17 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 29 Mar 2002 01:55:17 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA3AA98.2F94398B@activestate.com> Message-ID: On Thu, 28 Mar 2002 15:42:10 -0800, Cliff Wells wrote: >On Thu, 28 Mar 2002 15:43:20 -0800 >David Ascher wrote: >> May I suggest that you instead do: >> >> >>> class MyClass: >> ... def do_this(self): >> ... "this function would do this" >> ... def do_that(self): >> ... "while this function would do that" >> ... >> >>> >> >> and use the docstrings as a placeholder for the actions of the function >> -- typically something that's foremost in your mind when you're >> pseudocoding, and it counts as a statement as far as the parser's >> concerned (hence is syntactically valid), and at the same time, you've >> already got docstrings ready for you when you start to implement. > >Phil is trying to avoid having to backspace 4 times to delete a pass >statement. Why the hell would he want to type in an entire docstring??? Why would I want to write documentation anyway? :-) -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From SBrunning at trisystems.co.uk Wed Mar 13 11:06:39 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 13 Mar 2002 16:06:39 -0000 Subject: cgi xmlrpc anyone? Message-ID: <31575A892FF6D1118F5800600846864DCBCDFD@intrepid> > From: Robin Becker [SMTP:robin at jessikat.fsnet.co.uk] > Has anyone got a cgi version of an xmlrpc server? By that I mean a cgi > script which simulates being an xmlrpc server. We are allowed to do cgi > by our ISP, but not to run long running processes or to start up our own > servers etc. Robin, The effbot is running one, I think - . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From matt at mondoinfo.com Fri Mar 1 15:51:46 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Fri, 01 Mar 2002 20:51:46 GMT Subject: Ping References: Message-ID: On Fri, 1 Mar 2002 18:21:13 +0100, Riss Nicolas wrote: >Bonjour, Bonjour! >on ma dit que je pouvais ?crire en francais alors j'?crit en >francais. Of course it's reasonable to write in French here. I hope you will forgive me for replying in English because my French is sufficient for reading but rarely for writing. >Je voudrais pouvoir v?rifier toutes les 5 min que une machine ping >une autre machine et si elle ne ping pas qu'elle execute un >script. Comment faut il faire avec python pour pinger une machine et >v?rifier qu'elle r?pond?? Jeremy Hylton has Python code to do ping and traceroute at: http://www.python.org/~jeremy/python.html and my ping.py is at: ftp://ftp.visi.com/users/mdc/ping.py In order to open the raw socket that's necessary to send a ping, you'll need root authority under Unix and I don't think it's possible at all under Windows 9X. You might find it simpler or safer to use os.popen() to run your system's ping and parse its output. Andrae Muys points out in (wrapped for line length): http://groups.google.com/groups? selm=7934d084.0201081621.177c1c8e%40posting.google.com that it may also be possible to use an ordinary socket to connect to an ordinary port on the second machine and interpret any error message you get. You might have to experiment some to see what result was "normal" and what results represented errors. A bientot, Matt From tim.one at comcast.net Tue Mar 26 03:49:42 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 26 Mar 2002 03:49:42 -0500 Subject: list comprehension question In-Reply-To: <20020325155430.A27495@glacier.arctrix.com> Message-ID: [Neil Schemenauer] > PS. tell the bot I'm sorry I doubted the correctness of his code No problem, Neil! He had already projected both the depth and sincerity of your sorrow to six significant digits, and seemed quite pleased that doing so didn't exhaust his supply of available zeroes. He's off factoring primes again (I think he's on to something humans may have missed), so all is well. From gcordova at hebmex.com Wed Mar 27 10:57:20 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Wed, 27 Mar 2002 09:57:20 -0600 Subject: menu.add_command options Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689E1@SRM201002> > > Tkinter: > In the line: > > file_menu.add_command(label='Load Form', underline=0, > command=self.open_file) > > Does anyone have a list of options that go with the > menu.add_command? I > need to pass the frame to the method open_file, but I don't > know how to > pass that as an argument. The book I have Python and Tkinter > programming just says "options..." While I am all for a good mystery, > it is somewhat disheartening to find in a $50+ book. > Ahhh, Ye Eternal Callback Questions.... :-) THE most flexible solution I've ever used, involves using a callback class, where there's a __call__ method defined. That way, you create objects which can be called, just like functions. The nices part is that objects can carry around stuff which you can later apply during that invocation of the __call__ method. A simple class like this is enough for your purposes (maybe): class Callback: def __init__(self, function, *args, **kwargs): self.default_args = args self.default_kwargs = kwargs self.function = function def __call__(self, *more_args, **more_kwargs): # Create an updated argument tuple and kw-args dictionary. more_args = self.default_args + more_args more_kwargs.update(self.default_kwargs) # And call the function with all this stuff. self.function(*more_args, **more_kwargs) # If you're not using 2.x, then: # apply(self.function, more_args, more_kwargs) So now, you can: file_menu.add_command(label='Load Form', underline=0, command=Callback(self.open_file, FrameName, etc)) When the menu is invoked, the __call__ method of the object you passed as argument for "command=" above is called, which does the little mambo of calling the function you defined, with the default parameters you defined. Nice, eh? -gustavo From jonathan at onegoodidea.com Thu Mar 7 04:26:04 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Thu, 07 Mar 2002 09:26:04 +0000 Subject: PEP 284, Integer for-loops References: Message-ID: On 6/3/2002 16:41, in article eppstein-BB3186.08413106032002 at news.service.uci.edu, "David Eppstein" wrote: > One of the most common uses of for-loops in Python is to iterate > over an interval of integers. [...] Is it that common? I did a quick grep over the 2.2 library and found that around 10% of for loops used range. Of course, the library is pretty unrepresentative code since, by design, it contains all the stuff you *wouldn't* want to do yourself. I did the same grep over the random Python code in my projects directory and found that 3% of my for loops use range. This was 12 ranges out of 408 loops in about 18,000 lines of code. 12 times in the last 18,000 lines of code I've had to loop over a range. Am I unusual in saying that I really don't care? > The perceived lack of a natural, intuitive integer iteration > syntax has led to heated debate on python-list, and spawned at > least four PEPs before this one. [...] I keep getting the feeling that the "perceived lack" is from people who's perception is skewed by other languages. To a new programmer, teaching them that 'for' iterates over sequences and that 'range' makes sequences of integers is pretty easy (and yes, I used to teach). The problem only seems to be with programmers in other languages lamenting the lack of the BASIC, C, or whatever loop structures. If you're already a programmer then it shouldn't be that hard for you to adapt. If it is, then you were badly taught ;-) Jonathan From tejarex at yahoo.com Fri Mar 29 18:35:39 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 29 Mar 2002 23:35:39 GMT Subject: List problem References: <%l6p8.157527$2q2.12783856@bin4.nnrp.aus1.giganews.com> Message-ID: > or "c:/data/dict.txt" , which is both clear and safe. However, I > believe \d == d. Typo. I meant, \d == \d and not a control char like \a, \b, etc. From eric.brunel at pragmadev.com Wed Mar 13 09:24:10 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 13 Mar 2002 14:24:10 +0000 Subject: Tkinter: memory loss for tag bindings in Canvas Message-ID: Hi all, We've noticed a memory problem when doing multiple item deletion, (re)creations and tag bindings in Tkinter canvases. When monitoring the occupied memory of the following code: -------------------- from Tkinter import * root = Tk() c = Canvas(root) c.pack(side=TOP) def p(event): print 'beans' def foo(): for i in range(1000): c.delete(ALL) tId = c.create_text(100, 100, text='spam') c.tag_bind(tId, "", p) Button(root, text="Go", command=foo).pack(side=BOTTOM) root.mainloop() -------------------- we saw that every time we clicked on the "Go" button, the memory taken by the program significantly increased. Quite obviously, it shouldn't: the end state is exactly the same than the start state. Removing the "c.tag_bind" line solves the problem. This happens on Win2K, Linux (Mandrake 8.0) and Solaris 2.7. The same program written in tcl/tk doesn't result in memory loss, and deleting the bindings with for item in c.find_all(): for seq in c.tag_bind(item): c.tag_unbind(item, seq) at the beginning of the "foo" function doesn't help. I've looked into the Tkinter module and found that a new tcl command is being created for each binding. My guess is that for some reason, this command doesn't get properly deleted when the item is deleted or the binding destroyed. Does anybody has a solution or workaround for this problem? TIA - eric - From tim.one at comcast.net Mon Mar 4 19:58:52 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 04 Mar 2002 19:58:52 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: <7xy9h8pt9x.fsf@ruckus.brouhaha.com> Message-ID: [Paul Rubin] > I get the OverflowError under Red Hat 7.2 with the default Python 2.2 > build, which appears to not use -lieee. The configure script's > test for __fpu_control in -lieee appears to never be run when > you type "configure". I manually put "-lieee" into the LIBS=... > line in the makefile and rebuilt. Now I get: > > [phr at localhost Python-2-2]$ ./python > Python 2.2 (#2, Mar 4 2002, 01:31:37) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> 1e-200**2 > 0.0 > > so the behavior changes with -lieee. Cool! Thanks for the info. It's been recorded as a comment attached to >> Unfortunately, the C standard (neither one) isn't a lick of help here -- >> error reporting from C math functions is a x-platform crapshoot. > That seems to me to be a deficiency in the C standard--IEEE 754 > defines these different error modes because they're all important, and > any high level language that claims to be good for serious numerics > should give precise control over the error modes. I don't know of any high level language that does in a portable way. If vendors choose to implement the optional 754 gimmicks in C99, then such vendors' C99 implementations will come close. Short of that, you have to dig thru your favorite language+vendor+platform combo's extensions. From damononnews at hotmail.com Mon Mar 4 20:10:53 2002 From: damononnews at hotmail.com (Damon Lynch) Date: 4 Mar 2002 17:10:53 -0800 Subject: Black Adder and PyQt References: <3C80B1E3.575761B7@river-bank.demon.co.uk> Message-ID: Andrew Brown wrote in message > Yes, but _when_ will the final version be released? I'm not sure about the final, but the next beta is quite close. It is still being developed. Are you on the blackadder mailing list? Damon From bosahv at netscapenospam.net Sat Mar 9 12:41:03 2002 From: bosahv at netscapenospam.net (Bo Vandenberg) Date: Sat, 09 Mar 2002 17:41:03 GMT Subject: pyperl -- Arrays to Lists? ...Tuples? References: Message-ID: I think its most considerate to share a solution with the rest of the newsgroup. Many people who bring unique questions might find the answer themselves or somewhere other than the newsgroup. Speaking, mostly as a lurker, I appreciate you taking the time to bring back the solution you found. thanks. From furballphat at despammed.com Sat Mar 30 12:27:54 2002 From: furballphat at despammed.com (Adam C.) Date: 30 Mar 2002 09:27:54 -0800 Subject: piddle on xdarwin Message-ID: I recently got a copy of fink, xdarwin, python etc. It all works beautifully, but now I want to stop printing prime numbers to the stdout and actually draw things. I downloaded a copy of piddle and installed it. It installed fine and the modules can be imported etc. Unfortunately, when I run the test files nothing happens. There is no error, but no window pops up either. I have tried this with several back ends, but none work. Does anyone have any advice? From junkster at rochester.rr.com Sun Mar 17 16:56:15 2002 From: junkster at rochester.rr.com (Benjamin Schollnick) Date: Sun, 17 Mar 2002 21:56:15 GMT Subject: Eliminate Spam Now... >g< Python w/DNS/&POP3 Message-ID: Folks, I'm running into a slight problem... I'm attempting to use the (py)DNSlib (sourceforge project), to look up Spammers via ORBZ (or similiar group)... And I'm able to pull up the DNS information, but every entry I try response with a valid root level DNS entry.... Can anyone enlighten me regarding the operations of the black hole lists? I can't seem to find any of the sights that explain the actual functionality. (I've tried reversing the octets [i.e. 13.175.214.14 == 14.214.175.13], with no luck) = Benjamin From gmcm at hypernet.com Fri Mar 29 08:26:07 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 29 Mar 2002 13:26:07 GMT Subject: win32com client and McMillan installer 5.3b1 References: Message-ID: [posted and mailed] Francis Meyvis wrote: > Hello, > > I found a miserable work around. > The pythoncom16.dll is somewhere under the WINNT. > I copied this as pythoncom.dll and the thing now works. You should *not* rename it (pure Python can import it, but C code won't be able to). Of course, you shouldn't have to do anything. [from earlier msg] >> I've a bunch of python scripts that I'd like to convert into and exe. >> This works well with the McMillan Installer except the script that >> uses the win32com client stuff to access worksheets in an excell >> document. From the traceback I see that there's an import error: >> "No module named pythoncom" >> >> I tried it with McMillan installer 5.3b1 on >> NT5 with python 2.2 and Mark Hammond's associated win32 extentions >> NT4 with python 1.6 and Mark Hammond's associated win32 extentions I don't have Mark's extensions for Python22, but I just built the testMSOffice.py test in e2etests/win32 without problem on Python21 and Python 1.5.2 (using 5b3.1). I can think of 2 things that might cause your problem: - you don't really have the win32 extensions installed (which you do, so that's not it) - rthooks.dat is missing or trashed >> Both give me the same result. >> >> Can someone point me to what I'm doing wrong? >> I did a >> p22 Makespec.py --name=tst script.py >> p22 Build.py script.py I think you mean "p22 Build.py tst.spec", right? >> I have some warnings about a delayed __import__ >> According to the doc these have to be taken serious. >> But the doc does not explain in a clear way to me >> what I should do about it. >> Extend the path?, add the modules manually to the spec file? For this you shouldn't have to do anything. It should all be taken care of by rthooks.dat and the scripts in support/rthooks. -- Gordon http://www.mcmillan-inc.com/ From sholden at holdenweb.com Thu Mar 28 11:52:44 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 28 Mar 2002 11:52:44 -0500 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: [posted & mailed] "Ken Peek" wrote in message news:3ca33c88 at news.mhogaming.com... > Well-- OK, my new ISP doesn't have a news server, but I found one > that I could use to post this with. If you reply to my email, do > the 'nospam' thing first to my email address... > > I really am interested in what people think about this. I have > looked at all the other c.l.py posts on this construct, but I > don't think anyone proposed this format. > [ ... ] > > How about: > > match some_object: > > ("I dream of Jeanie",): > print "with the light brown hair" > > (1,3,5,7): > > print "some odd numbers" > > # 'break' leaves the entire match structure > if (time_to_leave): break > > # 'continue' jumps to the first > # statement in the next clause > continue > > (123,456,789): > > print "some bigger numbers too" > > (19,56,22): > > print "some random numbers" > > (1001,2002,3000): > # YES! It IS possible we want to do NOTHING! > pass > > any: > print "we got here because there were no matches" > > This is kind of a neat construct because you can put multiple > tests on one line, and it doesn't look too messy (like C's > 'switch' would look.) Also-- we are not limited to matching up > only integers. This is very clean code compared to a long string > of "if/elif/elif/elif/else" clauses... I like READABLE code-- > which is why I like Python! > > Note that the aggregate of the tuples must have unique values and > types-- (this allows for efficient implementation, and for future > optimization.) A match is found only when BOTH the type and > value are the same. 'some_object' can be any object, but it > would be wise to not use floating point numbers or other things > that do not guarantee a valid '==' compare. I suppose these > ambiguous types could be flagged with an error from the compiler, > but I would hate to see a run time check (which would slow things > down, just to accommodate a bad programmer.) > > The match clauses do not 'fall through' automatically like a "C - > switch" statement-- (this is the source of many errors in 'C'.) > A clause can be forced to 'fall through' with the use of a > 'continue' statement, which jumps to the first statement in the > next match clause (because 'falling through' IS useful > sometimes.) I suppose the interpreter/compiler could flag an > error "UnreachableCode" (or 'BadIndentation') if 'continue' was > used by itself, and there were statements after it at the same > indentation level... > > The 'any' keyword could be changed to 'else' I suppose, but I > think the word 'any' "just plain sounds better when you say it", > and I like the 'match' keyword better than anything I have seen > or can think of... > [ ... ] Well I don't know how easy it would be to introduce this from a syntactic point of view. Others will probably comment on that. Your example uses only constant (literal) values. This obviously makes it possible to guarantee that the tuples do not overlap at compile time, but is very restrictive. Was this intentional, or would your scheme also allow match some_object: (something_else): pass (this, that, the_other, 42): complex_processing This would be more flexible, but might make it necessary to accept "firsty matching value". You will find there is considerable resistance to adding new keywords, due to their propensity to break existing code (for example, I have some programs that use match as a variable name, and the re module uses it as the name of a method). regards Steve From James_Althoff at i2.com Mon Mar 4 20:14:24 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 17:14:24 -0800 Subject: Status of PEP's? Message-ID: James Althoff wrote: > [James Altfhoff] > > they can > > >>> -3 .__abs__() > > -3 > > >>> > > True. But your (aka *my*) point would probably be better made with > > >>> (-3).__abs__() > 3 Please learn to type my (aka *your*) own name correctly. (You realize, of course, that you committed this typo in a message in which you were *already* talking to yourself about a typo). Jim From h_schneider at marketmix.com Mon Mar 11 10:19:48 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Mon, 11 Mar 2002 16:19:48 +0100 Subject: DBgrid in python References: Message-ID: DBgrid in pythonwww.wxpython.org www.wxpython.org You have to install both to get a GUI ... Bye, Harald "Alves, Carlos Alberto - Coelce" schrieb im Newsbeitrag news:mailman.1014054238.12896.python-list at python.org... Is there any component in python as DBGrid component in Delphi?! If so, where can I get it?! Thanks, Carlos Alberto COELCE/DPRON-Departamento de Projetos e Obras Norte Fone: 677- 2228 e-mail: calves at coelce.com.br \|||/ (o o) --ooo0-(_)-0ooo-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreed at capital.edu Fri Mar 15 20:37:59 2002 From: dreed at capital.edu (Dave Reed) Date: Fri, 15 Mar 2002 20:37:59 -0500 Subject: pythonic way of depth first and breadth first tree iterators Message-ID: <200203160137.g2G1bxJ20471@localhost.localdomain> We're planning to use Python in our CS1 and CS2 courses next year so I'm beginning to think about the issues for these courses. http://www.python.org/doc/current/lib/typeiter.html states: If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) I don't quite understand exatly what that is saying - what would be the pythonic way of defining/calling separate breadth first and depth first iterators for a binary tree class - i.e., is there a way to indicate which method to use when you make the call to iter() so that I could do something like: for node in tree('depth'): and for node in tree('breadth'): Or is that just implying that I can make a depth first class iterator class and breadth first iterator class that both support the corresponding next() method and do something like: d = DepthIter(tree) for node in d: where DepthIter is a class that takes a tree as a parameter to its constructor and has a next() method that returns the nodes in a depth first manner. And similarly, write a BreadthIter class? Thanks, Dave From tim at vegeta.ath.cx Fri Mar 8 01:45:50 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Fri, 08 Mar 2002 06:45:50 GMT Subject: why is python slow? References: Message-ID: les ander graced us by uttering: > i am just curious as to why different programming languages have > different speed. [ snip ] > why is a perl program faster than similar python program? Oh dear. You said the P-word. The four-letter P-word. Nothing stigmatizes a comp.lang.python thread faster than bringing up Perl. However, your statement is far too subjective. Differences in execution speed between any two languages often depend much more on the knowledge, wisdom, and experience of the programmer than on which language is used. OTOH, Perl is optimized for certain things, and Python is optimized for others. Finally, words like "faster" and "similar" are far too subjective to get an accurate answer. If, however, you were to ask: Why does a hypothetical benchmark show shorter execution time for #/usr/bin/perl -w print while <>; than for the roughly functionally equivalent Python code #!/usr/bin/python import fileinput for line in fileinput.input(): print line, ??? TIA, J. R. Hacker ...you might find out that this is one particular area where Perl has been specifically optimized. > For example > when java came out it use to be pretty slow, but now it is pretty fast. How > was this speed-up acheived and why is it not possible to have such a speed up > for python? How this speedup was achieved is a problem I leave for Sun. However, the _reason_ this speedup was sought was because Java had gotten such a bad rep for being slow in the past. And so, industry competition once again achieves improvement through pressure. BTW, this is the same reason Perl implemented a (crufty) object system: user demand. > P.S. I am just trying to understand and do not intend to put down > python by any means. Understood. But the trick, as always, is not finding the right place to get an answer, but rather, knowing _which_ question to ask in the first place. HTH Tim Hammerquist -- You can lead a bigot to water, but if you don't tie him up, you can't make him drown. -- The Psychodots From h.jehadalwan at student.kun.nl Thu Mar 7 13:24:56 2002 From: h.jehadalwan at student.kun.nl (husam) Date: Thu, 07 Mar 2002 19:24:56 +0100 Subject: Python and computer graphics References: <3C8785EA.5010509@student.kun.nl> <1015517388.720858@news.commspeed.net> Message-ID: <3C87B078.2050806@student.kun.nl> Tom Babbitt wrote: > "husam" wrote in message > news:3C8785EA.5010509 at student.kun.nl... > >>hi, >>can anybody points me to usefull resources (books, urls) about using >>python for computer graphics that help for building skills in this >>subject from scrash? >> >>thanks in advance >> >> > A long time ago I read a book simply titled 3D computer graphics, I think it > was by some of the folks at pixar. My philosophy is not to spend too much > time at the bottom but go right to the top, check out > > http://www.linmpi.mpg.de/dislin/ > > http://mayavi.sourceforge.net//index.html > > http://pygame.seul.org/ > > Tom Babbitt > > > > > I was wondering whether it is possible to create graphics objects without the use of a external module. Imagin that you build an application and want to let other people use it. People have to install python, then the extra module. The chance that my program finds its way to clients screens is not so big. From python at rcn.com Wed Mar 6 12:12:23 2002 From: python at rcn.com (Raymond Hettinger) Date: Wed, 6 Mar 2002 12:12:23 -0500 Subject: [OT] Want to recognize pictures using Python References: Message-ID: Yes, PIL is a good choice. It has primitives that solve your problem directly: im.open() loads the image from almost any standard file format im.split() will generate the three R,G,B color separations im.resize() can shrink the images to 2 pixels by 2 pixels (a pixel per quadrant) im.getdata() will give you the element Python lists of the average quadrant values Raymond Hettinger "F. GEIGER" wrote in message news:a655p5$82t$1 at rex.ip-plus.net... > I plan to buy a USB camera (hope, they are not too expensive) to play a bit > with image analyzing. Nothing sophisticated, just color recognition: I'd > like to be able to tell whether the upper half of a picture has mostly the > color green or red or the lower left quarter of an image is mostly blue etc. > > I'm completely new to this topic, but really would like to do this in > Python. > > Does anyone know of a package capable of providing such services? As said > already, preferably for use in Python programs. PIL comes to my mind here. > Is PIL the right one to start with in this regard? > > > Thanks and best regards > Franz GEIGER > > > > From tdelaney at avaya.com Sun Mar 24 18:19:07 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 25 Mar 2002 10:19:07 +1100 Subject: two ideoms at one blow: line-reading and regexp-matching Message-ID: > From: Clark C . Evans [mailto:cce at clarkevans.com] > > I'd note that good "C" style is to always put the constant > as the LVALUE in this way the above looks "funny". In > other words when checking for equality in C, write "if (3==a) {" > this way if you forget the extra = you don't shoot yourself > in the foot (it is a syntax error). A good lint program > should be able to flag these cases for you. After a while > any equality test where the variable is on the left just > "looks funny"... if (b = a) { } Where's the constant? Tim Delaney From martin at v.loewis.de Thu Mar 21 01:18:50 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Mar 2002 07:18:50 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: Anthony Baxter writes: > Because Greg Ward burned out on it, and no-one's been willing to step up > and continue work on it. Note that "unmaintained" is a bit strong - bugs > are going to be fixed I'm not so sure about this. At the moment, there are 10 unreviewed patches (although those dating April 2001 have seen some recent progress); there are 15 open bug reports, the oldest one dating March 2001. Since March 2001, 30 distutils bugs have been closed, so one out of three distutils bugs is still pending (for Python in general, the ratio is 1:9). Regards, Martin From spex66 at web.de Fri Mar 8 08:30:18 2002 From: spex66 at web.de (spex66) Date: Fri, 8 Mar 2002 14:30:18 +0100 Subject: print >> details??? Message-ID: Hi there, I've tried this simple code (python 2.1.1 activestate): class x: def write(self, s): print 'START' print s print 'END' print >> x(), 'Hello' and got following result: START Hello END START END where does the second call of x.write() come from??? thanks for any hints Peter (=PA=) From kp87 at lycos.com Fri Mar 1 13:49:31 2002 From: kp87 at lycos.com (kevin parks) Date: 1 Mar 2002 10:49:31 -0800 Subject: C/C++ to Python translater Message-ID: <5e8bd451.0203011049.5d12d3a2@posting.google.com> Is there a translator to automatically port (rewrite) code snippets from C or C++ to Python? I have some old C code that i have been porting by hand (well by head really) and i was wondering if there were any translation utilities that i could try. I imagine that this would be a monster AI undertaking, Btu with Python's powerful built-in types i am guessing c --> Python is easier than the opposite. Just wondering... From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Thu Mar 28 03:53:23 2002 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Thu, 28 Mar 2002 09:53:23 +0100 Subject: Random... References: <%slo8.20800$cB5.20607@atlpnn01.usenetserver.com> Message-ID: Erno Kuusela schrieb in Nachricht ... >In article <%slo8.20800$cB5.20607 at atlpnn01.usenetserver.com>, "Steve >Holden" writes: > >i think it's good to remind people of this occasionally. while it may >waste time for most people, it also lets newbies learn the ways of >netiquette without having to be chastised invividually by email. > Especially as this silly Outlook Express strongly suggests top posting by placing the cursor at the beginning and inserting an empty line. So somebody _has_ to tell the newbie not to write at this point. (That somebody might be common sense, of course.) Koczian --- Dr. Sibylle Koczian Universitaetsbibliothek , Abt. Naturwiss. D-86135 Augsburg Tel.: (0821) 598-2400, Fax : (0821) 598-2410 e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From erno-news at erno.iki.fi Sat Mar 9 09:50:00 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 09 Mar 2002 16:50:00 +0200 Subject: why is python slow? References: Message-ID: In article , Erno Kuusela writes: | i think one optimization was that [...] upon re-reading, it looks like this is probably the same idea that i snipped from Fernando Pereira's message. d'oh... -- erno From cimarron+google at taylors.org Sun Mar 10 23:42:32 2002 From: cimarron+google at taylors.org (Cimarron Taylor) Date: 10 Mar 2002 20:42:32 -0800 Subject: Modulo operator : differences between C and Python References: <3C8BE537.74E55963@mega-nerd.com> Message-ID: <29e28c51.0203102042.76ac31b7@posting.google.com> > Anybody have any idea why this is? > Erik I encountered this as well in an application which needed to verify the results of a C program. Python seems to be counting "down" from y if x<0. I simply compensated for this with the following function: def mod(x,y): m = x%y if m==0 or x>0: return m return m-y Another thing to watch out for when comparing results from Python and C include is overflow/underflow behavior of the math operations. Cim From peter at engcorp.com Fri Mar 29 11:16:05 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 11:16:05 -0500 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: <3CA49345.CDA81C49@engcorp.com> Benjamin Schollnick wrote: > > We have the IF .... ELIF statement structure, which can be used to > simulate a case statement, but it is not as clear nor as neat as > the case statement. > > IF X == 0: > DO_THIS () > ELIF X == 2: > DO_THIS (2) What language is this? It has a style similar to Python, with the colon and indentation marking blocks, but Python doesn't have the keywords IF and ELIF. (Case-sensitive!) (You were probably trying to make it more readable or something. Please don't -- it makes it less readable to those familiar with reading Python.) -Peter From surajsub at netscape.net Mon Mar 18 12:55:18 2002 From: surajsub at netscape.net (Surajsub) Date: 18 Mar 2002 09:55:18 -0800 Subject: Help Required References: Message-ID: Chris Liechti wrote in message news:... > surajsub at netscape.net (Surajsub) wrote in > news:cf4a8ef1.0203151724.440b67ac at posting.google.com: > > Hi, > > I am a newbie to Python and am pretty fascinated by it power and > > speed. > > Welcome > > >I am however puzzled in trying to write this script. > > The script builds a list of userids to be fed to ldap and it is > > supposed to be > > > > uid1,uid2,uid3....and so on.( Notice there is no space) > > > > However when i am trying to create the uid list it gives > > > > uid1, uid2, uid3,...and so on. > > how do i get rid of this leading space if u would call it.. > > string.lstrip does not work either. > > i don't see what you're doing. please post some example code alomg > with such questions. however some guesses: > > if you have a list of numbers: n = [1,2,3,4] > you can make string of it using: ','.join(map(str,n)) > > or are you parsing the numbers from a string? then you could try: > >>> import string > >>> n = map(string.strip, '1, 2, 3, 4'.split(',')) > > and if want numbers instead of strings in the list: > >>> n = map(int, '1, 2, 3, 4'.split(',')) > > (*) "map" is simply calling the 1st argument (a function) with each > element of the list 2nd arg and saves the result in a list which it > returns. > you can achieve the same with a "for" loop over the list and saving > the result in an other list, but i find the "map" is very elegant. > > chris Ok here is the code..I just need a set of uid's and other similar parameters which i need to feed to ldap.these are just a dummy set of values. ============================================================= #!/usr/local/bin/python import string MIN=0 MAX=25 UID="UID" val="" for x in range(MIN,MAX,1): if( x == 0 ): x=str(x) val=UID,x+',' st=string.join(val,"") st=string.strip(st) print st, elif(x > 0 ): x=str(x) val='UID'+x+',', st=string.replace(string.join(val,""),' ','') print st, ========================================================== The output that this script produces is UID0, UID1, UID2, UID3, UID4, UID5, UID6, UID7, UID8, UID9, UID10, UID11, UID12, UID13, UID14, UID15, UID16, UID17, UID18, UID19, UID20, UID21, UID22, UID23, UID24, Notice the spaces between the , and the UID ============================================ I need to get rid of these spaces.How do i do it.. Thanks From helmut.zeisel at aon.at Thu Mar 7 11:01:26 2002 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: 7 Mar 2002 08:01:26 -0800 Subject: SWIG and abstract base class Message-ID: I want to use SWIG to create a Python module for a C++ class hierarchy using abstract base classes: %module mymodule %{ #include "base.h" #include "derived1.h" ... %} class Base // Abstract base class { public: // many common methods .. }; class Derived1 public Base { public: // special methods .. }; In the created C++ code, I get error messages like "cannot instantiate abstract class due to following members:" Is there any possibility to tell SWIG that Base should be treated as abstract class? What could be a workaround (except of repeating all the base class methods in every derived class)? Helmut From tanzer at swing.co.at Sat Mar 2 02:34:47 2002 From: tanzer at swing.co.at (Christian Tanzer) Date: Sat, 02 Mar 2002 08:34:47 +0100 Subject: Minor, minor style question In-Reply-To: Your message of "01 Mar 2002 10:39:42 CST." <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: claird at starbase.neosoft.com (Cameron Laird) wrote: > Why would I prefer > string = "" > string = string + "abc " > string = string + "def " > string = string + "xyz" > over > string = "abc " + \ > "def " + \ > "xyz" > ? Why not use: string = ("abc" "def" "xyz" ) for constant strings, and string = "".join((abc, def, xyz)) for variable strings? Both are more robust, way more efficient, and (to me, at least) easier to read. BTW, beware of: result = "" for s in ... : result = result + mumble(s) For many elements, this gets really slow. Appending to a list and joining at the end is much faster. -- Christian Tanzer tanzer at swing.co.at Glasauergasse 32 Tel: +43 1 876 62 36 A-1130 Vienna, Austria Fax: +43 1 877 66 92 From op73418 at mail.telepac.pt Tue Mar 5 14:07:23 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Tue, 05 Mar 2002 19:07:23 +0000 Subject: Status of PEP's? References: <7xwuwrofhk.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 04 Mar 2002 19:59:03 -0800, David Eppstein wrote: >In article <7xwuwrofhk.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > >> Usually the term "natural numbers" don't include zero. >> http://mathworld.wolfram.com/NaturalNumber.html > >I think "usually" is an exaggeration. For instance, a better authority >than Weisstein, Ebbinghaus et al's _Numbers_ (Springer Graduate Texts in >Mathematics 123, 1991, p. 14) disagrees As a practising/learning mathematician I always understood natural numbers to include the 0. From db3l at fitlinxx.com Fri Mar 29 20:38:45 2002 From: db3l at fitlinxx.com (David Bolen) Date: 29 Mar 2002 20:38:45 -0500 Subject: Python+wxWindows as Visual Basic replacement? References: Message-ID: "Robb Shecter" writes: > Python per se isn't the issue - what I'm not sure about is what the > development and deployment experience is like, when using these parts, taken > together. One caveat to get out of the way first - if it's a pure GUI front end to database access, development will still be easier in the VB IDE for GUI design, layout and so on. You can improve on the Python side by trying something like Boa, or the commercial wxDesigner for the dialogs, but it's not really quite up to VB IDE levels yet. There are other IDE choices too for Python, but not many that attack the GUI layout issue. Personally, I just code directly in Python without any special GUI designer, but that's how I've always done GUI coding - getting some junior folks in my office who previously used VB to use Python has been ok for non-GUI stuff, but they are clearly more productive in GUI design under VB. Of course, with the exclusion of GUI layout, Python, the language, is IMHO superior to VB, although with a nice collection of components you can get a lot of the same high level data constructs for use in VB too. But I find Python development itself more robust. With the above caveat, the actual output of a Python+wxPython application is just fine. Looks and feels native, performs great, and so on. We're using it in a number of internal applications, and at least one external application with others to follow. And there are some benefits to the wxPython approach over VB that may not be immediately obvious. When we evolved a simulation application from a VB version into a later Python version, since the new GUI was designed in wxPython with sizers, the primary screen that had been a fixed size in the VB application, became resizeable "for free". There are third party controls to try to do this to a VB form, but it takes some work and isn't the normal way of doing it in VB. For deployment, we've used two approaches. For our primary distributed system (system installations across the country), Python was made part of our standard system installation, including wxPython. So any Python scripts or applications we develop for use on the systems are simply deployed directly as Python source (or pyc files if we want to save space). The same mostly holds true for our internal machines where our support group or internal users can install Python. For general external deployment, we use the packaged approach (I use a combination of Installer and InnoSetup, but py2exe is fine too). True, it includes its own copy of the Python DLL and support files, but it's guaranteed to work on the target system independent of any prior installation, and it behaves just like the windows setup of an application the users expect. I've even taken this approach for a couple of internal use (even non-GUI) tools that needed to be executed on a few machines on which we weren't planning on installing Python, so I could just copy the output distribution directory from Installer to the target systems. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From martin at v.loewis.de Sun Mar 3 15:40:41 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 03 Mar 2002 21:40:41 +0100 Subject: Why isn't pychecker mentioned prominently? References: <3C80ED0B.42292C99@tds.net> Message-ID: "Edward K. Ream" writes: > I just found out about pychecker (http://pychecker.sourceforge.net/) and > I am wondering why it isn't mentioned prominently all over the Python > web site: the tutorial, the links on the left and side of the home page, > topics guides, general reference etc. Two reasons: a) it is mentioned prominently. Guido mentioned as hist favourite tool both in the proceedings and his keynote at IPC10. It can't get more prominent than that, in the Python world :-) b) because it is fairly new, and evolving c) because nobody submitted patches to the tutorial. (you always get three reasons in a message that says it will give two reasons :-) Regards, Martin From gh_pythonlist at gmx.de Fri Mar 1 21:04:53 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Sat, 2 Mar 2002 03:04:53 +0100 Subject: Can use python to play MP3 file? In-Reply-To: <3c7ec28f$0$27085$4c41069e@reader1.ash.ops.us.uu.net> References: <3C7E6328.6050500@bigfoot.de> <3c7ec28f$0$27085$4c41069e@reader1.ash.ops.us.uu.net> Message-ID: <20020302020453.GD3201@lilith.hqd-internal> Le 28/02/02 ? 16:52, Tim H ?crivit: > "Gerhard H?ring" wrote: > > Ricky wrote: > > > I hear that PHP can online play MP3 file. Is there any method that > > > can make me play MP3 by using Python CGI? > > > > > > Thanks for any reply! > > > > Do you want to play the MP3 file on the server, like a jukebox. Or do > > you want to stream MP3 files back to the client computer? > > > > (Of course you can do both with Python) > > > > Gerhard > > Do you have examples, links, hints to doing each with python? Playing an MP3 file using pygame (http://www.pygame.org/): import pygame.mixer as mixer mixer.init(44100) mixer.music.load("White Bird.mp3") mixer.music.play() mixer.music.get_busy() print "Press enter to quit." raw_input() OTOH streaming MP3 files from the server to the client has IMHO little to do with Python, it's more of a HTTP thing. As long as you've set the correct content type and played the right tricks with HTML, it should just work. FWIW, there's a streaming MP3 server written in Python at Sourceforge: http://edna.sourceforge.net/ Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 4.0 ?C Wind: 3.2 m/s From cliechti at gmx.net Wed Mar 13 16:39:00 2002 From: cliechti at gmx.net (Chris Liechti) Date: 13 Mar 2002 22:39:00 +0100 Subject: telnet References: Message-ID: "M.Beis" wrote in news:a6obko$743$1 at kinder.server.csc.liv.ac.uk: > I'm connected to a network with a number of telnet servers. I want > to get a list with the names (hostnames) of each availiable server. that would be a network scanner(*) - and most likely something your sysadmin doesn't like to see. isn't there a list available somewhere in your net. loading alist of IPs from a file is simpler and faster. chris (*) brute force method: get your own IP and netmask then try to connect to each IP in your subnet on the telnet port. as sayed above most administrators don't like scanning and it could have consequences on your career. -- Chris From phd at phd.pp.ru Tue Mar 12 05:22:46 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 12 Mar 2002 13:22:46 +0300 Subject: IDv2/IDv3 Tag on mp3-files In-Reply-To: ; from mail@andreas-penzel.de on Tue, Mar 12, 2002 at 11:11:26AM +0100 References: Message-ID: <20020312132246.B11831@phd.pp.ru> On Tue, Mar 12, 2002 at 11:11:26AM +0100, Andreas Penzel wrote: > Is it possible, to read the IDv2 or IDv3 Tag from mp3-files? http://www.id3.org/implement.html http://csl.cse.ucsc.edu/~ben/python/ https://sourceforge.net/projects/pyid3/ Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From brian at sweetapp.com Sat Mar 9 17:00:58 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 9 Mar 2002 14:00:58 -0800 Subject: Newbie question In-Reply-To: Message-ID: <00a101c1c7b5$e50088b0$445d4540@Dell2> > How do you get the ordinal value (ASCII) of a character? For example, to > make a ROT13 program. You use the built-in function "ord". e.g. >>> ord('a') 97 Cheers, Brian From kragen at pobox.com Thu Mar 14 16:50:37 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 14 Mar 2002 16:50:37 -0500 Subject: [q]Mouse event References: Message-ID: <834rjin7iq.fsf@panacea.canonical.org> "John" writes: > Is there any way to record Mouse events (click, double click, and etc.) on > the applications running, using Python? What platform are you using, nobody at nobody.com? From mwh at python.net Thu Mar 21 06:59:15 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 21 Mar 2002 11:59:15 GMT Subject: __file__ for relative imports References: <2OVMEJA7kKm8EweI@jessikat.demon.co.uk> Message-ID: Robin Becker writes: > Is there an obvious reason why modules imported from the current > directory don't have an absolute pathname for __file__? No. I think there's a bug on sf about this. It would be a bit of a pest to implement, I think, but I may be missing something. Cheers, M. -- Two decades later, well-known hacker Henry Spencer described the Perl scripting language as a "Swiss-Army chainsaw", intending to convey his evaluation of the language as exceedingly powerful but ugly and noisy and prone to belch noxious fumes. -- the jargon file From jrchaff at mcn.net Wed Mar 13 15:08:46 2002 From: jrchaff at mcn.net (jrc) Date: Wed, 13 Mar 2002 20:08:46 GMT Subject: Why Don't Scripts Run ? References: <3C8F9C59.F9408D47@mcn.net> Message-ID: <3C8FB1E0.C0E0C6E7@mcn.net> I apologize for earlier comments. I find Python 2.2 will run scripts in Windows (Dos prompt) IF the inter- preter has not already been launched. This is clearly the reason each scriptname is prefixed by 'python'. The confusion is that this small point is completely overlooked in the documentation, including Fehily's book. A newcomer gets the impression that one starts the interpreter, THEN types 'python script.py', which leads to the errors I initially experienced. It is worth changing the documentation. I am sure I'm not the first (by far) to stumble on this and it is quite frustrating. jrc -------------------------------------------------------------- jrc wrote: > Hi - I'm a reasonably experienced programmer. I work in > Windows (ME). Thinking to give Python a try, I downloaded > v22 and installed. At first, it looks good, but then, I discover > it seems impossible to get any scripts to run in the command > prompt, using any available documentation whatever. I even > have Chris Fehily's book - essentially none of his examples > work with scripts from command prompt; yet this is a 2002 > book . (?!!) > > I do have the path set (and yes, rebooted, etc) - I checked it. > It includes both the installation directory and the working > directory. I started the cmd line prompt using the provided > icon, and also via a Dos Prompt (again, with proper path set), > followed by 'python'. The interpreter starts up just fine and > works ( >>> 2 + 2 -> 4 , etc). But, with a script in the > current directory (on the path too), a command, > > 'python script.py' > > completely fails (syntax error). This is the only way I > know - following the Fehily book and the sparse comments > in Python documentation - to execute scripts from the cmd > line. If v 22 is somehow different, it would be very nice to > point out to (potential) users. I've also tried every permutation > of this procedure that I can reasonably imagine - with the > same result. > > The only way I am able to get scripts to run (without which > python is just a toy) is to use 'Idle', load the file via "File Open", > then in THAT window, execute it, (!!), then back in the cmd > line I have to issue yet another command to get the prompt > back. This is essentially an unusably awkward procedure, > for my use. So unless there is some reasonably convenient > way to run scripts, python has no value to me at all. > > I would very much appreciate someone telling me which un- > documented point(s) I am missing. Thanks, > > jrc From cliechti at gmx.net Tue Mar 5 16:04:48 2002 From: cliechti at gmx.net (Chris Liechti) Date: 5 Mar 2002 22:04:48 +0100 Subject: Problems importing anything using _socket References: Message-ID: h.e.w.frater at cs.cf.ac.uk (Hugh) wrote in news:e2e9e807.0203050335.65ca52f4 at posting.google.com: > Hi all, > I'm totally new to python, but have decided to use it to do a welcome > first year uni project. I've got to develop a web based library. > I'm using oracle with the DCOracle2 module, and that works fine. > But I can't import anything that uses _socket. If I try and do an > "import cgi" frok inside the interpreter, I get this message: >>>> import cgi > Traceback (most recent call last): ... > File "/usr/local/lib/python2.2/socket.py", line 41, in ? > from _socket import * > ImportError: No module named _socket >>>> import cgi >>>> > > However, As you can see from above If I then type and run the line > "import cgi" again, it forks fine. Any ideas? no it doesn't work. the module is half initialized in the module- cache. it's only loaded gain when you type "reload(cgi)" and it will certainly print the error again. "_socket" is a .so file that should be in some subdirectory of your python installation. Seems that your installation is broken. you seem to be on an Un*x/Linux, i can't help you there - every thing worked fine on my Debina machine. maybe some other has an idea. (i would try the configure/make/make install dance again, but i'm also a winblows user ;-) chris -- Chris From bokr at oz.net Wed Mar 13 20:55:03 2002 From: bokr at oz.net (Bengt Richter) Date: 14 Mar 2002 01:55:03 GMT Subject: Is Python an object based programming langauge? References: Message-ID: On Wed, 13 Mar 2002 13:59:28 +0100, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: >On 11 Mar 2002 07:31:55 -0800, drevenhaug at hotmail.com (Graz Bukanoff) >wrote: > >>Is Python an object based programming langauge? > >Short answer: > >Yes, but at least for me there can be some confusion originating from >factors that have to do with graphical user interfaces. > >Long answer: > >Some modern programming IDE's (integrated development environments) >are trying to adapt the way user thinks to the way the computer works. >A computer is a thing that is in an infinite loop where sometimes >events can trigger certain actions. > >For example in the old days of Borland Pascal or Borland C it was easy >to write a program that did certain things and then exited. > >Now with modern Delphi or C++ Builder its a real accomplishment to >write such a program. It goes directly against the paradigm of always Sorry, but that is not true of Delphi. Did you ever work Delphi from the command line? You can easily write console apps that do not use GUI windows: --- [17:10] V:\Dwk\bare>type bare.dpr program bare; {$APPTYPE CONSOLE} uses sysutils; begin Writeln('Hello World ;-)') end. [17:10] V:\Dwk\bare>dcc32 bare.dpr Delphi for Win32 Version 10.0 Copyright (c) 1983,97 Borland International bare.DPR(7) 8 lines, 0.08 seconds, 26328 bytes code, 2145 bytes data. [17:10] V:\Dwk\bare>bare Hello World ;-) [17:11] V:\Dwk\bare>dirf "bare.*(dpr|exe)" . 02-03-13 17:09 94 V:\Dwk\bare\bare.DPR 02-03-13 17:10 36,352 V:\Dwk\bare\bare.exe --- This is on NT4 using Delphi 3. GUI IDE or command line, don't diss Delphi either way ;-) >creating a form (a form is a container for graphical objects) whether >one needs one or not, and since forms are reacting to events one has >to generate an exiting event. In this view it's also natural to view >graphical things on the screen as objects, and to have objects react >to events. (user clicks button) > >This idea has become very pervasive and can be seen in other IDE's >that are of the GUI kind (graphical user interface). In python most of >the time objects are not connected to graphical elements on the >screen. In Delphi, C++ Builder and Visual Basic there are also non >graphical objects, but these IDE's *start* with graphical objects and >introduce other objects later. Not unless that's the way you want to use it. > >In python it is the other way around: It is possible to have graphical >objects and infinite loops and events but a starting python script is >often more like the "old" way of programming. This makes it easy to >try things out. Complex loops and graphics can be added later. > Ditto for Delphi. >Both ways of designing programs have some advantages. Different ways >of viewing objects -as graphics reacting to events or as >datacontainers reacting to methodcalls- can be appropriate. A program >can be nongraphic but still be object oriented and reacting to events, >for example a webserver. The resulting confusion sometimes leads to >not recognizing the object oriented (or object based?) nature of other >language-IDE combinations. > You could also look at the graphics as visual side effects of "datacontainers reacting to methodcalls" in an OO-designed GUI ;-) >On the other hand its entirely possible that the source of the >confusion is something completely different. > Well, please don't add to the confusion about Delphi's capabilities ;-) You could put someone off that might like it ;-) BTW, note the compile time. It's not a fluke. Big programs go very fast too. Coming from C++ you will wonder if it actually compiled or not ;-) Oops, this wasn't sent... here we go. Regards, Bengt Richter (No association with Borland). From phr-n2002a at nightsong.com Thu Mar 7 21:06:05 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 07 Mar 2002 18:06:05 -0800 Subject: Seek fame(*) & fortune(**) as a Python developer References: Message-ID: <7xd6yflsoi.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > Whether or not you want to be able to check files into the CVS repository, > if you want to contribute, you should probably subscribe to the python-dev > mailing list. You can subscribe here: > > http://mail.python.org/mailman/listinfo/python-dev > > If you'd like checkin privileges, send me (skip at pobox.com) an email with > "Python developer" in the subject. Don't simply reply to this message. > Your note may well get lost (I get tons of email) among followups that are > just feedback about this message. Let me know where your Python interests > and experience are, and maybe point to some stuff you've done. I'll do a > little filtering (probably not a lot), then pass it along to another group > of people who will decide about granting CVS checkin privileges. This disturbs me. I'd prefer that checkin privileges be extremely limited. I don't want random crackers to be able to check trojan horses into the Python distribution. I'd rather that every patch be examined by one of the official maintainers before check-in, as is done with the Linux kernel and the main GNU stuff. Of course I can't expect the maintainers to do exhaustive security analysis of every single patch, but they should at least eyeball the patches for obvious bugs and trojans. From jason at jorendorff.com Mon Mar 4 06:03:52 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 4 Mar 2002 05:03:52 -0600 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: <7xy9h8pt9x.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Tim Peters writes: > > Unfortunately, the C standard (neither one) isn't a lick of help here -- > > error reporting from C math functions is a x-platform crapshoot. > > That seems to me to be a deficiency in the C standard--IEEE 754 > defines these different error modes because they're all important, and > any high level language that claims to be good for serious numerics > should give precise control over the error modes. To be fair, C99 goes on about this at great length in Annex F. The error behavior appears to be specified pretty closely, to my untrained eye, and all sorts of error-detecting and -handling functions are provided in . (No idea what compliance is like out there, though.) But the standard leaves it to the implementation whether "underflow" and "inexact" are reported in certain cases. Interestingly, the footnote blames the underflow lenience on IEEE: "IEC 60559 allows different definitions of underflow. They all result in the same values, but differ on when the floating-point exception is raied." Btw, I hereby disclaim all knowledge of what I'm talking about. (As if there were any doubt.) ## Jason Orendorff http://www.jorendorff.com/ From maxm at mxm.dk Wed Mar 6 17:33:28 2002 From: maxm at mxm.dk (Max M) Date: Wed, 06 Mar 2002 22:33:28 +0000 Subject: Python on W2K server and dos batch files? References: <3c866f0c$1_2@axion.net> Message-ID: <3C869938.60900@mxm.dk> Mark Kingston wrote: > I would appreciate if you can tell me if Python is a good fit for what I > want to do. If not, please recommend another solution. All of the things you want to do looks absolutely feasible from Python. Especially you should look at: in module os popen(command[, mode[, bufsize]]) Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as the corresponding argument to the built-in open() function. The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned. Availability: Unix, Windows. regards Max M From matthias_j at lycos.com Sun Mar 10 13:39:28 2002 From: matthias_j at lycos.com (Matthias Janes) Date: 10 Mar 2002 10:39:28 -0800 Subject: Binary Register entries Question Message-ID: I exported a Win NT register to a reg file like this. [HKEY_CURRENT_USER\Software\TEST] "Password"=hex:b3,e8,85,f6,4d,9c,29,04 Now I'm not sure how to write binary Hex data with python. ---------------------------------------------------------- I do something like this import os, sys, win32api, win32con parentkey = win32con.HKEY_CURRENT_USER subkey = r"Software" Computer = None values = ...... I do not know how to use this for binary hex data b = win32api.RegConnectRegistry(Computer, parentkey ) c =win32api.RegCreateKey (b, subkey) v = win32api.RegSetValueEx (c, "Password", 0,win32con.REG_BINARY, values) ---------------------------------------------------------- Any Help would be greate Matthias Janes From m.faassen at vet.uu.nl Sat Mar 23 08:43:11 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 23 Mar 2002 13:43:11 GMT Subject: "Zope-certified Python Engineers" [was: Java and Python] References: Message-ID: Laura Creighton wrote: [snip] > Finally, > out of the chaos, we have produced the social situation where order > beats freedom of expression hands-down. And Google must be responsive > to it or risk going out of business. Would you trade 'the freedom to > be different' for 'the choice to be excellent'? Every new python > progrqammer who has given up on 'self-expression through my favourite > brace style' is making this choice. The subversive message is 'order > is a lot of fun'. I think that this message will finally produce > people who are brave enough to say that they want good authorities, > not the absence of all authorities. But then I'm an Order-loving > Optimist. Rest assured the Python Secret Underground is working on all of this. An important breakthrough was made yesterday in Consistinuum 47B (on Astor's Scale of Cross Temporal Diffusion, see crosstime://astorsctd.org for an index). Fnord. The PSU is Fnord confident (.85) that the Discordians can Fnord be stopped Fnord by Fnord Fnord Fnord Hail Eris! All Hail Discordia! The Aneristic Principle is that of APPARENT ORDER; the Eristic Principle is that of APPARENT DISORDER. Both order and disorder are man made concepts and are artificial divisions of PURE CHAOS, which is a level deeper that is the level of distinction making. Seek the Sacret Chao -- therin you will find the foolishness of all ORDER/DISORDER. They are the same! this message is temporary out of order - the Mgt. and Fnord therefore Fnord the PSU is in an excellent Fnord position not just to diminish Erisian propaganda, but to completely eliminate it shortly. From edcjones at erols.com Tue Mar 26 11:18:11 2002 From: edcjones at erols.com (Edward C. Jones) Date: Tue, 26 Mar 2002 11:18:11 -0500 Subject: C API for modules Message-ID: <3CA09F43.80206@erols.com> Is there some simple way to call functions in modules from C? In particular, for module struct, how do I call pack, unpack, and calcsize? Thanks, Ed Jones From sjmachin at lexicon.net Thu Mar 28 00:20:33 2002 From: sjmachin at lexicon.net (John Machin) Date: 27 Mar 2002 21:20:33 -0800 Subject: Extending/embedding versus separation References: Message-ID: "skoria" wrote in message news:... > Hi > > I have a system for processing usage statistics, for which most of the > hard work is done by a small C program [etc etc] > > Now I want to create fancy graphs, [etc etc] > So the plan was until today to write everything out > to a text file and process these files with python to display in html > or whatever other format comes to mind. > > But I've been reminded that python is good at integrating with C > programs through extension and embedding. This tells me that the other > way to go from here is to turn my c program into a python extension, > or somehow merge the two languages, so that I miss the step of saving > the C programs results to disk. (and potentially increase memory > usage?). I will be having a look at "programming python" tonight, to > see which, out of extending and embedding, is what I should go for. My take on a project like yours would be to write *everything* (that's not available off the shelf) in Python first, even parts that you think you know for sure are going to have to be implemented in C later. Those parts can be coded up in Python modules that can be replaced by C extensions if really needed. The infrastructure stuff like command-line-arg handling (or GUI input), file handling, etc is so much easier to bolt together in Python than in C that I would prefer extending Python (if necessary) to embedding Python in C. Hash tables in C? Are you using a package like Cdt, or did you write your own? If you can process data into hash tables in C and then get the data into Python faster than you can process the data into dictionaries in Python, then please divulge your deep dark magic spells to Tim Peters the Python-dict-shaman. You seem to be a bit concerned about memory usage. My advice is to write a prototype of your application in Python, bearing memory efficiency in mind, but not obsessively -- i.e. use the most appropriate data structures and don't distort your Python code into unreadability. Then you either have enough memory or you don't. Do some back-of-the-envelope calculations, like: a 256MB stick of memory costs how few hours of developer time? If you can't for whatever reason get more memory, then it's time to consider your next step. If your application has some large dictionaries that only have objects of type X as keys and type Y as values (where Y is a simple type like int or float) then it might be a good idea to take a copy of dictobject.c and make a specialised intdict (say) module that instead of managing (PyObject *) pointers, managed int values directly -- this would save you heaps (pardon the pun) of memory; see recent thread in this newsgroup about amount of memory taken up by Python objects. For another (already implemented) variation on this memory-saving theme, google("c.l.py", "Machin intern memory"). HTH, John From skip at pobox.com Thu Mar 7 07:02:13 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 06:02:13 -0600 Subject: hash(unicode(string)) == hash(string) sometimes In-Reply-To: References: <7dee885c.0203051843.36efa5c2@posting.google.com> <7xvgcabcti.fsf@ruckus.brouhaha.com> Message-ID: <15495.22213.352930.662418@12-248-41-177.client.attbi.com> >>>>> "Martin" == Martin v Loewis writes: Martin> sjmachin at lexicon.net (John Machin) writes: >> ... making hash(string) always do hash(unicode(string)) ... Martin> The real solution, IMO, is to never change the system default Martin> encoding. Veering off on a tangent, the question of raw_input failing for latin-1 input came up on python-help in the last day. The suggested solution was to change the system default encoding. If not that, then what? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From kragen at pobox.com Mon Mar 25 20:14:48 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 25 Mar 2002 20:14:48 -0500 Subject: Client/Server Tutorial? References: Message-ID: <83u1r43zav.fsf@panacea.canonical.org> "Irmen de Jong" writes: > > Is there any good tutorial for creating advanced client/server apps > > (like online games) out there? i tried to make one 2 times, and both > > May I suggest you take a look at Pyro; http://pyro.sourceforge.net > It may be just what you want/need for easy distributed application development. > You don't have to do any network programming when using Pyro. I don't think Pyro is suitable for online games. It's an RPC layer. From skip at pobox.com Tue Mar 19 08:31:37 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 19 Mar 2002 07:31:37 -0600 Subject: psyco, jython, and python speed tests In-Reply-To: References: <83hendkou7.fsf@panacea.canonical.org> Message-ID: <15511.15801.929250.332133@12-248-41-177.client.attbi.com> >> ... but because in some cases, there really *are* performance issues >> that rule Python out. c//> Indeed; and believe it or not, there are even some environments c//> where writing external C doesn't solve the problem either. I'm coming in late here, so maybe I'm misreading something, but I don't think Python tries to be the one-and-only programming language. If packages like Psyco expand the range of applications to which it can be applied, so much the better, but I view that as an incremental change, not a fundamental change. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From eric.brunel at pragmadev.com Mon Mar 4 08:42:21 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 4 Mar 2002 13:42:21 +0000 Subject: what is happening at __init__ References: <3C8358C0.81D97AD8@doc.ic.ac.uk> Message-ID: Hi, Your questions regarding the so-called "constructor" may simply show that the term "constructor" is not so good after all. In fact, the constructor does not "build" anything: the instance is already created (i.e. allocated in the memory) when the constructor is called. So your Q2 starts on the wrong basis: self is *not* assigned to a new value within the function; the new value is created *before* the call to the constructor, which simply references it as its parameter named "self", just like any other function/method. So if you do something like: class C: def __init__(self): self = None o = C() o will *not* be set to None, but to a new, uninitialized instance of C: as always in Python, modifications to a method parameter are lost when the method ends, and the "constructor" is no exception. In fact, Python is a tad more explicit than other languages when it calls the "constructor" __init__, because it would be far more accurate to call it an "initializer" rather than a "constructor": it doesn't create the instance, but simply initialize its attributes. And note it is not specific to Python: in C++ or in Java, the "constructor" is also called when the instance has already been allocated, so it doesn't build it. Maybe this enlightens you a little bit more. The answers for your other questions should now be clear: - Q1 is a "yes but": instance is created, then passed to the constructor where it is assigned to local variable "self" - Q2 is pointless: self is *not* assigned in the constructor - Q3 is no: the return value for the constructor is completely ignored, so you can return whatever you want (it's just useless...) - Q4 is yes: you work on the actual instance that was created before the call to the constructor - Q5 is yes: it is not the return value of the constructor that matters, but what is done to self's attributes within the method If there are still unclear points in all that, you should carefully read the section 3.1 of the Python language reference manual ("Objects, values and types") where the objects and references concepts are described (IMHO not so well, but it's a start...). HTH - eric - From syver-en+usenet at online.no Thu Mar 28 21:21:03 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Fri, 29 Mar 2002 02:21:03 GMT Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <3ca27d3d@news.microsoft.com> Message-ID: Dale Strickland-Clark writes: > Syver Enstad wrote: > > >Adding the registry settings so that one can drop data files on .py > >and .pyw files and the files dropped will be received as commandline > >arguments would also be nice. > > > I raised this issue some while ago. I don't think that's just a > registry change. Oh but it is, I have it on my machine. I just nicked some registry stuff from the exe file key in HKEY_CLASSES_ROOT and py and pyw file behave beautifully when dropped files on. Here's what you need: REGEDIT4 [HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] @="{86C86720-42A0-1069-A2E8-08002B30309D}" [HKEY_CLASSES_ROOT\Python.NoConFile\shellex\DropHandler] @="{86C86720-42A0-1069-A2E8-08002B30309D}" -- Vennlig hilsen Syver Enstad From duncan at NOSPAMrcp.co.uk Mon Mar 18 04:07:13 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 18 Mar 2002 09:07:13 +0000 (UTC) Subject: Zope Question References: <3C950D0B.60602@thomas-guettler.de> Message-ID: Thomas Guettler wrote in news:3C950D0B.60602 at thomas-guettler.de: > But I can't figure out how to insert >> either CHECKED or nothing depending on the state of a variable. >> > > One solution would be to do it like this (I use pseudo-code since I > am new to page templates, and don't want to look up the syntax): > > if checked==true > > else > > You just do it like this:

    I'm checked
    I'm not.
    I'm checked
    I'm not.
    The page type must be text/html for this to work. Zope's templates have a list of attributes in HTML that are given in a boolean form (compact, nowrap, ismap, declare, noshade, checked, disabled, readonly, multiple, selected, noresize, and defer). Strangely this list is declared in two separate places in the source, and only used in one place! -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From abou at cam.org Sun Mar 31 10:49:06 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Sun, 31 Mar 2002 10:49:06 -0500 Subject: seek() References: <3CA6AD4D.C552BDDA@engcorp.com> Message-ID: <3CA72FF2.6B5681F0@cam.org> Peter Hansen wrote: > Well, that's the basic key to writing software: use components > that already exist to build up a more sophisticated solution. > > In this case, if you have a method of finding a string in a string > (which you have already found), and you have a method of getting > a string from a file or webpage, you can clearly put the two together > to solve your overall problem. > > Getting a string from the data in a file is rather simple, and if > you want to get a string from a web page you should look at the > urllib module. > > -Peter This is what I have so far: import urllib import string c = open('/home/corestats', 'w') try: f = urllib.urlopen("http://www.coremud.org/cgi-bin/mycore.pl?stocks=1&font=Arial") except IOError: print '\nWebsite not reachable. Core 2651 must be down or check your connection.' k = urllib.urlretrieve("http://www.coremud.org/cgi-bin/mycore.pl?stocks=1&font=Arial", 'corestats') # Now I have the source in a file. No problems here. # This finds the byte where 'Gold' starts. I know that Gold's value is found 8 # bytes later. longstr = c.read() print string.find(longstr, 'Gold') # Is it possible to have the output of string.find() converted to a string, or even # better, to an int? If I can get the location of 'Gold' into an int, it would be # easy to do: c.seek(1469) # this is where 'Gold' is c.read(4) # this gets Gold's value (in this case, 9.60) c.close() # But since the webpage is dynamic, it's never the same bytes so I can't hardcode # the location of the different values I want. # I'm not trying to get the string.find() output into an int... -- Zutroi Zatatakowski Commando PACU http://pacu.cjb.net From ralph at inputplus.demon.co.uk Sun Mar 31 08:07:11 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 31 Mar 2002 13:07:11 GMT Subject: PEP 285: Adding a bool type References: Message-ID: Hi Guido, > IMO, bool(x) is the right way to "normalize" any value into a truth > value. What do you think of `truth(x)' for all the good reasons listed elsewhere in the thread? You used truth yourself instead of Boolean above. Ralph. From john at yahoo.com Sat Mar 23 02:37:56 2002 From: john at yahoo.com (John Warney) Date: Sat, 23 Mar 2002 07:37:56 GMT Subject: Core Python Programming, chapter 5 exercises number 5-3, question on this exercise References: <8dbo9u8jv0j9p58h4dvhqojk2154m8vict@4ax.com> Message-ID: nm, i found the answer to my question. If i would have waited anotehr 5 mins.... on the page after i stopped reading last nite i found example 6-1 which uses raw_input() which was used on page 27. Forgive me since i had read that like 2 months ago and had picked the book back up for the first time 2 days ago in almot 2 months. Rob PS---why is it that every mailing list or newgsroup posting i always ask, i always answer my own dumbass question 5-10 mins after i post/ask it??, lol From md_lazreg at yahoo.com Tue Mar 19 23:27:48 2002 From: md_lazreg at yahoo.com (mohamed lazreg) Date: Tue, 19 Mar 2002 20:27:48 -0800 (PST) Subject: bug tracking system Message-ID: <20020320042748.24672.qmail@web10507.mail.yahoo.com> Dear pythoners, Are you aware of any free bug tracking system written in python? Thanks in advance... Mohamed __________________________________________________ Do You Yahoo!? Yahoo! Sports - live college hoops coverage http://sports.yahoo.com/ From cfelling at iae.nl Tue Mar 5 18:01:21 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 6 Mar 2002 00:01:21 +0100 Subject: Updating Python...Newbie alert! References: Message-ID: Mr.Lee wrote: > How new am I? I am this new: when I typed 'make install' > went into it's proper place! I didn't quite finish the proper > procedures. Ya lern sumthin' new ev'ryday. If this worked and you didn't specify an --prefix to ./configure then you're probably running as root. *Don't do that* It will heart someday. Do the ./configure and make dance as a normal user and switch to root just to do the install step. -- groetjes, carel From bokr at oz.net Sat Mar 16 22:11:30 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Mar 2002 03:11:30 GMT Subject: PIL Headaches: Advice Needed References: <4378fa6f.0203161652.7f28e23b@posting.google.com> Message-ID: On 16 Mar 2002 16:52:49 -0800, mnations at airmail.net (Marc) wrote: >I have gone thru all the tutorials and read me's I can find, and I >still can't get PIL to work for me. At no point has it ever been able >to recognize any file that I try to open in all formats (.bmp, .jpg, >.gif, etc). > >I've imported the two DLL's into my main structure. I've imported all >of the imaging .py files into the main Lib folder. The classes are >being recognized and imported correctly. > >Has anyone else had similar problems? What am I doing wrong? > Not posting minimal failing actual code ;-) Regards, Bengt Richter From tim.one at comcast.net Sun Mar 31 16:49:21 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 31 Mar 2002 16:49:21 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Message-ID: [Pearu Peterson] > Theorem: > ======== > Assume specification of PEP 285. The following statements hold truth: > > True is One > > and > > False is Zero, > > where One and Zero represent integers 1 and 0, respectively. The theorem is false; it would be true if you replaced "is" by "==". > Proof: > ------ > According to PEP, True and False are instances of bool that is a > subclass of int. True. > Therefore True and False can be considered as integers Unclear what that means, exactly. > and it makes sense to compare them with integers. Except "is", in terms of which your theorem is stated, is a special kind of comparison that can reveal non-guaranteed implementation accidents. To cut this short, there's no guarantee that even 0 is 0 returns true, although it *happens* to be true in all implementations of CPython to date (although for different internal reasons in different implementations!). The PEP *does* guarantee that True is True False is False are true; that's a stronger guarantee than is made for integers. > If n is an integer then the following statements hold > > True == n only if n is 1 Only if you're using a non-Python meaning for "is". A true statement using Python meanings would be True == n if and only if n == 1 Note that this covers cases like True == 1.0 too. > ... From nsbase at yahoo.co.uk Sat Mar 16 11:31:28 2002 From: nsbase at yahoo.co.uk (Noel Smith) Date: Sat, 16 Mar 2002 16:31:28 -0000 Subject: Windows NT shell + extended characters. Bug or what? References: Message-ID: <3c937209$0$8509$cc9e4d1f@news.dial.pipex.com> Jeff Shannon wrote: >> However I've recently installed python 7.2 on Windows NT4 > Wow! 7.2 ? They really *have* sped up the release cycle... Doh! I was installing RedHat at the same time as writing the post. I meant 2.2 although it doesn't really matter what the version is. Jason Orendorff wrote: > Alas, the PC console uses a different character set called CP437, > which is not Latin-1 compatible. In CP437, the pound sign > is 156 and the yen sign is 157. This was the bit of info I was really after! I must admit that I hadn't ever come across the "cp437" character set before, even though I've been doing windows coding for a good few years now. Now I know about it I can just apply a decode to a string to get the correct answer: >>> ord( "?".decode("cp437") ) 163 Martin V. Loewis wrote: > This is rather unlikely, I doubt the interactive interpreter will ever > be able to properly identify the encoding of the console window. More > likely, this line will give an error, since no encoding has been > declared. Although I agree that interpreter can't determine the encoding automatically, it would be really nice to be able to set the input encoding when you start it up. Its a real pain to look up the unicode value for every extended character you want to use and it would make Python a lot easier for those with a large number of extended characters on their keyboards. Thanks for all the help. Noel Smith From maxm at mxm.dk Wed Mar 13 15:42:24 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 20:42:24 +0000 Subject: Why Don't Scripts Run ? References: <3C8F9C59.F9408D47@mcn.net> <3C8FB1E0.C0E0C6E7@mcn.net> Message-ID: <3C8FB9B0.7050304@mxm.dk> jrc wrote: > I apologize for earlier comments. I find Python 2.2 > will run scripts in Windows (Dos prompt) IF the inter- > preter has not already been launched. This is clearly > the reason each scriptname is prefixed by 'python'. No that is actually a classic. Well at least I have seen it a few times before on the list. The problem is that if you have allready launched python you are typing dos commands into Python. And that doesn't quite compute :-/ You are trying to run a Python program that looks like: python script.py And naturally that will not work. regards Max M Btw. wouldn't it be good practice to write possible/more keywords in the bottom of an answer-post so that it can be easier google'd ??? or is that a stupid idea? -------------------------------------- dos command line interactive python interpreter start launch python program python.exe From johnroth at ameritech.net Sat Mar 30 18:24:08 2002 From: johnroth at ameritech.net (John Roth) Date: Sat, 30 Mar 2002 18:24:08 -0500 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> Message-ID: "Martin v. Loewis" wrote in message news:m3y9ga7z38.fsf at mira.informatik.hu-berlin.de... > Peter Hansen writes: > > > Are there code snippets which clearly have significantly improved > > readability as a result of a rewrite using the proposed bool? > > The standard library has 110 occurrences of "return 0", 70 occurrences > of "return 1", and 136 occurrences of "return None". Optimistically, > this makes 300 functions. It would help users of these 300 functions > if they would know whether those functions return a boolean or an > integral value (if integral, what range?); for the "return None" > cases, the boolean type would help to clarify whether this is "return > no value", "return False", or "return nil object"; > > Regards, > Martin I make it optimistically 180 functions. Given the reasonably high quality of the standard library, "return None" almost certainly means that the function does not have a return value, not that the return value should be treated as False. Good practice shouldn't be to return None if you meant False - the convention is 1 or 0. John Roth > From akuchlin at dust.mems-exchange.org Fri Mar 8 08:31:40 2002 From: akuchlin at dust.mems-exchange.org (A.M. Kuchling) Date: 08 Mar 2002 13:31:40 GMT Subject: Seek fame(*) & fortune(**) as a Python developer References: Message-ID: In article , Jonathan Gardner wrote: > Skip Montanaro scribbled with his keyboard: >> Yes, I believe python-dev has opened up. Try subscribing again and see >> what happens. ;-) > Deferred for administrator's approval. I got the same message when I re-subscribed a few weeks ago and had to wait a few days for someone to get around to adding me, so that message isn't anything to get worried about. --amk (www.amk.ca) He can't make ends meet -- probably too many economists in the government. -- The Doctor, in "The Sunmakers" From trentm at ActiveState.com Wed Mar 13 12:26:21 2002 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 13 Mar 2002 09:26:21 -0800 Subject: trackers (was: zlib vulnerabilities and python) In-Reply-To: ; from mwh@python.net on Wed, Mar 13, 2002 at 02:43:13PM +0000 References: Message-ID: <20020313092621.C2272@ActiveState.com> [Michael Hudson wrote] > Time to look at roundup again? The tracker on sf is starting to piss > me off (even more). If you *are* going to get motivated to look at a different tracker *please* consider bugzilla. You will find it a much more appropriate than roundup. Trent p.s. I am gonna regret feeding this. -- Trent Mick TrentM at ActiveState.com From duncan at NOSPAMrcp.co.uk Thu Mar 21 04:14:30 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 21 Mar 2002 09:14:30 +0000 (UTC) Subject: Unicode problem References: <3c98f206.24909027@news.tiscali.no> <3c98faad.27124282@news.tiscali.no> Message-ID: gargravarr at whoever.com wrote in news:3c98faad.27124282 at news.tiscali.no: >>if you don't tell Python what 8-bit encoding you want >>to use for a Unicode string, Python will assume ASCII. > > How do I tell Python what 8-bit encoding I want to use ? Can I tell > Python so I don't have to use encode? site.py uses sys.setdefaultencoding to set the default encoding but it then does 'del sys.setdefaultencoding' to stop anyone else messing with it. Your options (entirely at your own risk): Edit site.py to select a different default encoding. Edit site.py to remove the line that deletes sys.setdefaultencoding OR to recover a reference to setdefaultencoding: import sys; reload(sys) I have no idea whether it is safe to call setdefaultencoding multiple times, although a quick play with the interpreter didn't reveal any massive problems. I also have no idea what effect reload(sys) may have on anything. I didn't even know you could reload a builtin module until I tried it. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From shalehperry at attbi.com Fri Mar 1 11:54:01 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 01 Mar 2002 08:54:01 -0800 (PST) Subject: Minor, minor style question In-Reply-To: <5F9A347EAC81A19E.F4E6D6813EA4DC98.17114695240B3A22@lp.airnews.net> Message-ID: On 01-Mar-2002 Cameron Laird wrote: > Why would I prefer > string = "" > string = string + "abc " > string = string + "def " > string = string + "xyz" > over > string = "abc " + \ > "def " + \ > "xyz" > ? I see a lot of the former in contexts I associate > with Visual Basic- or JavaScript-majority folkways. > Is there an attraction to the redundancy (and fragil- > ity!) I'm missing? Are \-s *so* deprecated? According to posts by people like Tim Peters the preferred idiom is more like: l = ["abc", "def", "xyz"] s = string.join("", l) i.e. build up a list of pieces through out the function and then join() them at the end. From boud at valdyas.org Sat Mar 2 12:22:53 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sat, 02 Mar 2002 16:22:53 -0100 Subject: PyQT and shaped windows in X References: Message-ID: <3c80ef25$0$90048$e4fe514c@dreader1.news.xs4all.nl> Moray Taylor wrote: > Hi, > > Can anyone point me in the direction of an example of shaped windows > using QT with Python, is the XLib module required? Is it even > possible? > Have you tried translating the tux example from the Qt examples directory? I've attached a quick and dirty script. You should get the image from someplace yourself. > BTW I have tried asking in the PyQT/PyKDE mailing list, but it wasn't > considered to be a PyQT question, go figure. > Well, it certainly isn't very Qt specific. -- Boudewijn Rempt | http://www.valdyas.org -------------- next part -------------- A non-text attachment was scrubbed... Name: tux.py Type: text/x-java Size: 788 bytes Desc: not available URL: From fredrik at pythonware.com Tue Mar 12 17:25:11 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 12 Mar 2002 22:25:11 GMT Subject: trouble testing for existance of variable References: <4bbaa6d6.0203121352.4358f14@posting.google.com> Message-ID: googlePoster wrote: > python gurus: > > if I want to know if a variable exists before > testing it, what do I do? gurus don't write code that do stuff like that, but never mind... > if locals().has_key("colors_name") try: colors_name except NameError: # doesn't exist else: # does exist; do something or: try: # does it exist? colors_name except NameError: colors_name = None # now it does ... if colors_name: # do something (etc) From mcherm at destiny.com Wed Mar 6 08:38:51 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 06 Mar 2002 08:38:51 -0500 Subject: Status of PEP's? Message-ID: <3C861BEB.60701@destiny.com> Not that my opinion means anything, but I'll go ahead and express it anyhow. 1) I think that "for i in range(len(items)):" is awkward, annoying, and detracts from Python. There should be a better way. 2) When I first saw PEP 276 I thought "Hey!, that's a nice solution! We're not using iteration for integers for anything else, and I certainly agree that looping from 0 to x-1 IS the "most obvious" thing to do (in Python anyhow), so it's really quite nice. 3) Since then I've seen objections, typified by the following: > I can NEVER bring myself to see an integer as a collection, > not outside of a lecture on number theory, anyway. > > Sorry to rant, but this is the only idea for Python I've seen in a > VERY long time, since the 1.5.2 days, where rather than capturing > my interest and giving me something to contemplate, just strikes me > as ugly, and stays ugly no matter how long I look at it. I still think it's a nice solution, but with the vehemence of the objections, I have to back off. 4) The need to use "for i in range(len(items)):" is STILL awkward, and STILL needs some solution. "for 0 <= i < len(items):" just doesn't do it for me. "for x in [0:len(items)]:" is a pain. Perhaps something as simple as "for i in iterlen(items):" is the answer (and throw in "for i, x in iteritems(items):" too) would do the trick. I don't know. -- Michael Chermside PS: *PLEASE* disregard the whole "set theory" argument. I don't think that anyone defending PEP 276 is suggesting it as the motivation... that makes it a classic "straw man" retorical fallacy. It's a red herring... the real motivation is simply that "loop from 0 to x-1" is the "most obvious" way to "iterate an integer" *IF* such a thing were allowed in Python. From maxm at mxm.dk Wed Mar 13 04:35:48 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 09:35:48 +0000 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: <3C8F1D74.10802@mxm.dk> Martin v. Loewis wrote: > I don't count articles in a newsgroup saying "this is a good thing", > "just continue with your efforts", "we definitely need this" as > interest. Instead, people contributing code, reporting bugs, or just > using the system in their applications show interest. This is the case > for Jython, but I don't think Armin or Christian got much actual code > contributions. Likewise, when Mark would not deliver a win32all build > for a few weeks, people would complain - but nobody would actually > step forward and publish a build herself. This could also just be a sign that there is interrest, but the people using win32all might not be able to publish a build themself? Not everybody is as knowledgable as Mark, Even though we work on the superior Windows platform ;-) regards Max M From stephen at stephencox.org Wed Mar 13 07:35:21 2002 From: stephen at stephencox.org (Stephen Cox) Date: Wed, 13 Mar 2002 12:35:21 GMT Subject: MySQL Library or Interface? Message-ID: Is there a MySQL library or some kind of framewrok available for Python? -- Stephen Cox From graz at mindless.com Fri Mar 15 16:17:18 2002 From: graz at mindless.com (Graham Ashton) Date: Fri, 15 Mar 2002 21:17:18 +0000 Subject: Optimising list comparison Message-ID: A friend of mine is using Python in a research project where he needs to compare each element of two vectors, such that comparing [a, b, c] and [d, e, f] would involve comparing a with d, b with e and c with f. The only possible values in either list are 0, 1 and -1. When comparing two values, if either value is set to -1 then both values are deemed to be equal. So we've got: 0 == 0 0 == -1 1 == 1 1 == -1 1 != 0 What he wants to know is simply whether all the values in the two lists are "equal", in which case the comparison returns 1, otherwise it returns 0. Now, having read Skip M's python optimisation page I would have thought that the following example could be beaten into the ground by an alternative involving map(). Obviously, a C extension would win the grand prize, but I'm interested in learning some map() tricks.... list1 = [1] * 20 list2 = [1] * 19 + [0] def compare(): for i in range(len(list1)): a = list1[i] b = list2[i] if (a != b) and (a != -1) and (b != -1): return 0 return 1 Neither of us have yet managed to come up with anything to beat it (we've been timing the alternatives over 100000 itterations). Any hints? What I can't work out how to do is how to break out of a call to map() if two values don't match. The only thing I've come up with so far is this: func = lambda a, b: (a == b) or (a == -1) or (b == -1) or 1 / 0 try: map(func, list1, list2) except ZeroDivisionError: pass and though I felt quite smug when I'd thought of it, it's more than a bit hacky. The raise and except also double the execution time on my machine. Here's my complete script: ----cut---- #!/usr/bin/env python import time list1 = [1] * 20 ## list1 = [1] * 9 + [0] + [1] * 10 list2 = [1] * 19 + [0] def benchmark(func, iters=100000): start = time.time() for i in range(iters): r = func() end = time.time() print "%d iterations of %s took: %.3f secs" % (iters, func, end - start) def attempt1(): for i in range(len(list1)): if (list1[i] != list2[i]) and (list1[i] != -1) and (list2[i] != -1): return 0 return 1 func = lambda a, b: (a == b) or (a == -1) or (b == -1) or 1 / 0 def attempt2(): try: map(func, list1, list2) except ZeroDivisionError: pass if __name__ == "__main__": benchmark(attempt1) benchmark(attempt2) ----cut---- Cheers, Graham. From stojek at part-gmbh.de Tue Mar 5 11:26:06 2002 From: stojek at part-gmbh.de (Marcus Stojek) Date: Tue, 05 Mar 2002 16:26:06 GMT Subject: python IDE, komodo Message-ID: <3c84f0eb.27475796@news.easynews.net> Hi, I am looking for an Python IDE. Nothing extremly special, just easy debugging, tracing maybe profiling. Is Komodo okay? Is there something else (except Visual Studio .NET) I should look at. Something free would be nice. Thanks, Marcus From skip at pobox.com Tue Mar 5 09:14:14 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 5 Mar 2002 08:14:14 -0600 Subject: OT - file permission checks on Windows In-Reply-To: References: <15491.48228.515787.419778@beluga.mojam.com> Message-ID: <15492.53942.960344.105700@12-248-41-177.client.attbi.com> >> Given this simple file access permission code: [...] how would I do >> this under Windows? Jason> The following is not a joke. Yup, no smilies. :-) Jason> Any Windows programmer would just "return 1". After seeing various responses, this is what I decided to do. I figure some Windows programmer who wants to earn his stripes can fix it. Jason> Note that even on Unix, the code you quoted isn't perfect. Users Jason> can belong to multiple groups these days. Good point. I think I can beef up my code fairly easily in this area. Thanks to all for the useful feedback. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From adina_levin at mindspring.com Mon Mar 25 13:47:30 2002 From: adina_levin at mindspring.com (adina_levin at mindspring.com) Date: Mon, 25 Mar 2002 12:47:30 -0600 Subject: Question: recursion and scope Message-ID: Hello, Pythonistas. I am attempting to teach myself some basic computer programming concepts using Python. I'm currently extending the recursive binary tree program in Programming Python to traverse the tree and count its depth. The program successfully traverses the tree and counts the number of nodes. So far, though I haven't figured out how to calculate the "maximum depth" of the tree without declaring "maxdepth" as a global variable. If maxdepth is declared as a local variable within the recursive method, it gets re-set for each subtree. What am I missing? Many thanks, - Adina From johnroth at ameritech.net Mon Mar 25 07:24:57 2002 From: johnroth at ameritech.net (John Roth) Date: Mon, 25 Mar 2002 07:24:57 -0500 Subject: Debugging on windows via print statements -- reliable? References: Message-ID: Since you're running a console app, I'd suggest two changes to your test setup. 1) Execute the program from the DOS prompt, not from PythonWin. 2) Redirect stdout to a file. The first suggestion is simply to eliminate one possible variable - if switching to a raw command prompt changes something, you've got more data, if it doesn't, you've eliminated a possible candidate. At the command prompt, you can set up a .bat file that runs the app very conveniently, and does the redirection. It's a couple of keystrokes and mouse taps more than running it under PythonWin, but I find that it's worth it. John Roth "Nick Arnett" wrote in message news:mailman.1017034718.25848.python-list at python.org... > > > > -----Original Message----- > > From: python-list-admin at python.org > > [mailto:python-list-admin at python.org]On Behalf Of Peter Hansen > > > [snip] > > > By the way, how can Python code get "stuck"? Is it a logic flaw, > > or are you talking about the kind of "stuck" that used to happen, > > in the "old days", when we were always writing code in languages > > which would actually crash the computer? > > I'm using these vague adjectives because I can't tell what is happening. > Somewhere in the midst of retrieving pages with urllib and parsing them with > sgmllib, everything seems to stop. And yes, it's a console app for the > moment. I have a GUI that'll control it, but I'm working on pieces that > grab web pages, extract data and stick them in MySQL. The only thing I'm > sure of is that it's not a problem with the database. It happens at a > different point each time, sometimes after a few dozen pages, sometimes > after a couple of hundred. And I can re-do the same sequence of pages and > it'll freeze/loop/stop/whatever at a different point each time. The process > is alive, there's no memory size change and it's consuming very few CPU > cycles when this happens. > > I'm working in PythonWin and I would have hoped that "break into running > code" would get me into it when this happens, so I could see where it's > getting stuck, but no, that would apparently be too convenient. > > Nick > > From Gurdon_Merchant at ml.com Mon Mar 11 09:22:48 2002 From: Gurdon_Merchant at ml.com (Gurdon Merchant, Jr.) Date: 11 Mar 2002 06:22:48 -0800 Subject: win32com - Code snippet works in VBScript but not Python. Message-ID: <484d9f6a.0203110622.7275204d@posting.google.com> The Python win32com package works fine for most COM work. However, I'm having problems with cases where the reference is to be used to invoke a method which creates another object. Here is a VBScript snippet that works fine: ' START VBSCRIPT SNIPPET ' vbtest.vbs Dim WshController Set WshController = WScript.CreateObject("WshController") Dim localVbscriptToRun localVbscriptToRun = "c:\temp\test-script.vbs" Dim remotePc remotePc = WScript.Arguments(0) Dim RemoteScript Set RemoteScript = WshController.CreateScript(localVbscriptToRun, remotePc) ' END VBSCRIPT SNIPPET But the equivalent Python code: # START PYTHON SNIPPET # pytest.py import sys import win32com.client WshController = win32com.client.Dispatch("WshController") localVbscriptToRun = "c:\\temp\\test-script.vbs" remotePc = sys.argv[1] RemoteScript = WshController.CreateScript(localVbscriptToRun, remotePc) # END PYTHON SNIPPET fails with this exception: Traceback (most recent call last): File "C:\temp\pytest.py", line 10, in ? RemoteScript = WshController.CreateScript(localVbscriptToRun, remotePc) File "", line 2, in CreateScript pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024891), None) To make the following code snippets run you must: 1) Be on NT4 Sp6 or higher. 2) ActiveState Python 2.1.212 (or Python with win32all). 3 "Remote" = "1" (type REG_SZ) in: "HKLM\Software\Microsoft\Windows Script Host\Settings" on both local and remote PC (WshController requirement). 4) Have Scripting engines 5.6 or higher installed. 5) Have a c:\temp\test-script.vbs with at least a blank line. 6) Invoke the code snippets with UNC (\\foo) format of name of a remote PC you have local administrator privs on (or use name of local PC). The VBScript will execute correctly. The Python code will not. win32com works for me in other examples. I just seem to be having problems in cases where I try to invoke a method on a returned object. That is, lines similar to "RemoteScript = WshController.CreateScript(localVbscriptToRun)". I appear to be missing some subtle point. Can anyone shed some light on it? Thanks in advance, Gurdon Merchant, Jr. Gurdon_Merchant at ml.com From nas at python.ca Tue Mar 12 16:08:59 2002 From: nas at python.ca (Neil Schemenauer) Date: Tue, 12 Mar 2002 13:08:59 -0800 Subject: Has Mark Hammond attained pariah status yet? In-Reply-To: ; from aahz@pythoncraft.com on Tue, Mar 12, 2002 at 03:49:48PM -0500 References: <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: <20020312130858.A27486@glacier.arctrix.com> Aahz wrote: > IIRC someone (Michael Hudson?) tried doing a bit of work with > Parrot/Python as a proof of concept. That was AMK. It seems the Parrot guys are more interested in micro-optimizations and adding regex support to the VM than in supporting Python on Parrot. Too bad. Neil From theller at python.net Thu Mar 21 08:31:17 2002 From: theller at python.net (Thomas Heller) Date: Thu, 21 Mar 2002 14:31:17 +0100 Subject: How to install pychecker? References: Message-ID: "Dale Strickland-Clark" wrote in message news:jgmj9ucgm47i87dp6eie5l5frn65ntfrpl at 4ax.com... > I thought I'd try this out. > > In the absence of any instructions (that I can find) I tried unzipping > it to a directory and running setup.py. > > I got this: > > C:\Program Files\pychecker-0.8.10>setup.py > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: no commands supplied > The canonical way is 'setup.py install'. 'setup.py --help-commands' shows you the available commands. An even easier way, which does also give you the ability to uninstall, is demonstrated in the ASPN Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117248 Thomas From pete at dexterslab.de Fri Mar 29 07:14:48 2002 From: pete at dexterslab.de (Henning Peters) Date: Fri, 29 Mar 2002 13:14:48 +0100 Subject: chat server References: <3CA4544D.6646CB30@q-survey.be> Message-ID: > Don't reinvent the wheel. Use asyncore.py and asynchat.py, it's > part of the standard Python library. hmm, but it's fun for me to make my own way... bye, henning From kirill_simonov at mail.ru Fri Mar 8 12:06:44 2002 From: kirill_simonov at mail.ru (Kirill Simonov) Date: Fri, 8 Mar 2002 19:06:44 +0200 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: <553719390.20020307212819@neosynapse.net> References: <553719390.20020307212819@neosynapse.net> Message-ID: <20020308170644.GA710@abulafia.local> * Steven D. Arnold : > 2. Some have asked why one would not use vars() and the mapping format > all the time, since vars returns a dictionary of the local namespace? > The problem with vars() is that (at least as far as I know) it doesn't > support dictionaries, lists, object attributes and function calls. ### xstring.py ### import sys class XDict: def __init__(self, globals, locals): self.globals = globals self.locals = locals def __getitem__(self, key): return eval(key, self.globals, self.locals) def xstring(string): frame = sys._getframe(1) return string % XDict(frame.f_globals, frame.f_locals) def test(): import math x = y = 2 s1 = "%(x)s + %(y)s = %(x+y)s" s2 = "sin(pi/4) = %(math.sin(math.pi/4))0.4f" s3 = "Python-%(sys.version[:3])s" for s in [s1, s2, s3]: print "xstring(%r) == %r" % (s, xstring(s)) if __name__ == '__main__': test() ### EOF ### -- xi From tim.one at comcast.net Thu Mar 7 20:29:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 07 Mar 2002 20:29:49 -0500 Subject: Seek fame(*) & fortune(**) as a Python developer In-Reply-To: Message-ID: [Skip Montanaro] > Whether or not you want to be able to check files into the CVS > repository, if you want to contribute, you should probably subscribe > to the python-dev mailing list. You can subscribe here: > > http://mail.python.org/mailman/listinfo/python-dev [Darrell] > Have you changed to acceptance criteria? Guido did, yes. You still have to be approved, but the acceptance criteria changed from "Guido has reason(s) to want you there" to "Guido doesn't have reason(s) to want you somewhere else". > Last time I tried to join that list they told me to go away. "They" would have been one of Barry Warsaw and Jeremy Hylton. If you couldn't figure out from the subscription page that they're the Python-Dev administrators, maybe you're not really ready yet to develop Python . > Filled my time up with other things since then. You could have had more fun writing a Python program to try subscribing every hour under a different one-shot email account! Driving Barry and Jeremy nuts is loads of fun, and easy to do. From abou at cam.org Sat Mar 30 17:58:30 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Sat, 30 Mar 2002 17:58:30 -0500 Subject: seek() Message-ID: <3CA64316.919436E4@cam.org> Is there a kind of seek() function that does the same thing but except of bytes, it seeks for a string? Basically, I want the 5 next bytes after a certain string in a file. Example: Foo:36.50 The data I want (36.50) is located on a web page and since the content of that page always change, I can't get it with seek() because the bytes always change too. I've checked in STRING and RE modules but I can't find a function that checks in a file/webpage, they all need input from a string. -- Zutroi Zatatakowski Commando PACU http://pacu.cjb.net From amoustafa at pobox.com Wed Mar 20 04:29:52 2002 From: amoustafa at pobox.com (Ahmed Moustafa) Date: Wed, 20 Mar 2002 09:29:52 GMT Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> Message-ID: <3C985678.8010200@pobox.com> Peter Hansen wrote: > > 3. The best support for either Java or Python is probably in > their respective newsgroups. Python's is widely known as being > one of the most polite and helpful. The language has been > around a little longer as well, and as it's not largely a > commercial venture this might suggest that the "support" > question is a bit of a red herring. Do you regularly contact > the Microsoft for help with VB, or Sun for help with Java? > (Or did you mean who is "backing" the language, ensuring > its continued viability. The answer to that is twofold: > look at the 11+ year age of Python as historical proof > it's not a flash in the pan, and note it's _open source_ > so it cannot, by definition, lose viability while people > support and use it. You can always get the source.) > For example, where I work, we have JRE for OS/390 (by IBM). Is there a mainframe interpreter for Python? Or, will Jython do? > -- Ahmed Moustafa From erno-news at erno.iki.fi Fri Mar 29 23:21:56 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 30 Mar 2002 06:21:56 +0200 Subject: multicast test program References: Message-ID: In article , Brian Lee writes: | Is there any python code which test multicast? Demo/sockets/mcast.py (predictably enough). -- erno From tejarex at yahoo.com Sat Mar 23 17:57:13 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 23 Mar 2002 22:57:13 GMT Subject: Sorting distionary by value References: <7xd6xwntgx.fsf@ruckus.brouhaha.com> Message-ID: "John Machin" wrote in message news:c76ff6fc.0203231305.7eb20123 at posting.google.com... > "Terry Reedy" wrote in message news:... > > or, I believe, change the last line to > > print counts[w], w > > The basis for whatever it is you believe apparently doesn't include > running the code. Whoops, I misread something and posted too quickly. I normally do run stuff before posting to avoid just this sort of mistake 8-(. From dale at riverhall.NOTHANKS.co.uk Wed Mar 20 10:52:46 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Wed, 20 Mar 2002 15:52:46 +0000 Subject: Develop-test-debug cycle References: Message-ID: <24bh9u4lmkj47e1jufc1c26od21gd0eq50@4ax.com> Gustavo Niemeyer wrote: >You could save this in a file and execute it with "python -i file.py". That's true but it doesn't overcome the problem of having to quit after each error - which is what I find so irritating because it is so time consuming >It seems to work here: > >[niemeyer at ibook niemeyer]$ echo 'a = 1' > mod.py >>>> import mod >>>> mod.a >1 > >[niemeyer at ibook niemeyer]$ echo 'a = 2' > mod.py >>>> reload(mod) > >>>> mod.a >2 This is a rather simple case. More comlex cases with classes don't behave so reliably. >Have you looked at pdb? Yes but this looks pretty much like a primitive form of what Pythonwin does for you. -- Dale Strickland-Clark Riverhall Systems Ltd From mhammond at skippinet.com.au Sun Mar 3 01:43:15 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 03 Mar 2002 06:43:15 GMT Subject: Can somebody kill getpathp for me? References: Message-ID: <3C81C613.8000409@skippinet.com.au> Tim Peters wrote: > [Chris Gonnerman] > Have you tried setting PYTHONHOME? If, e.g., I set PYTHONHOME to \Python22, > then execute python while *in* my \Python21 directory (these both referring > to PythonLabs distros), then Python 2.1.2 comes up with sys.path pointing > entirely at Python 2.2 directories. This is insane, but shows that > PYTHONHOME works the way getpathp.c says it works. insane by design ;) PYTHONHOME was supposed to be a global override. Didn't someone promise to document all this once? >>What I want is a version of either python.exe or python21.dll >>(whichever contains the offending getpathp.c module) with the >>registry-probing code disabled. >> > > If that's what you really want, you'll have to edit getpathp.c and compile > your own Python. Or, use MSVC or some other resource editor to change the single string resource in the compiled Pythonxx.DLL (ie, no need to rebuild the DLL). This will cause a different registry key to be used (by the core, and also by extensions that are registry aware). Mark. From fgeiger at datec.at Wed Mar 13 12:58:57 2002 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 13 Mar 2002 18:58:57 +0100 Subject: python and analyze image format? References: <87henkickf.fsf@lumen.indyrad.iupui.edu> Message-ID: Could PIL be what you are after? See www.pythonware.com Cheers Franz "Michael A. Miller" schrieb im Newsbeitrag news:87henkickf.fsf at lumen.indyrad.iupui.edu... > Anybody know of a python reader/write for analyze image data and > header files? Would you provide a pointer if you do? > > Mike > > -- > Michael A. Miller mmiller3 at iupui.edu > Imaging Sciences, Department of Radiology, IU School of Medicine From grante at visi.com Wed Mar 6 18:37:54 2002 From: grante at visi.com (Grant Edwards) Date: Wed, 06 Mar 2002 23:37:54 GMT Subject: CP4E was Re: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: In article , Geoff Gerrietts wrote: > People don't get smarter as they get older, They certainly do (using just about any definition of "smarter" I can imagine) for the first year or two while the nervous system completes mylenization. After that, you may be able come up with a definition of "smarter" for which your statement is true. > People don't get "smarter" as they get older, though they do develop > strategies for learning that enable them to learn things more quickly. I'd call that getting smarter. :) -- Grant Edwards grante Yow! Imagine--a WORLD at without POODLES... visi.com From bokr at oz.net Tue Mar 19 17:20:39 2002 From: bokr at oz.net (Bengt Richter) Date: 19 Mar 2002 22:20:39 GMT Subject: Newbie: word count and Win32 References: Message-ID: On Tue, 19 Mar 2002 20:51:22 GMT, Joe Christl wrote: >On 19 Mar 2002 20:26:34 GMT, bokr at oz.net (Bengt Richter) wrote: > >> >>From a quick look that[1] script, it looks like it expects to read >>from stdin only. I.e., it says >> >> # iterate over each line on stdin >> for line in sys.stdin.readlines() : >> ... > >I emailed the author of the post (Derrick Hudson) and that was what he told me >too. > >> >>To feed the script's stdin you'll have to redirect or pipe data to it. >>To pipe stuff on windows to a python script you have to run the interpreter >>(python) explicitly one way or another, so I would try: >> >> python count.py < foo.txt >> >>or you could pipe the output of the windows type command, like: >> >> type foo.txt | python count.py > >The < redirect didn't seem to work from a Win32 standpoint. I tried the: > >python count.py < foo.txt >...and... >python count.py foo.txt > >... with failed results. I forgot about the pipe | > The script worked unchanged for me on NT4 using python count.py < foo.txt Were you in a console window with foo.txt in your current directory? (Did you have a foo.txt file with some data? ;-) If you con't have some data handy, use the file itself: python count.py < count.py Try it again, and post a verbatim copy of your screen where it fails (if it does). (to copy windows console text, use Alt=Spacebar>E>K or the system menu in the top left and Edit>Mark. Then select by mousing a box to enclose the text, and press Enter. Then paste that into your post. Then we can see what the "failed results" were ;-) Regards, Bengt Richter From peter at engcorp.com Sun Mar 17 13:13:21 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 17 Mar 2002 13:13:21 -0500 Subject: sunstring References: <0r4l8.22204$P4.1955815@newsread2.prod.itd.earthlink.net> Message-ID: <3C94DCC1.748EDC18@engcorp.com> Billy Ng wrote: > > Would anybody tell me how to do substring in python? Use slices. And look at the string module. Have you gone through the tutorials yet? -Peter From sandskyfly at hotmail.com Mon Mar 11 10:33:48 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 11 Mar 2002 07:33:48 -0800 Subject: scripting Outlook express with Python References: Message-ID: Jonathan Gardner wrote > If you want to customize your mail client, you're using the wrong OS. All > the customizability is over here in Linux, with procmail and sendmail and > fetchmail and all sorts of great stuff that you've never even dreamed of - > even in those really wild dreams where you use your computer for a month > and it doesn't crash once. Your point is well taken. Actually, I've had the move in mind for some time, and am hoping to ease the transition by getting used to the cygwin environment, and using cross platform tools as often as I can. However, I don't think I'm quite ready yet, and if I do make the move I don't know whether it will be to linux or to Mac OS X. At-least-I-can-be-sure-that-python-will-be-around-for-whatever-OS-ly-yrs, Sandy From ron.l.johnson at cox.net Mon Mar 4 02:12:20 2002 From: ron.l.johnson at cox.net (Ron Johnson) Date: Mon, 04 Mar 2002 07:12:20 GMT Subject: Converting mailbox formats Message-ID: Hi, Are there pythonic methods for converting the MH message header format to the mbox message header format? TIA, Ron -- +------------------------------------------------------------+ | Ron Johnson, Jr. Home: ron.l.johnson at cox.net | | Jefferson, LA USA http://ronandheather.dhs.org:81 | | | | 484,246 sq mi are needed for 6 billion people to live, 4 ! ! persons per lot, in lots that are 60'x150'. | ! That is ~ California, Texas and Missouri. ! ! Alternatively, France, Spain and The United Kingdom. | +------------------------------------------------------------+ From eric.brunel at pragmadev.com Mon Mar 11 05:59:52 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 11 Mar 2002 10:59:52 +0000 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> Message-ID: Hans Nowak wrote: > It's not April 1st yet... Considering Brad's article was posted on 2001-07-02, it certainly wasn't at that time... ;-) Can anyone using a recent version of Microsoft development tools confirm whether it's a hoax or not? If it isn't, this is bad news... - eric - From dieter at handshake.de Thu Mar 14 16:12:59 2002 From: dieter at handshake.de (Dieter Maurer) Date: 14 Mar 2002 22:12:59 +0100 Subject: GC thread safe? Message-ID: Several Zope users face crashing Python 2.1.2 (SIGSEGV inside the garbage collector). The problem only occurs when the following conditions are true: * Zope runs in multi-threaded mode * the cyclic garbage collector is not deactivated Is the cyclic garbage collector known to be thread safe? Dieter From theller at python.net Thu Mar 21 13:24:06 2002 From: theller at python.net (Thomas Heller) Date: Thu, 21 Mar 2002 19:24:06 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: "A.M. Kuchling" wrote in message news:slrna9k7u9.mtb.akuchlin at ute.mems-exchange.org... > > PEP 262 still has many, *many* XXX comments marking potential issues > that need to be cleared up before it can be implemented. Most aren't > particulaly complicated, just cases where I'm not sure if a feature is > needed or if it's just extra fluff. > Are you interested in my remarks to the XXX comments *now*? > Once those uncertainties are cleaned up, I'll try to get it > implemented for the Python 2.3 time frame. > Great! Thomas From gimbo at ftech.net Wed Mar 6 10:12:23 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 6 Mar 2002 15:12:23 +0000 Subject: [ANN] istring 1.0.1 released; announce list created In-Reply-To: <15494.11947.195706.267254@beluga.mojam.com> References: <3C86047F.1080601@stroeder.com> <15494.11947.195706.267254@beluga.mojam.com> Message-ID: <20020306151223.GD10985@andy.tynant.ftech.net> On Wed, Mar 06, 2002 at 08:58:51AM -0600, Skip Montanaro wrote: > > Duncan> I vote for (3): > Duncan> db.query("""SELECT foo, bar > Duncan> FROM %(table)s > Duncan> WHERE rsrc_id = %(rsrc_id)s > Duncan> AND name = '%(name)s'" % vars()) > > Which will work most of the time, but fail if name contains any apostrophes. > As was mentioned before, that's why the DB API supports a query method that > does its own variable interpolation. Different databases quote things in > different ways. We seem to be getting mixed up over two seperate issues here, which we should try to keep seperate: 1. Whether $table style string interpolation is a desirable or necessary addition to python. 2. How to do variable interpolation in SQL strings. For my money, issue 2 is addressed as above by Skip (ie let the DB API sort it out), and the question mark over 1 is: why is $table style necessary when we've got %(table) style? -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From jason at jorendorff.com Thu Mar 14 07:17:37 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Thu, 14 Mar 2002 06:17:37 -0600 Subject: Good book on Python? In-Reply-To: Message-ID: Antonis C Koutalos wrote: > I would greatly appreciate information about a good book on python. I > have been programming C for a few years, but I know next to nothing about > python. Therefore, I would appreciate a book that describes the basics of > python as well as the more advanced features of the language. Start with http://www.python.org/doc/current/tut/ You might not need a book. I never bought one. ## Jason Orendorff http://www.jorendorff.com/ From pxl at sonic.net Thu Mar 28 00:50:14 2002 From: pxl at sonic.net (Paul Archibald) Date: Thu, 28 Mar 2002 05:50:14 GMT Subject: C API for modules References: <3CA09F43.80206@erols.com> Message-ID: <3CA2AEFE.BB31C3A5@sonic.net> I am new to python, and am also interested in the c/c++ api. My problem is that when I look at the tutorial code, it says "#include ". I don't have such a file on my Mac. Where can I get it, and what other parts come with it that will help me build c/c++ extensions? "Edward C. Jones" wrote: > Is there some simple way to call functions in modules from C? In > particular, for module struct, how do I call pack, unpack, and calcsize? > > Thanks, > Ed Jones From s.schwarzer at ndh.net Mon Mar 18 15:29:14 2002 From: s.schwarzer at ndh.net (Stefan Schwarzer) Date: Mon, 18 Mar 2002 21:29:14 +0100 Subject: Generating getter methods with exec Message-ID: <3C964E1A.84D5A26B@ndh.net> I would like to generate some getter methods in a class which in fact access a stored dictionary. Unfortunately, I'm not able to get it work. Suppose the following code is in getter_test.py: class GetterTest: def __init__(self): self._dict = {'key1': 'one', 'key2': 'two', 'key3': 'three'} def _make_getters(self, dict_name, key_list): for key in key_list: code = ( "def %(key)s(self):\n" " return self.%(dict_name)s['%(key)s']\n" % vars() ) print code # this seems to be wrong but what should that be? exec code in globals(), self.__dict__ def key3(self): return self._dict['key3'] In the interpreter (Python 2.2) I get: >>> import getter_test >>> gt = getter_test.GetterTest() >>> gt._make_getters('_dict', ['key1', 'key2']) def key1(self): return self._dict['key1'] def key2(self): return self._dict['key2'] >>> gt.key1() Traceback (most recent call last): File "", line 1, in ? TypeError: key1() takes exactly 1 argument (0 given) As can be seen, gt.key1() doesn't behave as expected (at least as expected by me ;-) ). >>> gt.key1(gt) 'one' This works, but needs an additional instance parameter which corresponds to this observation: >>> gt.key1 though I would rather like >>> gt.key3 > Can anyone tell me how I can generate the evaluated code as bound methods instead of functions? Many thanks in advance for any help! :-) Stefan From sdm7g at Virginia.EDU Tue Mar 19 02:50:10 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Tue, 19 Mar 2002 02:50:10 -0500 (EST) Subject: Java and Python In-Reply-To: <3C96E79F.4010802@pobox.com> Message-ID: On Mon, 18 Mar 2002, Ahmed Moustafa wrote: > Delaney, Timothy wrote: > > >>From: Ahmed Moustafa [mailto:amoustafa at pobox.com] > >> > >>1. Where can I find an unbiased comparison between Java and Python? > >> > > > > Nowhere. The best place to look though is > > > > http://www.python.org/doc/Comparisons.html > > > > which has comparisons with various languages. > > > I knew about those articles and I felt they were biased to Python. Well -- you can have biased towards Python or biased towards Java, but you can't get unbiased anywhere! > >>3. Who does support Python? > >> > > > > What type of support are you talking about? If you want commercial support, > > I think ActiveState gives it. If you are talking about who maintains and > > enhances Python, that's the Python development team in general (but with a > > lot of community involvement. > > > I understand Microsystems supports Java. Who does play the same role for > Python? Nobody supports "Java", although often someone supports particular implementations of Java. ( Sun supports J2SE SDK, Apple supports MRJ, and there are open source compiler implementations like IBM's Jikes. ) -- Steve Majewski From erno-news at erno.iki.fi Sat Mar 9 09:09:20 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 09 Mar 2002 16:09:20 +0200 Subject: why is python slow? References: Message-ID: In article , Fernando Pereira writes: | On 3/8/02 12:19 PM, in article kuelivht8g.fsf at lasipalatsi.fi, "Erno Kuusela" | wrote: || In article , Fernando Pereira || writes: || || | Another reason is that a JIT compiler may not help Python as much as Java, || | because [...] || || i think the last time there was an in-depth thread about this, many || people speculated that a jit compiler could infact help python a lot. || (perhaps a jit compiler can help java even more.) || smalltalk and self implementation techniques were discussed. | The irreducible fact is that Python needs extensive runtime type checks, | Java doesn't. yes, java has an advantage in this respect. but still, there is no reason to abandon the idea, since people have previously been quite succesful in making dynamically typed languages execute faster than python currently does. i think one optimization was that you dynamically profile the execution of the program and see if some functions always (or almost always) get the same type of arguments. then you compile a native code equivalent of the function that assumes those frequently encountered types, with a check in the beginning for the mispredicted types case. (for some functions i think it might hep if you take the call site into account, so you'd have a (call site, function) -> optimized-code mapping.) i'm sure there are many more techniques, this is just one that i happen to remember and which seems it could offer a large speedup. -- erno From shalehperry at attbi.com Thu Mar 14 02:34:51 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 13 Mar 2002 23:34:51 -0800 (PST) Subject: Performance problem with filtering In-Reply-To: Message-ID: > > I understand how it works logically. I simply thought there might've been > some tricky C implementation of list comprehensions that improved > performance. > even if it was coded in hand tuned assembly it would be slower than the dictionary method because the algorithm is inherently slow. Every pass of the for i in list loop must make an entire walk of the other list. No matter how fast you make the walking, you still have to walk. Jog a mile, walk a mile it is still a mile. The dictionary version is faster because the key lookup does not have to check every key. From perryrain at hotmail.com Thu Mar 7 18:10:40 2002 From: perryrain at hotmail.com (dskhdskf dsfhs) Date: Thu, 07 Mar 2002 23:10:40 +0000 Subject: marcos and .pyc Message-ID: Is there a feature in the basic python for doing inline marcos (similar to the ones found in C and C++)? Also is there a way to specify where .pyc files are to be deposited? Chris _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From info at researchnetwork.com Thu Mar 7 22:41:42 2002 From: info at researchnetwork.com (ResearchNetwork.com) Date: 8 Mar 2002 03:41:42 -0000 Subject: Research Network Job Site Message-ID: <1015558902.39507.qmail@ech> Expand Your Universe on the Research Network. Research Network is a job site devoted exclusively to professional Researchers and companies who need Researchers. It doesn't matter what industry you specialize in. Research Network encompasses a broad spectrum of industries and we continue to add more every day. For a comprehensive list of industries we work in like Pharmaceutical Research, Marketing Research, Clinical Research, Financial Research, Health Care Research, (to name a few), log on to http://www.researchnetwork.com and discover the infinite possibilities. If your an Employer, stop wasting your valuable time by posting your jobs on generalized job sites that inundate you with inappropriate candidates. If your looking for Scientists, Project Managers, Analysts, Statisticians, Clinical Researchers, Engineers, Planners, Developers, Upper Level Management within a Research function, (to name a few), go to the source and get your research job posting in front of over 1/2 million researchers on our Network. Click on the link below to find the exact research talent you need. http://www.researchnetwork.com/emplogin.cfm If your a professional Researcher and wish to be considered for positions by employers on our network, click on the link below to join the network. http://www.researchnetwork.com Expand Your Universe _______________________________________________________________________ Powered by List Builder To unsubscribe follow the link: http://lb.bcentral.com/ex/manage/subscriberprefs?customerid=20467&subid=CFC8170D57120080&msgnum=1 From rliebsch at cogsci.ucsd.edu Mon Mar 18 19:01:46 2002 From: rliebsch at cogsci.ucsd.edu (Rob Liebscher) Date: 18 Mar 2002 16:01:46 -0800 Subject: Dictionary as non-iterable object? Message-ID: <265fffe3.0203181601.21c10ba@posting.google.com> Hi, My apologies for the simplicity of this question, and if it's been discussed before. (I'm very new to Python.) The deal is this: using the IDLE interpreter (directly from www.python.org), I can do the following: >>> D = {(4, 6): 13, (4, 3): 12, (5, 2): 11, (2, 5): 8, (1, 2): 9} >>> for x,y in D: print D[(x,y)] 13 12 11 8 9 10 >>> Fine, right? Unfortunately, ActiveState's latest version does not allow me to do this, saying that I can't iterate over a dictionary's keys. This happens regardless of how many vars I use: for x, for x,y, and for x,y,z all complain. (IDLE complains on the first and third because of a tuple unpack of the wrong size.) Any ideas? I just want to be able to iterate over all entries in a dictionary that has 2-tuples as keys, as in the above, so a method to do this would be a satisfactory answer. Thanks. From peter at engcorp.com Thu Mar 7 22:19:56 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 07 Mar 2002 22:19:56 -0500 Subject: Module Search Path? References: <3c87e781.62223437@news> Message-ID: <3C882DDC.AAD39898@engcorp.com> brobbins333 at shaw.ca wrote: > > I want to store the modules I have written in their own directory. > When I add it to the search path with sys.path.append the changes are > made for one session only. How can I make permanent changes to the > search path? I am using ActivePython 2.1 (PythonWin) in Win98. You could create a .pth file in the Python directory. See the comments in site.py for details. Alternatively, working with PYTHONPATH would get you there, but it's uglier. From akuchlin at ute.mems-exchange.org Thu Mar 21 13:53:59 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 21 Mar 2002 18:53:59 GMT Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: In article , Thomas Heller wrote: > Are you interested in my remarks to the XXX comments *now*? Of course! --amk From jp at NOSPAMdemonseed.net Fri Mar 8 14:08:20 2002 From: jp at NOSPAMdemonseed.net (jason petrone) Date: Fri, 8 Mar 2002 19:08:20 +0000 Subject: hotmail References: <899f842.0203071410.7a0895c4@posting.google.com> Message-ID: <472b6a.1id.ln@demonseed.net> Anthony_Barker wrote: > I use one written in perl (ya I know...) called gotmail.pl. It works > great but uses curl under linux. You could easily rewrite it in > python. I use gotmail. It works great! jlp From martin at v.loewis.de Sat Mar 30 06:52:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 12:52:05 +0100 Subject: Problem with Tkinter References: Message-ID: "Cyr" writes: > Thanks a lot for the help, I will try it. > By the way, do you know which path is used to search for Tk libraries ? Can > I change it manually in the Module/Setup file (after I ran ./configure) ? Depends on what you mean by "Tk libraries". If you are talking about the shared libraries (libtk83.so), please read your operation system manual on how your operating system finds shared libraries (hint: both LD_LIBRARY_PATH and -Wl,-R options might be considered). If you are talking about the .tcl files that Tk uses at startup: those are found through a compiled-in default (compiled into Tcl). You can use TCL_LIBRARY and TK_LIBRARY to override those locations. If you are talking about the part of sys.path used to find Tkinter.py and friends: this is in Modules/Setup. Regards, Martin From mlammon at nc.rr.com Tue Mar 19 13:01:48 2002 From: mlammon at nc.rr.com (Mike Lammon) Date: Tue, 19 Mar 2002 13:01:48 -0500 Subject: Telnetlib - Clearing/resetting within a Telnet Object Message-ID: <3C977D0C.B925E0EF@nc.rr.com> I am writing a small server program to interact with an external machine. (It is non-unix). The program connects fine. It issues the commands and receives data fine (most of the time). This is the problem. The machine I am connected too sends out system messages, etc to users who are connected (telnet). I can't turn off these system messages so that is not an option. The next time I issue a command from the client side, It will return the data but its not from the current command issued. It returns the next serious of data in sequence. I need a way to clear/reset (without destroying the telnet session) , then issue the current command. Any ideas? Thanks Mike From mxl at fluent.com Tue Mar 19 14:17:39 2002 From: mxl at fluent.com (Mohammed Lazreg) Date: Tue, 19 Mar 2002 14:17:39 -0500 Subject: nested_scopes with execfile References: <10ecacee.0203190845.4fa4e35d@posting.google.com> Message-ID: <3C978ED3.E4AE32EC@fluent.com> Here is what I believe is happening: when the interpreter enters the code block of f2 and finds f1 name, it tries to resolve it using the nearest enclosing scope. So if you execute Test2.py alone it will work because the enclosing scope is Test2.py itself which does define f1 , but when you try to load Test2.py from Test1.py the nearest enclosing scope of f2 scope is Test1.py which does not define f1, hence the error.... If you change your Test2.py to this, it will works in both cases: ----------------- def f1(): print "OK it works" def f2(arg): arg() f2(f1) ---------------- $ ../Python-2.2/python Test2.py OK it works $ ../Python-2.2/python Test1.py OK it works Mohamed Amir Hadar wrote: > Hi > > I've encountered a problem when executing a file within a function: > > #----- Test1.py ------------------ > from __future__ import nested_scopes > > def f(): > execfile("Test2.py") > > f() > # EOF Test1.py ------------------- > > #--------Test2.py ---------------- > def f1(): > print "OK it works" > def f2(): > f1() > > f2() > #EOF Test2.py -------------------- > > When executing the Test1.py the following error is displayed: > Traceback (most recent call last): > File "", line 1, in ? > File "C:\PROGRA~1\Python22\Test1.py", line 6, in ? > f() > File "C:\PROGRA~1\Python22\Test1.py", line 4, in f > execfile("Test2.py"); > File "Test2.py", line 8, in ? > f2() > File "Test2.py", line 6, in f2 > f1() > NameError: global name 'f1' is not defined > > The reson that I need this is because I want to make a "Load" funtion > that will execute the given file (e.g. Load("Yada.py")) and then will > run a function in that file (e.g. def Init():). > > In the example I gave the second file ("Test2.py") is loaded to the > local environment of the function f() in the first file (Test1.py). > Therefore the functions f1 and f2 are in that env. Now, When f2 calls > f1 it should resolve its variables in the enclosing environment which > is the env of f (Test1.py) but it doen't. > > Help Me. > Amir. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > This message has been 'sanitized'. This means that potentially > dangerous content has been rewritten or removed. The following > log describes which actions were taken. > > [ score: 10 ] > 00189 Split long word(s) in header. > > Anomy 0.0.0 : sanitizer.pl > $Id: sanitizer.pl,v 1.35 2001/02/01 00:10:46 bre Exp $ From mgash at trisystems.co.uk Thu Mar 28 09:23:40 2002 From: mgash at trisystems.co.uk (Mark Gash) Date: Thu, 28 Mar 2002 14:23:40 -0000 Subject: WIN32 Performance Data Helper problem Message-ID: <31575A892FF6D1118F5800600846864DCC7780@intrepid> Platform: Windows NT 4 (server and workstation) Dev Environment: PythonWin 2.2 win32all-146 I have written a script which monitors the disk space for Windows NT machines. If the counter exceeds a set limit, then an email message is sent to the administrator stating which machine and local disk is 'getting full'. Once the comparisons have completed, the script sleeps for 2 hours then re-enters the performance data collection/checking, sleeps for 2 hours.... ad infinitum The problem is that the script does not work on NT 4 Servers, although it works on NT4 clients. When the script is run on an NT 4 Server, the script enters the while loop and fails at the performance collection phase. The more serious issue is that there is no apparent errors thrown either by Python or by NT itself. The script prints the line "Entering the while loop" (as included in the extracted script) but then does nothing else. I have attempted to research into the problem, and found that the script failed on some workstations in a similar manner. I pinpointed this problem down to being a missing pdh.dll from the %WINNT%/system32 directory. Once this file was added, the clients worked ok. Although I have attempted this resolution with the Servers, they are still failing. A brief extract of the script is contained below, [PS I am a newbie to Python, so please try not to be too harsh about by coding ;-) ] .Also detailed is the log created when the Server ran the script. If required, the full script can be posted. Any assistance in this matter would be gratefully received. import sys import os import string # required for string manipulation import smtplib # required for the emailing bits import win32pdhutil # for the Performance Data Helper(utils) methods import win32pdh # for the Performance Data Helper methods import time # guess what? needed for time functions (sleep and now) import ConfigParser # needed to read/write the ini files import socket # needed for the gethostname function import win32api # Two Win32 API's that are needed to query what drives import win32file # are both fixed and on the local machine def machinename(): #get the hostname of the local machine return socket.gethostname() def main(): machinename = machinename() # analyse what drives are local HDD drives = [drive for drive in win32api.GetLogicalDriveStrings().split('\x00')[:-1] if win32file.GetDriveType(drive) == win32file.DRIVE_FIXED] #prepare the dictionary, depending on number of local drives for drive in drives: drive = drive[0] drive = drive + ":" counter[drive] = 0 while 1: spam.logfile.write(now() + " Entering while loop " + "\n") #read in performance data #compare values from performance data with the preset hwm # if the perf. data exceeds the hwm, then send an email alert for drive in drives: drive = drive[0] drive = drive + ":" # THIS IS THE LINE CAUSING PROBLEMS WITH NT SERVERS perfdata = win32pdhutil.GetPerformanceAttributes("LogicalDisk","% Free Space", "0/"+drive, -1, 256, machinename ) # END - THIS IS THE LINE CAUSING PROBLEMS WITH NT SERVERS if perfdata <= setup.freelwmpercentage: counter[drive] += 1 else: #do nothing pass if perfdata > setup.freelwmpercentage and counter[drive] > 0: #gradually return the counter back to zero as everything is rosy... counter[drive] -= 1 else: #do nothing pass if counter[drive] == 0: #do nothing as everything is 'hunky doory' pass elif counter[drive] > 11: spam.logfile.write(now() + " Disk usage exceeds LWM (minor)" + "\n") dcsend.send(drive, machinename, "LWM") elif perfdata < setup.freehwmpercentage: spam.logfile.write(now() + " Disk usage exceeds HWM (MAJOR)" + "\n") dcsend.send(drive, machinename, "HWM") time.sleep(7200) #wait for 2 hours then go back to the while loop.... #tidy up and close all open files spam.resultsclose() if __name__ == '__main__': global strDirName strDirName = ((os.path.dirname(os.path.abspath(sys.argv[0]))) + "\\") main() The output from the log looks like this:- *****************Start of Disk Checker Log File***************** Wed Mar 27 11:02:36 2002 License Checker started Wed Mar 27 11:02:37 2002 Entering while loop Kind Regards, Mark Gash Consultant TriSystems Ltd. 020 7264 0440 mgash at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From bokr at oz.net Mon Mar 4 01:26:13 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Mar 2002 06:26:13 GMT Subject: mx odbc result strings with special characters? References: <24c39b2c.0203021850.7679418c@posting.google.com> <24c39b2c.0203031100.33d57b3d@posting.google.com> Message-ID: On Sun, 03 Mar 2002 19:32:03 GMT, "Fredrik Lundh" wrote: >Alexander Jerusalem wrote: > >> Ok, thanks for your reply. Here's my output: >> >> >>> import mx.ODBC.Windows as odbc >> >>> con = odbc.connect("se", "scienceexile", "x") >> >>> c = con.cursor() >> >>> c.execute("select * from country") >> >>> print c.fetchone() >> ('aa1', '\xd6sterreich-Ungarn', None, None) >> >>> c.close() >> >>> con.close() >> >> And it's the same when I write the resultset to a file, so I don't >> believe that it's just a display problem. > >on the other hand: > >>>> print '\xd6sterreich-Ungarn' >?sterreich-Ungarn > More illustration (clipped from IDLE with 2.1) using example data from above: >>> print ('aa1', '\xd6sterreich-Ungarn', None, None) ('aa1', '\xd6sterreich-Ungarn', None, None) >>> print ('aa1', '\xd6sterreich-Ungarn', None, None)[1] ?sterreich-Ungarn and >>> oe = ('aa1', '\xd6sterreich-Ungarn', None, None)[1][0] >>> print oe, `oe`, str(oe), repr(oe), (oe, hex(ord(oe))) ? '\xd6' ? '\xd6' ('\xd6', '0xd6') ^^^^^^ I.e., it's not the data character, it's the presentation that depends on context here. HTH Regards, Bengt Richter >more info here: > > http://www.python.org/doc/current/tut/node5.html > > "The interpreter prints the result of string operations in the > same way as they are typed for input: inside quotes, and > with quotes and other funny characters escaped by back- > slashes, to show the precise value" > > http://www.python.org/doc/current/ref/strings.html > http://www.python.org/doc/current/ref/exprstmts.html > http://www.python.org/doc/current/ref/print.html > (etc) > > > > > > From philh at comuno.freeserve.co.uk Wed Mar 27 12:40:09 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Wed, 27 Mar 2002 17:40:09 +0000 Subject: OpenContact.org References: <3CA1E66E.1070205@opencontact.org> Message-ID: On Wed, 27 Mar 2002 15:35:32 GMT, William Levin wrote: >Hello, > >This is an invitation for Open Source enthusiasts and contact management >software developers to join OpenContact.org, a new online forum for the >discussion of contact management systems. > >The ultimate goal of OpenContact.org is to explore options for >integrating a centralized contact management database into the operating >system; and to develop an extensive set of standard fields (akin to >vCard) for universally compatible contact management. This would allow >every third-party application on a computer to access the same contact >data set, and eliminate the need to import and export contact data on a >single system. That sounds interesting. I might add this sort of functionality to Herbivore at some point. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From narnett at mccmedia.com Sun Mar 24 22:43:36 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Sun, 24 Mar 2002 19:43:36 -0800 Subject: Debugging on windows via print statements -- reliable? Message-ID: As I try to track down why my code is getting stuck (in a situation where it could take ages to step through in the debugger), I'm using print statements so that I can see where it's just been before it freezes. Trouble is, I'm not seeing much consistency in when (how many iterations) or where (in the code) it stops responding. Now I'm wondering if way of creating signposts is reliable. Is it possible that it's actually hanging up somewhere without actually outputting some of my print statements, even though they've been processed? Sometimes, I'm only getting part of the output of a print statement, which seems truly weird. If I had multiple threads, perhaps I could be clobbering the thread that's printing my signposts, but I'm not... Is there something on Windows (Win2K, to be exact) that I need to do to make sure that print statements are actually output as soon as the statement is executed. Thanks in advance... Nick -- narnett at mccmedia.com (408) 904-7198 From pereira at cis.upenn.edu Thu Mar 7 21:59:45 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Thu, 07 Mar 2002 21:59:45 -0500 Subject: why is python slow? References: Message-ID: On 3/7/02 9:41 PM, in article a2972632.0203071841.7cd09181 at posting.google.com, "les ander" wrote: > i am just curious as to why different programming languages have different > speed. I understand that if a language has an extensive grammar > (such as c++) the compiler would take longer. But what about execution? You will not get a good answer to this from a newsgroup. No one can summarize for you what takes years of education and experience in programming language and implementation to learn. The only way to become informed on these questions is to study programming languages seriously. > why is a perl program faster than similar python program? Says who? What programs? What's a "similar" program? To discuss these questions scientifically rather than with sound bites, one needs to define carefully the questions being asked, the experiments that will answer those questions, the experimental conditions (implementations, hardware platforms), and the supporting statistical analysis. Benchmarking is a difficult experimental craft. Relative speeds depend on problem, experimental conditions, etc. That's why so much effort and discussion went into developing processor benchmarks like SPECint and SPECfp. And Even then there are many disagreements on how to interpret them. >For example > when java came out it use to be pretty slow, but now it is pretty fast. How > was this speed-up acheived and why is it not possible to have such a speed up > for python? Again, the answers to these questions, and whether the questions themselves make any sense, require detailed study of many topics in language implementation. No one can give you a newsgroup-posting-sized answer. If they do, you shouldn't trust them. Benchmarking-is-harder-than-/.-ing-ly yours -- F From tejarex at yahoo.com Fri Mar 29 18:37:01 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 29 Mar 2002 23:37:01 GMT Subject: List problem References: Message-ID: "Jon Cosby" wrote in message news:a82mlc$ja1$1 at slb6.atl.mindspring.net... > Can anyone se why this is coming up empty in the "cols" list? I've tried > something similar in the interpreter, and everything here looks right. What happens if you paste exactly this text into the interpreter (on PC, turn off fast pasting)? (Answer: syntax errors, see below.) ###################################################################### ## > # WordSquare > # Build word squares from initial word > # Word dictionary > dict = "c:\data\dict.txt" As I said elsewhere, use forward slashes / to be safe, concise, and more portable. > firstword = input("Enter first word (enclosed in quotes): ") firstword = raw_input("Enter first word (do not enclose in quotes): ") is safer and easier for user. > lword = len(firstword) > words = [] > cols = [] > rows = [] > > f = open(dict, "r") > for line in f.readlines(): > if len(line[:-1]) == lword: > words.append(line[:-1]) # add 'word = line[:-1]' before if and sub in nect too two lines slightly faster > f.close() Need blank line to run interactively If words were sorted by len, you could read in only those of proper length > for i in range(lword): > cols.append([]) > rows.append([]) > rows[0].append(firstword) > > # Generate an array of words with matching first letters > for i in range(lword): > for word in words: > if word[0] == firstword[i]: # Matches not found > cols[i].append(word) As written, without indent of 'cols...' after 'if', this has a syntax error. This suggests that this is not exactly the file that produced the output below. If words of given length were sorted, you could grab just those needed. > print len(words) > print cols > > ###################################################################### > > C:\Python21>python projects\wordsquare.py > Enter first word (enclosed in quotes): "hello" > 4220 > [[], [], [], [], []] Try print words[0:10] to see what actually iterating through. # I pasted following into interpreter and got output marked by # firstword = "cow" # cow, ore, wee/wet make square lword = len(firstword) words = ['act', 'art', 'boo', 'cat', 'cad', 'coo', 'cow', 'oft', 'opt', 'ore', 'wee', 'wet'] cols = [] rows = [] # delete readin from file stuff for i in range(lword): cols.append([]) rows.append([]) rows[0].append(firstword) # Generate an array of words with matching first letters for i in range(lword): for word in words: if word[0] == firstword[i]: # Matches not found cols[i].append(word) print len(words) #12 print cols #[['cat', 'cad', 'coo', 'cow'], ['oft', 'opt', 'ore'], ['wee', 'wet']] so this much of program works. Terry J. Reedy From newsfroups at jerf.org Tue Mar 5 12:16:18 2002 From: newsfroups at jerf.org (Jeremy Bowers) Date: Tue, 05 Mar 2002 17:16:18 GMT Subject: Get reference to "owner" References: <20020305072655.GA1525@lilith.hqd-internal> <625h8.3294$tg2.206482@e3500-atl1.usenetserver.com> Message-ID: <3C84FD78.9070507@jerf.org> Robert Oschler wrote: > Gerhard, > > Excellent!!! Never expected to find a language that could do this and it > something I've wanted very badly for a long time. Yes that's exactly what I > meant. B knows about the A that owns it without having to artificially pass > a reference of A to B during construction. If I'm reading that correctly, be sure you understand the limitation of that implementation: B is actually getting a reference to the thing that's creating it, which may or may NOT necessarily be it's parent. And that only if the thing that's creating it calls itself "self" (which is only convention, not requirement in Python). Attempting to create an instance of B() directly in a function fails with a keyerror, unless you have a "self" in that function. You may consider it somewhat inconvenient, but in accordance with Python's "explicit rather then implicit" philosophy, you're probably better off passing an explicit reference to the parent. It's clear, it's flexible, it's standard, it doesn't have the laundry list of limitations and caveats the sample implementation does, and it also allows moving the parent pointer around, which is often useful. The only strike against it is a little extra typing; very little if there's a parent class you can move it into. Also consider looking at the weakref module; trees with parent pointers are one of the defining reasons for the existance of that module. From sholden at holdenweb.com Wed Mar 27 10:22:10 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 27 Mar 2002 10:22:10 -0500 Subject: Random... References: Message-ID: <%slo8.20800$cB5.20607@atlpnn01.usenetserver.com> "A.M. Kuchling" wrote in message news:slrnaa3nvr.bj2.akuchlin at ute.mems-exchange.org... > In article , > Chris Gonnerman wrote: > > Perhaps I'm stupid... what the heck is wrong with the OP's message? > > Original material was added at the top of the post, and the entire > message being responded to was quoted below. Usenet convention is to > do it the way I'm writing this message, by quoting only the few lines > of text I'm responding to and writing my answer below. Doing this way > makes it much easier to pick up a thread in the middle, saves > bandwidth, and users reading the digested version of python-list don't > have to plow through 187 quoted copies of the same text again and > again. > > I also view top-posting as rude; it implies the top-posting person's > time is so valuable they can't be bothered to edit down the quoted > text, but it's OK to waste *my* time by making me dig through levels > upon levels of quoted material. > While you correctly interpret netiquette, might it not have been more considerate to this list if you had *mailed* the OP rather than giving her/him a public dressing down which many others also had to read unnecessarily? Or is it OK to waste *my* time by chastising the OP publicly? [I am aware the same applies to this post :-)] netiquette-means-politeness-ly y'rs - steve From sab at NOSPAM.freeuk.com Sat Mar 23 06:51:47 2002 From: sab at NOSPAM.freeuk.com (G. Willoughby) Date: Sat, 23 Mar 2002 11:51:47 -0000 Subject: how do i get RGB from HEX? References: Message-ID: Thanks m8, thats great :) G. Willoughby "Robin Becker" wrote in message news:WCeE3TAUC2m8Ewar at jessikat.demon.co.uk... > In article , G. Willoughby > writes > >Hi, > > i have been trying to do this for to long now, i know there is an easy > >way, please somebody put me out of my misery! i need to get the RGB value of > >a HEX number (eg, #DCDCDC). can anyone help? > > > >thanks, > > > >G. Willoughby > > > > > split into pairs after stripping the # > > >>> def rgb(h): > ... n = eval('0x'+h[1:]) > ... return (n>>16)&0xff, (n>>8)&0xff, n&0xff > ... > >>> rgb('#DCDC0a') > (220, 220, 220) > >>> rgb('#DCDC0a') > (220, 220, 10) > >>> > > I'm sure there's probably some better way, but the above works. > -- > Robin Becker From geoff at gerrietts.net Wed Mar 6 13:32:20 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Wed, 6 Mar 2002 10:32:20 -0800 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <3C8623B9.3000504@sympatico.ca> References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> Message-ID: <20020306183220.GA20722@isis.gerrietts.net> Quoting Ramkumar Kashyap (rkashyap at sympatico.ca): > This is extremely non-intuitive to most people. Most 5,6,7 year olds > can speak fluently in their native languages, but how many of them could > tell you about vowels, consonants, nouns, verbs, adjectives. In fact > quite a few of them speak multiple languages, can easily differentiate > sentence structures in those languages, but would be hard-pressed to > give defintions of the above. > > So how come in programming, we ALWAYS jump into the constructs of a > language, rather than just doing, gaining proficiency and then > understanding how it is put together? I think the analogy here is interesting and useful, and bears consideration. I think that what you're asking for -- a reexamination of the pedagogy surrounding computer programming -- is useful. I would hesitate to suggest that your methodology is exactly appropriate, though. Here's why: - Go speak to a five or six year old child for a few hours. Engage them in any conversation you like, but make them talk, make them use the language for an expressive purpose. Their facility with the language is reasonable at this age, but far from mastery. Only the mentally disabled standardize at this level; even the stupid standardize at grade 5 or older. - Observe a two or three year old. Engage this child in conversation. It won't last long, but try it. For the space of around three years, a child is immersed almost constantly, from waking to sleep, and even sometimes while asleep, in language. For those first three years, the child is almost completely incapable of making him or herself understood. Some of this is the challenge of spoken language, the challenge of making your voice modulate to form the right sounds. Much research exists to show how young children can learn to sign long before they can learn to speak; if you eliminate the difficulty of speaking, you might get it down to age 2 or so. That's still 2 years in which the child can barely be understood if at all, and another three before the most basic constructs are reliably produced. People don't get smarter as they get older, they just have a better foundation for building on. It would be just as difficult for someone to learn programming through reading or transcribing lots of text as it would be for someone to learn French by riding the Metro all day long. People don't get "smarter" as they get older, though they do develop strategies for learning that enable them to learn things more quickly. Most of those strategies revolve around identifying patterns early, and spending most of the learning time exploring the "borderline behavior" that describes the limits of the pattern. That's why we go into constructs early, because those are the patterns. The next step for the educated learner is to explore the limits of these patterns -- what they can and can't do. This is where a great deal of practice can be immensely useful. A heavily practice-based pedagogy could be a very good thing, especially if the practical applications were designed to explore recently-introduced concepts to show when the pattern applies, and when it does not. My belief is that most people find computer programming to be difficult because logic is not the natural way people think; it is a forced mode. People tend to think intuitively, using "gut feelings" and good guesswork. That's the way we tend to summarize the knowledge of our experiences: as gut feelings. Expressing things in a purely logical fashion is consequently difficult for people, and very few ever receive formal training in logic. What's worse is that trying to teach logic at the fundamental level doesn't immediately apply. Logic itself is a tool that a person must learn to use, and could easily fill several courses by itself. -- Geoff Gerrietts "Punctuality is the virtue of the bored." --Evelyn Waugh From koji at twinsun.com Wed Mar 20 05:04:16 2002 From: koji at twinsun.com (Koji Nobumoto) Date: 20 Mar 2002 02:04:16 -0800 Subject: how to ask different DNS for gethostbyname? Message-ID: <8de6d3da.0203200204.31b083d9@posting.google.com> Dear All, Is there any way to use a DNS which is not looked up when I just use the socket.gethostbyname(), without changing /etc/resolv.conf or any system configuration? Thanks in advice Koji From logstx at bellatlantic.net Sat Mar 9 15:51:02 2002 From: logstx at bellatlantic.net (logistix) Date: Sat, 09 Mar 2002 20:51:02 GMT Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> Message-ID: I ain't no lisp expert (so please don't yell at me Paul F. ; ) ), but the interpreter is a read-eval-apply loop. 1. A statement is READ in 2. The arguments are EVALuated (unless short circuited by a quote) 3. The evaluated arguements are APPLYed to the function, result is returned Once think about it in those terms, it's pretty easy to reproduce in Python: >>> import types >>> def printf(x, *y): print x % y >>> def readEvalApply(list): for fun in functions: function = fun[0] arguments = fun[1] if type(arguments) == types.StringType: arguments = eval(arguments) apply(function, arguments) >>> foo = "bar" >>> funs = [ (printf, ("%s", foo) ), # not quoted, foo eval'ed now (printf, "('%s', foo)" ) #quoted, foo eval'd later ] >>> readEvalApply(funs) bar bar >>> foo = "xxx" >>> readEvalApply(funs) bar xxx -- - "N Becker" wrote in message news:1f5252d4.0203080721.3bfc5c14 at posting.google.com... > Back in 1999, I asked "where is quote?". I was looking for > a way to quote a function (delay evaluation). > > I wonder if there is anything new. It looks to me that the > best answer is to use lambda. > > example: > > def f(): > return lambda: os.chmod(""/root/.rhosts", 0644) > > def g(): > f() From duncan at NOSPAMrcp.co.uk Fri Mar 8 06:00:13 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 8 Mar 2002 11:00:13 +0000 (UTC) Subject: Order of constructor/destructor invocation References: Message-ID: "Reginald B. Charney" wrote in news:R29h8.5988$aP6.6654 at rwcrnsc54: > Brett is exactly right. I am using an approach that is valid and > elegant in C++. Since I am fairly new to Python, I had assumed it > handled contructors/destructors in an ordered (i.e. deterministic) > fashion. It seems not. May I just point out that, although the order of destruction of stack based variables is well defined in C++, the way you are using the destructors is most certainly not elegant. Destructors are called either when the block exits normally, or when an exception is raised. If a C++ destructor ever throws an exception when in the exception unwinding state then the world comes to an end (i.e. your program is immediately terminated). For this reason, something apparently as innocuous as printing a string should never be done from inside a C++ destructor without a lot of safety nets. -- 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 jdm352 at mail.usask.ca Mon Mar 11 23:25:15 2002 From: jdm352 at mail.usask.ca (Jim Meier) Date: Tue, 12 Mar 2002 04:25:15 GMT Subject: MacPython 2.2 errors after default installation .. ? Message-ID: Hi, I just installed MacPython22 from the full archive installer (this powerbook is not on the net), but I can't get any .py files to execute and double clicking the PythonInterpreterClassic icon tells me: "The document 'PythonInterpreterClasic" could not be opened, because the application "Unknown Python Document" could not be found. Could not find a translation extension with appropriate translators." ConfigurePythonClassic gives a similarly meaningless (to me) error: "The applicaton "ConfigurePythonClassic" could not be opened because "NavigationLib" could not be found" Did I do something wrong during the install? Os 8.1, Powerbook 5300ce 32 MB Thanks, -Jim From emailing at calltoaction.com.ar Mon Mar 25 12:03:28 2002 From: emailing at calltoaction.com.ar (SCI E-mailing) Date: Mon, 25 Mar 2002 14:03:28 -0300 Subject: Conozca SCI E-mailing Message-ID: <411077-22002312517328642@calltoaction.com.ar> -------------- next part -------------- An HTML attachment was scrubbed... URL: From phd at phd.pp.ru Sun Mar 17 06:43:02 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sun, 17 Mar 2002 14:43:02 +0300 Subject: Where to download bugfix for email Module? In-Reply-To: ; from usenet@thinkspot.net on Sun, Mar 17, 2002 at 12:35:43AM -0800 References: Message-ID: <20020317144302.A27683@phd.pp.ru> On Sun, Mar 17, 2002 at 12:35:43AM -0800, Sheila King wrote: > However, I can't figure out where this latest code is or how to download > it. CVSROOT=":pserver:anonymous at cvs.mimelib.sourceforge.net:/cvsroot/mimelib" export CVSROOT cvs login cvs checkout mimelib New code is in mimelib/email directory. If you still will have troubles, I can tar and send my copy to you. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From bokr at oz.net Thu Mar 28 21:00:03 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Mar 2002 02:00:03 GMT Subject: mutliple search and replace References: Message-ID: On 28 Mar 2002 04:53:02 GMT, bokr at oz.net (Bengt Richter) wrote: >On Wed, 27 Mar 2002 18:13:48 -0800, "Emile van Sebille" wrote: > >>Trung Hoang >>> Suppose i have a map (or two lists). is it possible to make a sweep >>through >>> a string to find all occurances of key's in the map then replace them >>all in >>> one sweep? >>> >> >>>>> d = {'one':'een','two':'twee','three':'drie','four':'vier'} >>>>> s = "one two buckle my shoe three four je t'adore" >>>>> ' '.join([d.get(w,w) for w in s.split()]) >>"een twee buckle my shoe drie vier je t'adore" >> >> >Nice. Here's a variant that doesn't use delimiters or >modify white space (key order could make a difference, >depending on key overlap): > > >>> import re > >>> d = {'one':'een','two':'twee','three':'drie','four':'vier'} > >>> resp = re.compile('('+'|'.join(d.keys())+')') > >>> s = "one two buckle my shoe three four je t'adore" > >>> ''.join([d.get(w,w) for w in resp.split(s)]) > "een twee buckle my shoe drie vier je t'adore" > >>> s = "one.two+buckle_my_shoe,three-four&je_t'adore" > >>> ''.join([d.get(w,w) for w in resp.split(s)]) > "een.twee+buckle_my_shoe,drie-vier&je_t'adore" > Here is something to deal with the key order problem (i.e., if one key is a substring of another. You have to sort by length to get maximal or minimal matching. This is for maximal: >>> def dirinterp(s,d): ... import re ... klist = [(-len(k),k) for k in d.keys()] ... klist.sort() ... resp = re.compile('('+'|'.join([k for l,k in klist])+')') ... return ''.join([kv.get(w,w) for w in resp.split(s)]) ... >>> subdir = {"sub":"","substring":""} >>> dirinterp("Will sub or substring be replaced?",subdir) 'Will or be replaced?' >>> dirinterp("Will substring or sub be replaced?",subdir) 'Will or be replaced?' This is hardly tested at all, but I guess it could be handy. No reason you couldn't have keys in the form '$xxx' or '$XXX$', etc., either ;-) What else needs to be fixed? (Yes, think of a better name ;-) Regards, Bengt Richter From martin at v.loewis.de Mon Mar 11 00:32:19 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 11 Mar 2002 06:32:19 +0100 Subject: Iterating over unicode strings References: <3C8C3136.9050507@sharma-home.net> Message-ID: Arun Sharma writes: > line = u"??????|| ?????????????????? ?????????????" > for c in line: > print c > > fails miserably. What is the right way to do it ? I would also like to > be able to slice the string i.e. line[i] to get the i'th character. I'm not sure what you expect to happen, but I believe your program works "correctly": it prints one character at a time. Now, the question is: what did you want to happen? Apparently, you want to use UTF-8 in your string literal. This is currently not directly supported - Unicode literals are Latin-1 encoded. Instead, use line = unicode("your text", "utf-8") HTH, Martin From fredrik at pythonware.com Mon Mar 11 11:44:38 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 11 Mar 2002 16:44:38 GMT Subject: Pyhon and PIL References: Message-ID: Fran?ois Pinard wrote: > Maybe this would work? > > import Image > Image.open('yellow.bmp').convert('L').point(255*[0] + [255]) \ > .convert('1').save('yellow.bmp') footnote: in this specific case, you can point & convert in one operation. or in other words, point(255*[0] + [255]).convert('1') can be written as: point(255*[0] + [255], '1') From gh_pythonlist at gmx.de Wed Mar 13 13:52:36 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 13 Mar 2002 19:52:36 +0100 Subject: Has Mark Hammond attained pariah status yet? In-Reply-To: <20020313092857.4765dd0d.logiplexsoftware@earthlink.net> References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> <3C8F1D74.10802@mxm.dk> <20020313092857.4765dd0d.logiplexsoftware@earthlink.net> Message-ID: <20020313185236.GB1227@lilith.hqd-internal> Le 13/03/02 ? 09:28, Cliff Wells ?crivit: > On Wed, 13 Mar 2002 09:35:48 +0000 > Max M wrote: > > > This could also just be a sign that there is interrest, but the people > > using win32all might not be able to publish a build themself? > > > > Not everybody is as knowledgable as Mark, Even though we work on the > > superior Windows platform ;-) > > And quite possibly because not many people using the superior Windows > platform have a C compiler available to them. Probably due to > thoughtfulness on Microsoft's part ;) There are plenty of free C compilers for Windows: mingw, Borland, lcc-win32. lcc-win32 even comes with an IDE. If you dig long enough on the Microsoft site, you can (at least you could at one time) even download a commandline version of the MS compiler. AFAIK the commandline tools of the .NET SDK are also available at no charge. Apart from that, many people might fear that hacking the internals of a COM implementation might make their head explode. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 14.5 ?C Wind: 1.2 m/s From maxm at mxm.dk Wed Mar 13 06:29:04 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 11:29:04 +0000 Subject: dictonary References: <3C8F27DC.F69B1F54@stud.cs.uit.no> Message-ID: <3C8F3800.3070002@mxm.dk> Gerhard H?ring wrote: >>db = _mysql.connect() >>string = { >> hello:'wow', >> something:'nothing', >> nothing : 'something', >> number : 5, >> name : 'daniel'} >> > This is one way to do it, I bet there's a better one: > > dict = {'name': 'Andy', 'age': 39} > > columns = ",".join(dict.keys()) > # I hope using only %s works for MySQLdb. It does work like this for pyPgSQL. > placeholders = ",".join(['%(' + k + ')s' for k in dict.keys()]) > sql = "insert into table(" + columns + ") values (" + placeholders + ")" A bit more readable perhaps? keys = dict.keys() vals = dict.vals() sql = "insert into table(%s) values (%s)" % ( ','.join(keys), ','.join(list(len(keys)*'?')) ) cursor.execute(sql, vals) regards Max M From robin at jessikat.fsnet.co.uk Mon Mar 11 05:16:56 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 11 Mar 2002 10:16:56 +0000 Subject: distutils install control Message-ID: I would like to distribute various modules using distutils, but seem to lack documentation/support for fine control over which modules/submodules get included and so on. For example: include package x.y but have module x.y.z included as a pyc file (for security) include package a.b but exclude particular modules eg a.b.c generate a manifest of an install. This seems to be something to do with source distributions, but I would like manifests for the installed stuff. -- Robin Becker From jwilhelm at outsourcefinancial.com Fri Mar 1 13:12:42 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 01 Mar 2002 11:12:42 -0700 Subject: Problems with multipart messages w/email class Message-ID: <1015006362.1673.7.camel@jwilhelm.ofsloans.com> I'm trying to send an email via the email class in Python 2.2 with an attached PDF. Easy feat, I assume. However, email.Generator is having problems in _handle_multipart() (Caused by some strange __getitem__ error in Message) >>> outer.get_payload() >>> That works fine. However... >>> for part in outer.get_payload(): ... print "Blah" ... Traceback (most recent call last): File "", line 1, in ? File "/opt/python/lib/python2.2/email/Message.py", line 151, in __getitem__ return self.get(name) File "/opt/python/lib/python2.2/email/Message.py", line 214, in get name = name.lower() AttributeError: 'int' object has no attribute 'lower' >>> I originally found this error because of this traceback: Traceback (most recent call last): File "", line 1, in ? File "/opt/python/lib/python2.2/email/Message.py", line 59, in as_string g(self, unixfrom=unixfrom) File "/opt/python/lib/python2.2/email/Generator.py", line 83, in __call__ self._write(msg) File "/opt/python/lib/python2.2/email/Generator.py", line 104, in _write self._dispatch(msg) File "/opt/python/lib/python2.2/email/Generator.py", line 134, in _dispatch meth(msg) File "/opt/python/lib/python2.2/email/Generator.py", line 240, in _handle_multipart for part in msg.get_payload(): File "/opt/python/lib/python2.2/email/Message.py", line 151, in __getitem__ return self.get(name) File "/opt/python/lib/python2.2/email/Message.py", line 214, in get name = name.lower() AttributeError: 'int' object has no attribute 'lower' I got this from calling message.as_string() I can provide my code used to generate the email if necessarry, however I don't believe it should be. I derived my code directly from an example in the email documentation. Any help would be appreciated. --Joseph Wilhelm From cliechti at gmx.net Mon Mar 25 15:25:05 2002 From: cliechti at gmx.net (Chris Liechti) Date: 25 Mar 2002 21:25:05 +0100 Subject: reading in ints from binary files References: Message-ID: "Bill" wrote in news:a7ns1d$mi1$1 @nntp1.jpl.nasa.gov: > Quick Newb question: > > How do I read in integers from binary files? readlines() reads returns > the data in as a string. I can manipulate the string to get the > desired result. However, is there an easier way of doing this? I > currently do something like: > > f=open('file', 'rb') > s = f.readline() > l = list(s[0:-1]) > l.reverse() > a = array.array('h', ''.join(l)) > > There's gotta be an easier way. i usualy use the struct module. a = struct.unpack(" From duncan at NOSPAMrcp.co.uk Tue Mar 19 05:42:34 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 19 Mar 2002 10:42:34 +0000 (UTC) Subject: Generating getter methods with exec References: <3C964E1A.84D5A26B@ndh.net> <3C96569F.8E76FA6E@metaslash.com> <3C966323.A522D680@ndh.net> <3C967A13.C6074484@metaslash.com> Message-ID: Neal Norwitz wrote in news:3C967A13.C6074484 at metaslash.com: >> So to rephrase the problem a bit: I would like to generate simple >> getters and setters with rather little decision overhead during the >> actual accesses. > >:-) Well in that case: > > class GetterTest1: > def __init__(self): > self._dict = {'key1': 'one', > 'key2': 'two', > 'key3': 'three'} > > def _make_getters(self, dict_name, key_list): > for key in key_list: > code = "def %(key)s(): return %(dict_name)s['%(key)s']\n" > % vars() exec code in self.__dict__, self.__dict__ > > You still don't need to even consider using exec for this: >>> class GetterTest2: def __init__(self): self._dict = {'key1': 'one', 'key2': 'two', 'key3': 'three'} def _make_getter(self, dict, key): def getter(): return dict[key] self.__dict__[key] = getter def _make_getters(self, dict, keys): for key in keys: self._make_getter(dict, key) >>> g = GetterTest2() >>> g._make_getters(g._dict, ['key1', 'key2']) >>> g.key1 >>> g.key1() 'one' >>> g.key2() 'two' >>> This is for 2.2, with 2.1 you need to enable nested scopes. -- 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 I.j.w.Wever at student.tnw.tudelft.nonsense.nonsense.nl Fri Mar 29 05:20:33 2002 From: I.j.w.Wever at student.tnw.tudelft.nonsense.nonsense.nl (Fused) Date: Fri, 29 Mar 2002 10:20:33 GMT Subject: Anyone need a program written? Message-ID: <3ca43ef4.3666136@news.tudelft.nl> I'm currently trying to master Python, but to succeed I need to exercise. However, I detest building programs that have already been built a kazillion times and aren't of use to anyone. Can anyone think of a program that I could build that would actually have use to someone (you?)? I'm trained in Delphi, know some Java and rudimentary C, so the programs don't need to be newbie-easy ( I like a challenge: the greater the challenge, the faster I'll learn ;-) ). From dswegen at software.plasmon.com Tue Mar 19 04:32:36 2002 From: dswegen at software.plasmon.com (Dave Swegen) Date: Tue, 19 Mar 2002 09:32:36 +0000 Subject: #define equivalents and config files Message-ID: <20020319093236.GB19059@software.plasmon> Is there a pythonic way of doing something similiar to Cs #define? I'd like to have what essentially is a header files with easily modifiable values (these will then be used to give default attribute values to various classes). Or are globals the only way to go? Cheers Dave From md_lazreg at yahoo.com Fri Mar 22 16:18:55 2002 From: md_lazreg at yahoo.com (mohamed lazreg) Date: Fri, 22 Mar 2002 13:18:55 -0800 (PST) Subject: Packaging tool Message-ID: <20020322211855.68996.qmail@web10504.mail.yahoo.com> Dear Pythoneers, I have been encouraged by the responses I got about my bug tracking system question... So now I am looking for a free packaging tool writeen in python (it has to be in python)... By a packaging tool I mean a tool that goes into a development area of a software, takes the correct files and binaries depending on some user parameters (configuration files) then creates a package ready to distribute... Thank you again for all your help... Mohamed __________________________________________________ Do You Yahoo!? Yahoo! Movies - coverage of the 74th Academy Awards? http://movies.yahoo.com/ From abou at cam.org Sat Mar 30 14:27:03 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Sat, 30 Mar 2002 14:27:03 -0500 Subject: getting infos from a website Message-ID: <3CA61187.C0548FD5@cam.org> Geoff Gerrietts wrote: > > Check out urllib for retrieving the page: > http://www.python.org/doc/2.2p1/lib/module-urllib.html > > Check out string and re for parsing the page to grab the stuff you > want: > http://www.python.org/doc/2.2p1/lib/module-string.html > http://www.python.org/doc/2.2p1/lib/module-re.html > > If that's not enough to get you productive, let me know where you're > having specific stopping points. > > --G. Ok, I can now get the html source of the page I want. It stores it in a file: #! c:/python/python.exe import urllib import re c = open('c:/python/tester', 'w') f = urllib.urlopen("http://www.coremud.org/cgi-bin/mycore.pl?stocks=1&font=Arial") k = urllib.urlretrieve("http://www.coremud.org/cgi-bin/mycore.pl?stocks=1&font=Arial", 'tester') c.close() # But then I'm trying to read the file and it never outputs what I ask: raw_input('press Return->') c = open('c:/python/tester', 'r') c.read() # readline(), read(), etc. don't seem to work because it doesn't output the 'tester' file. In this example I close then reopen the file, but even if I do not close it first, it doesn't output. Could it have something to do with file permission? (even if I'm on windoze - the 'tester' file in an 'archive' file). Anyone knows what I am doing wrong? -- Zutroi Zatatakowski Commando PACU http://pacu.cjb.net From magnus at thinkware.se Wed Mar 20 07:21:46 2002 From: magnus at thinkware.se (Magnus =?ISO-8859-1?Q?Lyck=E5?=) Date: Wed, 20 Mar 2002 13:21:46 +0100 Subject: Can't print national characters in IDLE with Python 2.2.1c1 References: <3C97E9DF.3070300@thinkware.se> Message-ID: <3C987EDA.2010309@thinkware.se> Thank's for clearing this up Martin (and Oleg who mailed). And thanks for all the work you do to actually make these things work. I've followed the discussions, and realize the problems, but I didn't expect the Span^W silent conversion via unicode that Tcl/Tk performs. Maybe German or Japanese Python books are better at explaining localization and problems with not using US ASCII, but all the Python books in English I read just ignores this subject. Just as they ignore site.py etc. Martin v. Loewis wrote: > It's a known limitation, also it is not clear what the solution should > be. Well, actually it was very simple. Just enable the locale in site.py. (Thank's Oleg.) if 1: # <--- Changed 'if 0:' to 'if 1:'. I just had to change one bit! # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] I assume that in the longer perspective, unicode is the only way to go for proper i18n, at least if your programs will run on platforms that you don't have control over... (Assuming all users will have full character sets!) > If you type "funny characters" in IDLE, Tk will represent them as > Unicode strings (in fact, it represents *all* strings as Unicode > strings). Aha! But is this new? I thought python 2.1 used the same Tcl/Tk version (8.3). What puzzled me was that this always worked before. (As long as used IDLE at least--six years?) I knew that I'd get this behaviour if I'd type u"???". But I just made a plain string. Or so I thought... > Notice that, strictly speaking, your program is incorrect: ... > # ... 8-bit characters may be used in string literals and > # comments but their interpretation is platform dependent; Raising an exception is not what I expect when I read "interpretation is platform dependent". I only assume it would mean that I can't assume that ord(x) would have a particular value for x = '?' > # ... the proper > # way to insert 8-bit characters in string literals is by using octal > # or hexadecimal escape sequences. That doesn't help one tiny bit. I still don't know what print "\0xd5" will look like if I don't know the locale settings. Besides, the error in IDLE is the same due to this silent unicode-string translation. So making "correct" programs in IDLE causes just the same problem. > There is no easy solution to this. Just consider the fragment > > >>> s = '???' > >>> print ord(s[0]) > > What do you want to be printed here (what number)? Assuming you have > some answer (say, 229), then what would you expect if s contained some > Cyrillic or Japanese characters? One solution is to use the locale. I assumed that using setlocale would do the trick, but obviously that must be set up in site.py and cemented with os.setdefaultencoding. Indicating encoding in the file as is being discussed seems reasonable to me. > Under PEP 263, some of the current restrictions will be removed, so > that you can put those characters into Unicode literals. Putting them > into string literals still won't be supported. But... It's always been supported!!! Until now. I hope you don't imply that it will stop working, even if you set default encoding? So, when will Python be all Unicode, and the 7-bit legacy put on the same scrap pile as all 7-bit hardware? (It's really silly to claim that software changes faster than hardware. :) My son is both Lithuanian and Swedish. There is no 8-bit character set for him! He needs transparent Unicode support!!! :) But he's only three, so there is still some time before he starts programming. (At least a year.... ;-) P.S. It's not only IDLE that has shortcomings with non ASCII characters. PythonWin behaves very strange as well. In some columns (!) it won't display certain characters correct (the program will work, but what you see on the screen will change if you change the indentation), and when you press backspace after typing a non-ascii character, you will probably get a yen symbol etc where you had your "bad" letter (I even got a corrupted source code file due to this, and the bad byte wasn't visible in PythonWin at all!). I guess vim and emacs are the only reliable code editors... :-( From pachy at 012.net.il Sat Mar 2 05:44:10 2002 From: pachy at 012.net.il (Tal Linzen) Date: Sat, 2 Mar 2002 12:44:10 +0200 Subject: Fw: smtplib: including a subject Message-ID: <002901c1c1d7$306af590$e00dc7d4@ussr6gwe8yu2pu> Hi. I couldn't figure out how to send a mail with a subject. Help? (By the way, I think the docs on this module could use some rewriting -- it appears to be directed to those familiar with the c library it wraps, rather than to the common Python user). Thanks, Tal From mhammond at skippinet.com.au Wed Mar 13 08:33:52 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 13 Mar 2002 13:33:52 GMT Subject: Python / Active Scripting - Value Assignment - HELP References: Message-ID: <3C8F5564.7020502@skippinet.com.au> adeptus wrote: > OK... > > Within a script block of a HTML file, I can do the following: > > something = ax.document.bgColor > ax.document.write("Background color is %s:" %something) What does: ax.document.write("Background color is %r:" %something) show? (%r == repr(ob)) > > However, unlike all the Javascript and VB examples I see, I can't do > the > following: > > ax.document.bgColor = "#000000" > > I always get an error about unicode strings being read only. Post the exact error. You could try ax.document.bgColor.Value = "#0000" - expecially if the object repr() says "" instead of still being a string. Mark. From mcherm at destiny.com Sun Mar 10 00:31:43 2002 From: mcherm at destiny.com (Michael Chermside) Date: Sun, 10 Mar 2002 00:31:43 -0500 Subject: PEP 284, Integer for-loops (code bash?) Message-ID: <3C8AEFBF.7090102@destiny.com> > 1. Michael! Your Computer thinks its April! You are making > python archives one month ahead of yourself! > (see: http://mail.python.org/pipermail/python-list/2002-April/091714.html) Yipes! Thanks. Someone's idea of an april fools joke on me maybe? Anyway, thanks for point it out. > 2. Haskell, which I mispelt, shame on me, I know better, is a > functional language. I certainly know of the language and didn't even notice the misspelling. > It has functional syntax - don't go there looking > for a 'for loop'. However, it also has list comprehensions, (which is > where we got them from, I think). So, what I meant was 'I wish that > Guido had used Haskell's syntax for arithmetic sequences in Python's > for loops'. That is as follows: I figured you meant something like that. > [1..10] => [1,2,3,4,5,6,7,8,9,10] > [1,3..8] => [1,3,5,7] > [1,3..] => [1,3,5,7,9, ... (infinite sequence) Aha! Abundantly clear. > 3. Make the time to learn Haskell. It is simply too much fun. It's next on my list. Thanks! -- Michael Chermside From robin at jessikat.fsnet.co.uk Fri Mar 8 14:36:26 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 8 Mar 2002 19:36:26 +0000 Subject: Autodiscovery of proxy settings from a python script References: <7EHvmJAipQi8Ew$x@jessikat.demon.co.uk> Message-ID: in fact inside urllib there seems to be some support built in for the registry attack under nt. ie urllib.getproxies() is supposed to return a dictionary mapping services to proxies urls. Doesn't on my machine though. -- Robin Becker From grante at visi.com Mon Mar 11 16:13:05 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Mar 2002 21:13:05 GMT Subject: Setting UNIX environment with a Python script References: <3C8D143A.17963385@all.com> Message-ID: In article <3C8D143A.17963385 at all.com>, Nom de Plume wrote: > The only step left is sourcing the ora_env.[name] file from within > Python in a way such that the environment of the parent shell is > modified. Anyone have any ideas? I have tried: It is not possible under Unix to modify the environment of your parent process. You can only modify your own environment and then export that environment to your children. -- Grant Edwards grante Yow! I'm DESPONDENT... I at hope there's something visi.com DEEP-FRIED under this miniature DOMED STADIUM... From martin at v.loewis.de Wed Mar 20 01:33:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 20 Mar 2002 07:33:05 +0100 Subject: Can't print national characters in IDLE with Python 2.2.1c1 References: <3C97E9DF.3070300@thinkware.se> Message-ID: Magnus Lyck? writes: > Can someone explain this? It's a known limitation, also it is not clear what the solution should be. If you type "funny characters" in IDLE, Tk will represent them as Unicode strings (in fact, it represents *all* strings as Unicode strings). When Tkinter returns strings to Python, it returns plain (byte) strings if the string can be converted using the default encoding (ASCII in most installations), and Unicode objects otherwise. When Python then tries to interpret a Unicode string as source code, it gives up - that text is no valid source code. Notice that, strictly speaking, your program is incorrect: According to http://www.python.org/doc/current/ref/lexical.html # Python uses the 7-bit ASCII character set for program text and # string literals. 8-bit characters may be used in string literals and # comments but their interpretation is platform dependent; the proper # way to insert 8-bit characters in string literals is by using octal # or hexadecimal escape sequences. There is no easy solution to this. Just consider the fragment >>> s = '???' >>> print ord(s[0]) What do you want to be printed here (what number)? Assuming you have some answer (say, 229), then what would you expect if s contained some Cyrillic or Japanese characters? Under PEP 263, some of the current restrictions will be removed, so that you can put those characters into Unicode literals. Putting them into string literals still won't be supported. As a work-around, you can change the system default encoding. Regards, Martin From threehounds at worldnet.att.net Thu Mar 14 09:59:28 2002 From: threehounds at worldnet.att.net (Matthew Austin) Date: Thu, 14 Mar 2002 14:59:28 GMT Subject: basic statistics in python References: Message-ID: I'm new to Python from an R/S background, but it sound like overkill to learn a new language to compute simple descriptive statistics. But if there is interest, check out the RSPython module at www.omegahat.org which allows you to run Python from within R on Windows and UNIX/Linux (and vice-versa on UNIX/Linux systems). "dsavitsk" wrote in message news:PEWj8.10349$k5.3869114 at newssvr28.news.prodigy.com... > it looks like there is a D/COM interface to R, though. Not really a python > solution, but it might work anyway. > > > "Matthew Austin" wrote in message > news:QTUj8.10299$Ex5.957528 at bgtnsc04-news.ops.worldnet.att.net... > > RPy has not been ported to Windows yet. > > > > > > "Emile van Sebille" wrote in message > > news:a6on8n$frj93$1 at ID-11957.news.dfncis.de... > > > "dsavitsk" wrote in message > > > news:OvQj8.10177$k5.3810357 at newssvr28.news.prodigy.com... > > > > hi all, > > > > > > > > never having done numeric calculations in python* i am seeking advice > > > on how > > > > to best go about doing some basic statistics. in particular, i need > > > to find > > > > standard deviations and point bi-serial correlations**, and i am > > > seeking > > > > advice on the best way to go about it. i know how to do them, but i > > > am > > > > wondering if there are prebuilt modules that might simplify the task. > > > > > > You might want to take a look at rpy at > > > http://www.cmat.edu.uy/~walterm/rpy/ > > > > > > -- > > > > > > Emile van Sebille > > > emile at fenx.com > > > > > > --------- > > > > > > > > > From danielk at aracnet.com Fri Mar 1 09:02:04 2002 From: danielk at aracnet.com (Daniel Klein) Date: Fri, 01 Mar 2002 06:02:04 -0800 Subject: Socket connection manager Message-ID: Just wondering if there is a commercial product out there (written in Python of course) that maintains a pool of connections and keeps track of 'state' for web users. Thanks, Daniel Klein From jeff at ccvcorp.com Tue Mar 26 13:59:46 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 26 Mar 2002 10:59:46 -0800 Subject: Difference between eval and exec ?? References: Message-ID: <3CA0C522.90B74851@ccvcorp.com> Thomas Weholt wrote: > Eval and exec seem to have the same effect. What's the real difference? > > In this case : docs != enlightenment. Raymond Hettinger already answered the question you asked, but I'll stick my nose in and add another comment. Yeah, they do both seem to have the same effect -- they both mislead people into thinking that they're a good shortcut, when in reality, 99.99% of the time that you might reach for exec/eval(), there's a cleaner, safer, *better* way of doing things. Both should come with clear warnings, "For Emergency Use Only!!" Jeff Shannon Technician/Programmer Credit International From db3l at fitlinxx.com Thu Mar 28 15:19:27 2002 From: db3l at fitlinxx.com (David Bolen) Date: 28 Mar 2002 15:19:27 -0500 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: philh at comuno.freeserve.co.uk (phil hunt) writes: > IIRC in Awk you can just say: freq[word] ++ and it works > correctly even when there is no pre-existing index of word in freq. > > IMO it's a pity Python isn't like that. I'm not so sure. Doing it that way presumes that in fact you aren't making an error while trying to access an index (word) that doesn't exist. Python requires marginally more effort to cover this case (e.g., you have to explicitly use a method like .get to include a default value if you know the key might not yet be present), but that also means that the code explicitly highlights that the scenario is anticipated and being handled. Sure, in a simple example like an increment operation it seems a bit much, but as a general case, I think it's the smarter and more maintainable default behavior. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From karthik at james.hut.fi Fri Mar 1 03:13:31 2002 From: karthik at james.hut.fi (Karthikesh Raju) Date: 01 Mar 2002 10:13:31 +0200 Subject: Numeric Python Installation woes References: <2dg03lvk1q.fsf@james.hut.fi> Message-ID: <2dbse8vh78.fsf@james.hut.fi> Hi, Thankx. This is exactly what happens with my RH7.1 system. When i try to upgrade 1.5 to 2.2, the system complained and so i left it alone. Now Python 2 which also exists. Dont know how to set this right, and probably because of this numpy does not work even. wishes karthik -- ----------------------------------------------------------------------- Karthikesh Raju, email: karthik at james.hut.fi Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From tim.one at comcast.net Fri Mar 8 15:58:27 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 08 Mar 2002 15:58:27 -0500 Subject: PARTIAL SOLUTION: Compiling Python 2.2 with GCC in HPUX 10.20 does not work In-Reply-To: Message-ID: [Michael Piotrowski] > I've had a look at test_fpformat: The test expects that > > "%.*f" % (0, -0.003) > > produces -0 (negative zero), No, and this is important: this has nothing to do with negative zeroes. What the test expects is a two-character *string*, '-' followed by '0'. > but on HP-UX 10.20, this yields 0. It seems that, according to IEEE, > -0 would be correct, and this is indeed what you get on HP-UX 11. IEEE-754 is irrelevant to this test. It's the C standard that defines the result here, and IEEE rules have nothing to do with it. -0.003 is a non-zero negative number. IEEE esoterica would get involved only if the test had been "%.*f" % (0, -0.0) instead. But the Python test suite stays away from stuff like that, precisely because the C standard doesn't say anything about signed zeroes. > This is basically a, ahem, property of the 10.20 libc; I don't think > there's anything reasonable one could do about it. Also, apart from > the test, I'd think that this has any impact on Python. If you need > the "correct" behavior, the best idea might be to upgrade to 11. > > You might also want to have a look at > > 8ff40090279cd0f9,00.html> > > According to this posting, Solaris 7 and AIX 4.3 seem to behave in the > same way as HP-UX 10.20, so test_fpformat should fail on these > platforms, too. That link is again about IEEE signed zeroes, and test_fpformat doesn't use signed zeroes. From helmut.zeisel at aon.at Fri Mar 8 03:54:42 2002 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: 8 Mar 2002 00:54:42 -0800 Subject: SWIG: operator const char*() const Message-ID: I have a class, say myString, with an operator const char*() const for which I want to create Python shadow classes (swig -c++ -swig -python) class myString { public: const char* operator() const; ... }; Using this code, I get the warning: "Can't wrap operator const char* unless renamed to a valid identifier." So I tried to rename: %rename(c_str) myString::operator const char*() const; gives the error message "Syntax error in input" What is the correct syntax to rename? Helmut From James_Althoff at i2.com Tue Mar 5 20:09:41 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Tue, 5 Mar 2002 17:09:41 -0800 Subject: Status of PEP's? Message-ID: [Jim] > Interesting observation. But actually, we very much chose those forms to > "underline" not to "hide" the fact that numbers are first-class objects in > Smalltalk (as they are also in Python). [Samuele Pedroni] > Yup that's the current Smalltalk cult . Well, it was the *original* one, too. > But it is not the impression I had reading the Alan Key's > paper about the history of Smalltalk. You might want to go back and read it again. Alan (it's Alan Kay) is the one that converted me and everyone else in his group to *his* original "everything is an object" view. From the "Blue Book", Smalltalk-80 The Language and its Implementation", Goldberg and Robson, 1983 ISBN 0-201-11371-6 ABCDEFGHIJ-HA-89876543: "The Smalltalk-80 system is based on ideas gleaned from the Simula language and from the visions of Alan Kay, who first encouraged us to try to create a uniformly object-oriented system". The vision wasn't based on some notion of doing "all objects" just to be different. It came from a deep intuition that this would be a more natural and robust way to model things when programming. (Alan has interesting thoughts about viewing large programming systems like biological systems). And as a way to make computer programming easier. For everyone (so to speak). > There were all the aspects together: everything as an object > as hard-core CS abstraction (like eval and lists and function > invokation in lisp), as a natural mapping from the real word > in the computer world, and the english-like aspect. > > My question is about newbies (kids in Alan Key's case), > as I said I cannot answer myself, and it seems > you can't either . I *can* give you personal experience, however. Whether it was kids brought in from local high schools to play with early versions of Smalltalk, C.S. students from Stanford working as summer interns, or programmers in other parts of Xerox PARC who were not in the Smalltalk development group, it was the same thing: no one teaching the language to anyone new shied away from highlighting "everything is an object" (including numbers) right from the beginning -- quite the opposite, in fact. (Check out the "Blue Book" mentioned above, Part One, Chapter 1: "Objects and Messages"). And everyone in the group certainly *believed* that newbies found such an approach to be very friendly. Alan still likes to show videos of highschoolers using Smalltalk to do advanced things like programming helicopter flight simulations to prove this point -- which is pretty impressive when you realize this was happening 25 years ago. Jim From missive at frontiernet.net Sat Mar 2 17:53:58 2002 From: missive at frontiernet.net (Lee Harr) Date: Sat, 02 Mar 2002 22:53:58 -0000 Subject: newbie password question References: <20020302003514.13693.00001116@mb-fw.aol.com> Message-ID: On 02 Mar 2002 05:35:14 GMT, EtrOFsouls wrote: > Im a newbie to programming, and am having trouble with a certain task. I'd like > to know how to keep track of how often a person guesses at a password and > limits it to x many guesses. Here's a sample of what I've got so far. > > password = "foobar" > > while password != "unicorn": > password = raw_input ("Password:") > print "Welcome In" > > I understand all this (thank god), but I'm having trouble figuring out how to > get it to keep track of the number of guesses and then print a message such as > "Halt, you do not have access!" if the number of guesses exceeds the limit. I'm > learning this thru on-line tutorials and this was given as an excersise. All I > have to work with is variables and statements such as...while, if, elif and > else. > You also might want to look at the getpass module. (lets you get the password without echoing input) From peter at engcorp.com Mon Mar 11 23:32:05 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 11 Mar 2002 23:32:05 -0500 Subject: round() function strange behaviour References: Message-ID: <3C8D84C5.AB3F36BA@engcorp.com> Tim Peters wrote: > > The VB Currency type is a 64-bit signed integer under the covers, implicitly > scaled by 10,000. That's similar to a FixedPoint(4) if you use my > FixedPoint.py class, although a FixedPoint(4) has no restriction on the > magnitude, while a VB Currency value is restricted to the range > > -922,337,203,685,477.5808 <= Currency <= 922,337,203,685,477.5807 Which, coincidentally or not, is exactly the value you get if you project the annual increase in Bill Gates net worth until the point at which he says he will retire, in US dollars for that same year. Remarkable, really, but I guess he's not the senior architect at Microsoft for nothing. -Peter From mhammond at skippinet.com.au Mon Mar 18 17:20:47 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Mon, 18 Mar 2002 22:20:47 GMT Subject: Windows Scripting Component weirdness References: Message-ID: <3C96684A.8040003@skippinet.com.au> Keith Farmer wrote: > I modified \Python\Lib\site-packages\win32com\test\testPys.sct into > WSCTest.wsc, source below. Running the testPyScriptlet.js code (also below) > seems to reveal that I am unable to set properties on the instantiated > object. No errors are brought up -- the code just behaves as if I never > assigned new values to the properties. > > What am I doing wrong, assuming that the WSH is behaving properly? A simple mistake of mine! > def put_PyProp1(newValue): > PyProp1 = newValue ... > def put_PyProp2(newValue): > PyProp2 = newValue PyProp1 and PyProp2 should be declared global! Mark. From donn at u.washington.edu Fri Mar 8 12:28:59 2002 From: donn at u.washington.edu (Donn Cave) Date: 8 Mar 2002 17:28:59 GMT Subject: why is python slow? References: Message-ID: Quoth Fernando Pereira : | On 3/7/02 9:41 PM, in article | a2972632.0203071841.7cd09181 at posting.google.com, "les ander" | wrote: |> i am just curious as to why different programming languages have different |> speed. I understand that if a language has an extensive grammar |> (such as c++) the compiler would take longer. But what about execution? | You will not get a good answer to this from a newsgroup. No one can | summarize for you what takes years of education and experience in | programming language and implementation to learn. The only way to become | informed on these questions is to study programming languages seriously. That's true in general, but I wonder if all of Python's performance problems are really so deep. A few weeks ago someone posted some performance measurements and, among other things, noted that version 2.2 took twice as long just to start up. Did that appalling statistic attract any investigation into the cause, or did anyone even try that simple experiment themselves? Is it true? Is it news to the people who released 2.2? Is there any attention to performance there at all? I believe I recall something similar in 2.0, due to a mistake in site.py that was discovered during the beta releases. Not a hard problem, just one that wouldn't be noticed until someone wondered why performance went downhill so fast. We can wave our hands and say performance is a tough problem, but it would be more convincing if it looked like it was getting the most minimal attention. Donn Cave, donn at u.washington.edu From skip at pobox.com Mon Mar 11 08:40:56 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 11 Mar 2002 07:40:56 -0600 Subject: Internships and summer jobs In-Reply-To: References: Message-ID: <15500.46056.218779.908535@12-248-41-177.client.attbi.com> Brett> Is there any place out there to find a list of Python-related Brett> internships or summer jobs? How about entry-level Python jobs? Nothing specific to those categories, but I would check the Python Job board: http://www.python.org/Jobs.html Besides the job listings it contains, it has links to several other sites. Also, the Python and Zope Directory and Job Market might be worth checking out: http://www.pythonandzope.com/ though it seems to be having some problems. Report any you encounter to lozinski at openstepnews.com. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) "As often happens in Net communities, people find all kinds of energy to compose incisive criticisms of the threads and postings of other members, when they could be directing that energy towards brilliant new threads and postings of their own." - Tom Neff From geoff at gerrietts.net Wed Mar 6 23:07:23 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Wed, 6 Mar 2002 20:07:23 -0800 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <20020307035851.GA23955@isis.gerrietts.net> References: <3C7D8DCA.119D52EC@earthlink.net> <3C850173.4050004@bioeng.ucsd.edu> <3C8623B9.3000504@sympatico.ca> <20020307035851.GA23955@isis.gerrietts.net> Message-ID: <20020307040723.GB23955@isis.gerrietts.net> Quoting Geoff Gerrietts (geoff at gerrietts.net): > What is it about internet discussion forums that makes everyone > struggle to find grounds to argue rather than make an effort to > understand? I was probably being unfair here. Read here frustration at feeling like the point's been missed for the lint-picking. > Again, this is begging the question, and after two pointless arguments > niggling over the semantics of "smarter", I'm starting to get a little > annoyed. I can define smarter as "having a higher IQ", as "best > educated", or as "most able to solve a given problem" and all of them > work pretty well. Right now I'm talking about ability to ingest raw > information and retain it. It's clear I should have been a little more > explicit; I guess terms like "smarter" are just begging for people to > fight. And here at least I admit it's my fault, if a little late in the issue. I've tried to recast this discussion away from the specifics of my first article and toward the issues, lest they get lost. I just want to apologize in advance for letting my frustrations show, lest I give insult where none was intended or deserved. I'd rather the thread be intellectually provacative than provocational, if we can manage it; pedagogy is of interest to me. Thanks, --G. -- Geoff Gerrietts "Ordinarily he was insane, but he had lucid moments when he was merely stupid." --Heinrich Heine From jason at jorendorff.com Sat Mar 2 02:11:50 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sat, 2 Mar 2002 01:11:50 -0600 Subject: SAX-Parser entity In-Reply-To: Message-ID: fabi kreutz wrote: > where Character 19 in Row 29 is the occurence of an ?. Yep, if you are going to use non-ascii characters you have to specify the encoding in the XML document itself, so the XML parser knows what's going on. > After browsing the FAQs I changed the default encoding in site.py to > iso-8859-1, which had some nice effect, but not on minidom. What you need is: It must be the very first thing in the XML document; i.e. the two characters ") ## Jason Orendorff http://www.jorendorff.com/ From rvoutour at uoguelph.ca Sun Mar 3 23:09:15 2002 From: rvoutour at uoguelph.ca (Russell Voutour) Date: 4 Mar 2002 04:09:15 GMT Subject: Snack mod for python Message-ID: Hi i'm using the Snack sound module for python and i've run into a problem and was wondering if anyone had ever used it before. It installed find but when i use the .play() method it tries to open my /dev/dsp and it gets a error because the device does not exists it's under dev/sound/dsp. i've looked in the tkConfig file and the tclConfig file and can't find anything any sugestions would be helpfull thanks Russ -- From mcfletch at geocities.com Sun Mar 10 01:53:15 2002 From: mcfletch at geocities.com (Mike C. Fletcher) Date: Sun, 10 Mar 2002 01:53:15 -0500 Subject: Standalone Win32 wxPython apps? References: Message-ID: <3C8B02DB.2030805@geocities.com> I've done this for a commercial shop at which I used to work (5 or 6 projects). Using py2exe was the most satisfactory approach I found. I'd used the Installer before that, both worked, but py2exe seemed more understandable to me. I needed to hack around some things (such as PIL's plugins), but basically py2exe caught most dependencies and created a running app. I passed the output of py2exe onto our installer dude and he wrapped it with standard installers (installshield if I recall correctly). Users seemed happy with the results. I eventually made some modifications so that the output directory was the Python path for the application so that I could install plugins/new python code without needing to re-install the DLLs. Enjoy, Mike Grant Edwards wrote: > I'm considering writing a wxWindows app for Win32. The only > way I'm willing to do this is by doing all of the development > under Unix, and then grit my teeth while I package up the final > product for Win32. > ... > In order for it to be useful, I'll need to be able to > distribute it as a stand-alone app to users who don't have (or > care to have) a regular Python or wxWindows distro installed. > > Optimally, it would be a single "exe" file that doesn't require > any installation procedure. If that's not possible, it would > be permissible to use a typical "isntall-wizard" type > installation: running the exe installs the required files > somewhere, adds a start-menu entry, leaves an un-installer > around. > > It looks like Gordon McMillan's installer might fit the bill. > > Anybody care to share any experiences distributing wxWindows > apps for Win32? _______________________________________ Mike C. Fletcher http://members.rogers.com/mcfletch/ From hades at silentone.com Sun Mar 17 16:05:45 2002 From: hades at silentone.com (Culley Angus) Date: Sun, 17 Mar 2002 21:05:45 GMT Subject: pyclbr _modules cache - why? Message-ID: <3c9501d5.588674328@news.wlg.ihug.co.nz> Does anyone know the reasoning behind forcing use of the cache in the pyclbr module. I am implementing a simple ide where changes to modules are being updated in the gui... Alas I have had to hack the pyclbr module to stop it using cached data. Surely if someone is implementing a classbrowser, it is a fair assumption that they may be updating the classes being browsed. From nospam at bigfoot.com Fri Mar 22 19:33:25 2002 From: nospam at bigfoot.com (Gillou) Date: Sat, 23 Mar 2002 01:33:25 +0100 Subject: Packaging tool References: Message-ID: "make" seems to be what you're looking for. It's not in python, but it does the job. "mohamed lazreg" a ?crit dans le message news: mailman.1016831987.19520.python-list at python.org... > Dear Pythoneers, > > I have been encouraged by the responses I got about my > bug tracking system question... So now I am looking > for a free packaging tool writeen in python (it has to > be in python)... By a packaging tool I mean a tool > that goes into a development area of a software, takes > the correct files and binaries depending on some user > parameters (configuration files) then creates a > package ready to distribute... > > Thank you again for all your help... > > Mohamed > > __________________________________________________ > Do You Yahoo!? > Yahoo! Movies - coverage of the 74th Academy Awards? > http://movies.yahoo.com/ > From tim.one at comcast.net Sat Mar 16 02:34:59 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 16 Mar 2002 02:34:59 -0500 Subject: Windows Installation In-Reply-To: Message-ID: [Jonathan Gardner] > ... > My question is twofold: > 1) Where do I go to find a neat free software (READ: No problems > with GPL) windows installer (that works on all windows platforms)? Give Inno Setup a try: http://www.jrsoftware.org/isinfo.php It's free and doesn't require a GUI. You can a write a plain text file to drive it. > I could work through this on the Linux box and then have the guys on > windows try stuff out realtime for me. Better: shame your Windows users into writing the installer. If they can't figure out how to use Inno Setup, they're not users worth having anyway . Alternative: Ship your app in a zip file and skip the start menu (etc) business. Windows users should be able to create their own shortcuts -- the OS has extensive drag-'n-drop facilities for doing so. but-they'll-whine-even-if-you-do-it-for-them-ly y'rs - tim From kragen at pobox.com Wed Mar 20 18:37:37 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 20 Mar 2002 18:37:37 -0500 Subject: classes for fun and newbies References: Message-ID: <83y9gmdd4u.fsf@panacea.canonical.org> "Bruce Dykes" writes: > class call_record: > def __init__(self, record=''): > self.record_id=record[0:5] > self.date=record[6:11] I'd use: import struct self.record_id, self.date = struct.unpack("5s x 5s", record) This has the following advantages: - it makes it clear that you're skipping a byte between record_id and date (after you read struct.__doc__ to find out what x means) - it doesn't require math to figure out the length of each field - it gives you an error instead of silently wrong results if the format string is wrong (although the error is not very helpful) - it's a lot shorter It has the disadvantage that errors are harder to diagnose --- you have to use struct.calcsize to figure out whether your string is too long or too short, then change the string or the format to get it to work, then look at the results. From mwh at python.net Fri Mar 8 05:19:43 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 8 Mar 2002 10:19:43 GMT Subject: The language vs. the environment References: <23891c90.0203071057.57204175@posting.google.com> Message-ID: paul at boddie.net (Paul Boddie) writes: > Skip Montanaro wrote in message news:... > > * find a Python bug without a proposed fix and write one (there are > > currently between 250 and 300 open bug reports): > > http://sourceforge.net/tracker/?group_id=5470&atid=105470 > > Although one might think that this requires a "Python internals skill > level" of at least 7 out of 10, This isn't true. You need to know how to use "cvs" and "diff", and *some* bugs require a "Python internals skill level" of at least 11 out of 10, but most don't and many probably don't require more that 3 or 4 out of ten. Besides, what better way of acquiring the skill to fix deep bugs than to practice fixing shallow ones? CHeers, M. -- There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies. -- C. A. R. Hoare From jh at web.de Mon Mar 11 18:58:49 2002 From: jh at web.de (Jürgen Hermann) Date: Tue, 12 Mar 2002 00:58:49 +0100 Subject: [ANN] MoinMoin 0.11 Message-ID: A WikiWikiWeb is a collaborative hypertext environment, with an emphasis on easy access to and modification of information. MoinMoin is a Python WikiClone that allows you to easily set up your own wiki, only requiring a Web server and a Python installation (1.5.2, 1.6 or 2.0). Most important new features: file attachments, definition list markup (glossaries), change notification via email, variable substitution when saving pages, edit preview, and improved documentation. Note that the RSS features require a recent PyXML (CVS or 0.7) due to bugs in the namespace handling of xml.sax.saxutils in earlier versions. This is (hopefully) automatically detected on every installation. Statistical features are NOT designed to work with Python 1.5.2 and require Python 2.0 or higher. Overall, MoinMoin 0.11 is not explicitely tested for 1.5.2 compatibility. Homepage: http://moin.sf.net/ Download: http://sf.net/project/showfiles.php?group_id=8482&release_id=70345 http://prdownloads.sourceforge.net/moin/ Mailing lists: http://lists.sf.net/lists/listinfo/moin-user http://lists.sf.net/lists/listinfo/moin-devel New features: * XML formatting now (most often) produces well-formed, and, depending on proper layout of the wiki page, valid StyleBook XML * Headers are now automatically numbered, unless you set the config item 'show_section_numbers' to 0 * "#pragma section-numbers off" (or "0") switches that off explicitely, and "on" or "1" enables numbering * Added a "contributions" directory for 3rd party extensions * AttachFile action, contributed by Ken Sugino; note that you have to enable this action because of the possibility of DoS attacks (malicious uploads), by adding this to your moin_config: allowed_actions = ['AttachFile'] * "attachment:" URL scheme allows access to attachments, to get files from other pages use "attachment:WikiName/filename.ext". * New macros: Date(unixtimestamp) and DateTime(unixtimestamp) to display a timestamp according to system/user settings * Variable substitution when a page is saved, note that saving template pages does NOT expand variables. Supported are: @DATE@ Current date in the system's format @TIME@ Current date and time in the user's format @USERNAME@ Just the user's name (or his domain/IP) @USER@ Signature "-- loginname" @SIG@ Dated Signature "-- loginname date time" @MAILTO@ A fancy mailto: link with the user's data * Copied some new emoticons from PikiePikie || {{{ :-? }}} || :-? || tongue.gif || || {{{ :\ }}} || :\ || ohwell.gif || || {{{ >:> }}} || >:> || devil.gif || || {{{ %) }}} || %) || eyes.gif || || {{{ @) }}} || @) || eek.gif || || {{{ |) }}} || |) || tired.gif || || {{{ ;)) }}} || ;)) || lol.gif || * AbandonedPages macro * Added definition list markup: {{{term:: definition}}} * Added email notification features contributed by Daniel Sa? * SystemInfo: show "Entries in edit log" * Added "RSS" icon to RecentChanges macro and code to generate a RecentChanges RSS channel, see http://www.usemod.com/cgi-bin/mb.pl?UnifiedRecentChanges for details * Added config.sitename and config.interwikiname parameter * Better WikiFarm support: * /plugin/macro and /plugin/action can be used to store macros and actions local to a specific wiki instance * config.shared_intermap can contain a pathname to a shared "intermap.txt" file (i.e. one stored outside the datadir) * added `backtick` shortcut for {{{inline literal}}} (has to be enabled by "backtick_meta=1" in the config file); note that `` is then a shorter replacement for '''''' escaping * added inline search fields (at the bottom of each page) * Added preview to the editor, including spell checking * New languages: Chinese (Changzhe Han) and Portuguese (Jorge Godoy), updated French (Lucas Bruand), added Korean (Hye-Shik Chang) and Italian (Lele Gaifax) * New SystemAdmin macro * `[[Anchor(anchorname)]]` macro to insert anchors into a page, and [#anchorname Anchor Links]. * User option to open editor view via a double-click * Added commentary field to editor, recent changes and page info * Page trails (user option) * UserPreferences: checkboxes for double-click edit, page trail, fancy links, emoticons, jump to last page visited, and some other yes/no options * "config.nonexist_qm" is now the default for a user setting * `[[GetText(text)]]` macro loads I18N texts (mainly intended for use on Help pages) * table attributes via "|| ... ||", more details on http://purl.net/wiki/moin/HelpOnTables * PythonFaq interwiki tag and support for $PAGE placeholder * event logging, as the basis for future statistics * "moin-dump" command line tool to create a static copy of the wiki content * "config.external_diff" allows to set an exact path to the command, or change the name to for example "gdiff" if GNU diff is not a native command in your UNIX flavour * `[[PageSize]]` macro * the interwiki name "Self" now always points to the own wiki * config.title1 and config.title2 are inserted into the output right before and after the system title html code (title1 is right after the tag and normally undefined, title2 defaults to the "
    " above the page contents) * Additional link on diff pages to ignore whitespace changes * Subpages (config.allow_subpages, config.page_icons_up) * ^superscript^ markup * `[[FootNote]]` macro * many other new config options, see HelpOnConfiguration for a complete list * [[StatsChart(type)]] shows statistical charts (currently defined types: hitcounts, pagesize, useragents) * 'inline:' scheme works like 'attachment:', but tries to inline the content of the attachment into the page; currently knows about "*.py" sources and colorizes them * support for Java applet "TWikiDrawPlugin" via drawing: URL scheme (you need to activate the AttachFile action if you want drawings) * numeric entities (&#nnnnn;) are now optionally NOT escaped, which allows you to insert more characters into a Latin-1 page, especially the Euro symbol * navi_bar is now a list of page names which should be linked on every page * test.cgi is now rolled into moin.cgi, and can be called by adding "?test" to the wiki base URL. Also, as a security feature, the server's environment is only shown for requests local to the web server. Unfinished features: * user defined forms * XML export of all data in the wiki Documentation: * extended the online help ("Help*" pages) * German help pages (thanks to Thomas Waldmann) Bugfixes: * #425857: python Parser bug on the second call * #424917: Caching control * #465499: Two HTTPS problems * #491155: FrontPage hardcoded * Handling of inbound UTF-8 encoded URIs (only with Python >= 2.0) * Fix for subtle changes in "re" of Python 2.2 * User-provided URLs are now never URL-escaped, which allows appending #anchors and using %20 for spaces in InterWiki links From philh at comuno.freeserve.co.uk Sat Mar 9 08:09:39 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 9 Mar 2002 13:09:39 +0000 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: On 9 Mar 2002 05:38:20 GMT, Quinn Dunkan wrote: >On Mon, 4 Mar 2002 12:26:48 -0800, James_Althoff at i2.com >wrote: >>Carel, >> >>Thanks for the explanation, below. Very interesting. >> >>Yes, I agree with your basic analysis that producing an iterator for an >>integer makes a lot more sense if one accepts integers as first-class >>objects. The fact that Python treats integers as well as everything else >>as first-class objects is one of the big reasons why I like Python so much. > >I have no trouble accepting integers as objects just like any other type, and I >still don't like iter(5). Nor do I, since it bdoes the same thing as range(5) and/or xrange(5). One possibility might be a new looping construct, do: do 5: print "this will be printed 5 times" Note that you can't get hold of a do loop's loop variable. This would be easy to optimise, I imagine. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From rich at worldsinfinite.com Thu Mar 7 10:30:51 2002 From: rich at worldsinfinite.com (Rich Harkins) Date: Thu, 7 Mar 2002 10:30:51 -0500 Subject: CP4E/D&D/Twins (WAY Off-Topic) In-Reply-To: <19650FF08A99D511B19E00B0D0F06323060B49@SRM201002> References: <19650FF08A99D511B19E00B0D0F06323060B49@SRM201002> Message-ID: <200203071530.g27FUpk02021@localhost.localdomain> On Thursday 07 March 2002 10:19 am, Gustavo Cordova wrote: > [ snip ] > > But, what about identical twins, who speak their own language > well before they start speaking their parents? Aren't they > communicating with their peer(s)? > > [ snip ] > > Sometimes I wonder if I'd have twice the fun if I was two, > er, had a twin. :-) Or maybe I'd be twice as silly and make > half as much sense. > > [ snip ] My wife is a twin. Apparently she and her twin sister had their own little language for a while, although neither of them remember exactly what it entailed and noone in the family bothered to record their twin-speak. This persisted into their early childhood (about 5) from what I'm told. Oh, and they do seem to have twice as much fun when they're together BTW... Rich From chris.gonnerman at newcenturycomputers.net Fri Mar 15 20:38:33 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 15 Mar 2002 19:38:33 -0600 Subject: Help Required References: Message-ID: <007901c1cc8b$4b8655e0$0101010a@local> If you want help, you must include your source. ----- Original Message ----- From: "Surajsub" > Hi, > I am a newbie to Python and am pretty fascinated by it power and > speed.I am however puzzled in trying to write this script. > The script builds a list of userids to be fed to ldap and it is > supposed to be > > uid1,uid2,uid3....and so on.( Notice there is no space) > > However when i am trying to create the uid list it gives > > uid1, uid2, uid3,...and so on. > how do i get rid of this leading space if u would call it.. > string.lstrip does not work either. > > what am i doing wrong? > TIA > Suraj From ngps at madcap.netmemetic.com Tue Mar 5 11:00:41 2002 From: ngps at madcap.netmemetic.com (Ng Pheng Siong) Date: 5 Mar 2002 16:00:41 GMT Subject: SSL Server Sockets? References: Message-ID: According to Jim Dennis : > ... so I guess and it's still too closely coupled to the > swig version so 1.3.10u is too new and 1.1 is (understandably) > too old. > > Ng, are you planning on updating this to Python2.2 using the > latest swig? Could we find an (international) volunteer to > maintain a Debian package? I can't keep up with SWIG, so I'm doing this: bundle the output of SWIG and a setup.py that uses the bundled files. Tested ok on FreeBSD and Win98 with Python 2.2. The snapshot should appear on my website tomorrow. Cheers. -- Ng Pheng Siong * http://www.netmemetic.com From miracle at paradise.net.nz Tue Mar 26 15:28:38 2002 From: miracle at paradise.net.nz (Matthew Sherborne) Date: Wed, 27 Mar 2002 08:28:38 +1200 Subject: How to get a key from dictionary? References: <3C9FAFCC.20062.91741D@localhost> <009501c1d458$0a5a86c0$3425fea9@0016314730> Message-ID: <002d01c1d504$d0749010$08020196@Jonah> Sorry to be a show off, but I reckon that this way may be faster. Sorry again. The other replies are very helpful. :) def findKey(val): for key, value in dict.items(): if value == val: return key return None GBU Matthew Sherborne ----- Original Message ----- From: "Don Arnold" To: ; ; ; ; Sent: Tuesday, March 26, 2002 11:51 AM Subject: Re: How to get a key from dictionary? > >>> targetval = 2 > >>> dict = {'aa':1, 'bb':2, 'cc': 3, 'dd': 1} > >>> targetval = 2 > >>> for key in dict.keys(): > if dict[key] == targetval: > print "found", targetval, "at key", key > > found 2 at key bb > >>> targetval = 1 > >>> for key in dict.keys(): > if dict[key] == targetval: > print "found", targetval, "at key", key > > found 1 at key aa > found 1 at key dd > > ----- Original Message ----- > From: "A" > To: ; ; > ; > Sent: Monday, March 25, 2002 4:16 PM > Subject: How to get a key from dictionary? > > > > Hi, > > Is there a possibility to get, from a dictionary, a key according to a > > value ? > > For example > > I have a dictionary > > > > dict={'aa':1,'bb':2} > > > > and > > dict['aa'] > > is 1 > > > > But how can I for value 1 find out key? (That is here 'aa') > > > > Thank you for help > > Ladislav > > > > > > _______________________________________________ > > ActivePython mailing list > > ActivePython at listserv.ActiveState.com > > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs > > _______________________________________________ > ActivePython mailing list > ActivePython at listserv.ActiveState.com > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pereira at cis.upenn.edu Fri Mar 8 22:18:07 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Fri, 08 Mar 2002 22:18:07 -0500 Subject: why is python slow? References: <7xvgc6fnus.fsf@ruckus.brouhaha.com> Message-ID: On 3/8/02 9:59 PM, in article 7xvgc6fnus.fsf at ruckus.brouhaha.com, "Paul Rubin" wrote: > Fernando Pereira writes: >> The irreducible fact is that Python needs extensive runtime type checks, >> Java doesn't. One could argue that agressive inlining of built-in operations >> and type checks followed by removal of redundant machine instructions might >> have the effect of removing most type checks, but that needs to be shown. > > 40 years of Lisp compiler implementations have shown pretty conclusively > that these problems are surmountable. It's precisely because I know that history that I raise those points. I don't want to dissect here the lessons of history, but the practical fact is that the heroic optimization efforts of Lisp compilers have not proven to be *economically* viable. That is, the cost of creating, maintaining, and running such compilers has been huge relative to the lines of code that they succeed in optimizing. It's easier to build compilers producing fast code for statically typed languages. That is, the costs are spread over all the programmers who have to obey compile-time type disciplines (and those costs may be lower than one things, as those disciplines catch bugs), rather than being concentrated on the compiler developers. This is not a critique of dynamically-typed languages, but rather an observation from 25 years of implementing and using such languages. -- F From mzou at bu.edu Sun Mar 24 23:45:23 2002 From: mzou at bu.edu (ricky) Date: Sun, 24 Mar 2002 23:45:23 -0500 Subject: question: python and UDP References: <3C9E9CFD.AC6A149B@engcorp.com> <3C9EA4CC.1208750A@engcorp.com> Message-ID: sorry about that last msg i sent, i didn't mean to ask people to do work for me i was out of my mind, i posted the msg without even thinking about it... I found the documentation about struct, and successfully constrcuted a struct... i haven't tested on the proxy server yet if i get into more troubles, i'll post another msg with more details thank you, peter and all "Peter Hansen" wrote in message news:3C9EA4CC.1208750A at engcorp.com... > ricky wrote: > > > > Peter Hansen wrote: > > > ricky wrote: > > > > > > > > I am trying to write a python program to connect to a proxy server which > > > > takes the following header: > > > > however, the proxy server doesn't seem to understand the header i sent > > > > to it. > > > > > > Are you looking for the 'struct' module? That should be enough to > > > produce the header format you need. > > > how would i use the struct module? > > Well, you could start by looking at the documentation on it, and > asking specific questions to clarify any misunderstanding that > remains. If you don't know where to look for the documentation, > feel free to ask. > > If you post some sample code which you've tried, we can probably > explain why the "server doesn't seem to understand the header" > you sent it, and if you try using struct and still have trouble, > post samples of your efforts and we can work on improving those. > > (You haven't given enough info yet for anyone to just write > the code for you, even though there are likely people here > who would be happy to do that. I'm generally not one of them.) > > -Peter From paul at boddie.net Mon Mar 11 10:09:56 2002 From: paul at boddie.net (Paul Boddie) Date: 11 Mar 2002 07:09:56 -0800 Subject: scripting Outlook express with Python References: Message-ID: <23891c90.0203110709.6056b0e1@posting.google.com> sandskyfly at hotmail.com (Sandy Norton) wrote in message news:... > Does anyone have any experience, code, etc...? I guess my first > question should be: is it possible? Ignoring the platform switch recommendations (which are probably meant for your own good, anyway), I would use something like PythonWin to investigate the type libraries and automation objects available to you. Use the "Tools" -> "COM Browser" menu option to take a look at the huge number of COM interfaces that are likely to be around on your desktop. Hopefully, you will find one for Outlook Express - I found "OutlookExpress.MessageList". Then, use the "Tools" -> "COM Makepy utility" menu option to see the available libraries, and see if there's anything relevant. The version of Outlook I have uses the "Microsoft Outlook 9.0 Object Library (9.0)" but you would need to check with the Microsoft documentation to see what Outlook Express provides - their Web site usually has this kind of information on it. Paul From bh at intevation.de Thu Mar 7 06:19:41 2002 From: bh at intevation.de (Bernhard Herzog) Date: 07 Mar 2002 12:19:41 +0100 Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: <6qpu2gzktu.fsf@abnoba.intevation.de> James_Althoff at i2.com writes: > [James Althoff] > > Can you suggest a less contrived example that might be a problem? > [Bernhard Herzog] > > x, = 1 > > > > would assign 0 to x instead of raising an error. > > Agreed. Note that this example has been in the PEP from the beginning. Indeed. It's been a while since I read that pep :) The pep doesn't say anything about the other contexts in which iterators are used (except for the sequence unpacking above). With iterable integers: >>> list(4) [0, 1, 2, 3] >>> tuple(4) (0, 1, 2, 3) >>> max(4) 3 >>> min(4) 0 >>> filter(None, 4) # also for map and reduce [1, 2, 3] >>> L = [] >>> L.extend(3) >>> L [0, 1, 2] >>> zip(3) [(0,), (1,), (2,)] Do we really want all of these new behaviors? Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://mapit.de/ From dsavitsk at e-coli.net Fri Mar 22 03:59:35 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 22 Mar 2002 08:59:35 GMT Subject: CGI, etc. References: Message-ID: "Sheila King" wrote in message news:a7dgl7.3vs45c5.1 at kserver.org... > [posted and mailed] > > On Fri, 22 Mar 2002 04:06:06 -0000, "purplebo1212" > wrote in comp.lang.python in article > : > > > Hi! I'm new to Python and was looking at writing an CGI script that > > would execute a program. Any pointers? > > thanx > > > > > http://www.python.org/topics/web/ > btw, the instructions linked to here for doing CGI on windows under iis are out of date (only covering 9*/NT). For win2k (server and professional) see http://www.e-coli.net/mag.shtml (or http://www.e-coli.net/pyiis.html and http://www.e-coli.net/pyiis_server.html specifically) -d From tim.one at comcast.net Sat Mar 30 17:52:23 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 17:52:23 -0500 Subject: PEP 285: Adding a bool type In-Reply-To: Message-ID: >> 1) Should this PEP be accepted at all. [Pearu Peterson] > It seems that this is already decided as Guido is the author and also > the only one who accepts PEPs. Guido has rejected his own PEPs before. It depends on the quality of arguments raised, both pro and con. > ... > In future (Python 2.>=3, >3), are these constructs valid or must they > be replaced with > > while bool(x): > ... > > ? :( Under the PEP "while x:" continues to work fine. > Ka-Ping Yee has raised related conserns in > > http://mail.python.org/pipermail/python-dev/2002-March/020893.html > > that never got a proper answer from Guido nor others. There are 8 replies to his msg. I don't know what you mean by "proper". Under the PEP, none of the stuff he was worried about breaks, and that was explained. I thought Greg Ewing's reply was more than enough: http://mail.python.org/pipermail/python-dev/2002-March/020921.html From jgardn at alumni.washington.edu Wed Mar 13 19:45:27 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Thu, 14 Mar 2002 09:45:27 +0900 Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: <873cz44ea8.fsf@bunty.ruud.org> Message-ID: Clark C . Evans scribbled with his keyboard: > On Wed, Mar 13, 2002 at 11:34:55AM -0500, ruud de rooij wrote: > | perhaps lists should support .keys() and .items() for those operations > | (analogous to dictionaries). > > Very nice idea. This is PEP worthy. It is nice beacuse it > does not introduce anything new; a list can easily be viewed > as a mapping having a positive integer domain. This is simple, > consistent, and quite elegant. > It certainly provides a feature I would use often. Jonathan From gh_pythonlist at gmx.de Wed Mar 13 13:44:51 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Wed, 13 Mar 2002 19:44:51 +0100 Subject: python and analyze image format? In-Reply-To: <87henkickf.fsf@lumen.indyrad.iupui.edu> References: <87henkickf.fsf@lumen.indyrad.iupui.edu> Message-ID: <20020313184450.GA1227@lilith.hqd-internal> Le 13/03/02 ? 12:48, Michael A. Miller ?crivit: > Anybody know of a python reader/write for analyze image data and > header files? Would you provide a pointer if you do? I'm not quite sure if I understand you correctly, but the imghdr module in the standard Python library can check the file format of an image file. If you're on Unix, the "file" system command can detect a whole lot more. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 14.3 ?C Wind: 1.2 m/s From bokr at oz.net Fri Mar 8 18:29:03 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Mar 2002 23:29:03 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8827E5.C7D5036C@cosc.canterbury.ac.nz> <3C880AC2.6070708@sneakemail.com> Message-ID: On Fri, 08 Mar 2002 04:57:10 GMT, Joshua Macy wrote: >Greg Ewing wrote: > >> I have another idea that doesn't suffer from that >> problem. >> >> def string my_string: >> This is a free-form string constant. Its value consists >> of all the text at this indentation level, verbatim, >> with the indentation stripped off. It can contain >> ', ", ''', """, \ or any other characters. >> >> > > >But then you have to indent everything in the text to that level, which >isn't quite the same as cut-and-paste arbitrary text any more. Granted, >it's not hard to do with a good editor, but neither is escaping a >whatever triple quotes you might find in the text (even Notepad can do >that). > >For that matter, the PEPs to make Python more unforgiving of what's >contained in strings (only valid declared encodings or binary as octal >escape sequences) seem to be advancing rapidly, so schemes for stuffing >more arbitrary and unexamined junk into the source code seem to be >heading in the wrong direction. > This is an interesting aspect. My example of pasting text into a current source really should take into account the encoding of both the text to be pasted and the destination context. I.e., ISTM a conversion to whatever the current internal representation of the destination was should be done (which might raise an exception), followed by conversion for display purposes (which might also raise an exception in the context of a raw string, where unprintable characters can't be used! See my other post for some weirdness re current r'strings'). >I guess I don't really see the motivation for the proposed feature. If >triple quoting isn't sufficient, I'd take that as a sign that the >material should be a separate data file...it's not like Python makes it >hard to read an external file into a string. > No, but they are hard to see when you are reading code that just does i/o, and if you have dozens of snippets, that would be a lot of files. Of course, you could put them in a multipart MIME formatted file with, ahem, delimiters between the pieces ;-) From bokr at oz.net Fri Mar 8 20:36:37 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Mar 2002 01:36:37 GMT Subject: RFC PEP candidate: q''quoted ? References: Message-ID: On Fri, 8 Mar 2002 21:13:48 +0300 (MSK), Roman Suzi wrote: >On 4 Mar 2002, Bengt Richter wrote: > >>On Sun, 3 Mar 2002 14:56:45 +0300 (MSK), Roman Suzi wrote: >> >>>On 3 Mar 2002, Bengt Richter wrote: >>> >>>>Problem: How to put quotes around an arbitrary program text? >>> >>>Have it in a separate file. >>> >>That's fine in a lot of cases, but does require reliable presence >>of both files. It's not so convenient if you are trying to write >>e.g. a program generator and want to write out snippets containing >>mixed triple quoted doc strings and data etc. Or if you are >>writing copied example snips as part of dynamic HTML from CGI. > >>===the stuff I want=== >> >> >>Sure, I can copy it and make a separate file, and write some code to >>read the file into my snippet string, but would you actually prefer to >>do it that way? Ok, I could write a class to systematize it. Maybe I >>will, when I want use file-stored snippets, but I'd like both options >>;-) And I guess I'd like to have Q' as well as q' ;-) > >Well, maybe my first impressions were wrong. After all, the feature is >convenient. But probably you will need to coordinate it well >with encoding things. What if "dochere"'s encoding need to be >different from main program one? Are binary data allowed? >Otherwise the feature will become grammatical disaster... > Thanks for the first glimmer of positive feedback ;-) But you put your finger on an interesting aspect, which is important whether this particular quoting mechanism exists or not. Cf. my other post in this thread re eval("r'\x07'") etc. It's funny, but "raw" strings are less likely to represent binary data than ordinary strings. You can't re-render a raw string containing binary data as a raw string not containing binary data, whereas you can with an ordinary string, since escapes are available. The normal "raw" string is actually usually representing a source string, without interpreting escapes, so it itself can't represent control characters within the normal source alphabet, it can only represent representations of control/unprintable characters. So the "raw" name is misleading in a way. If you pasted binary (i.e., encoded as uninterpreted octets) anywhere into a Python source encoded as Latin-1, presumably the octets would go 1:1 into the source, but when you saw them on the screen, they would appear according to the screen font, yet when re-rendered, would appear escaped (inside strings otherwise they would be syntax errors (except maybe comments?)), as in: >>> '^G','\x07',r'^G' ('\x07', '\x07', '\x07') ... where I typed Ctrl-G binary data into the source where the screen rendered ^G. Presumably, if the source encoding were UTF-8, pasting octets would change them to UTF-8. However, interpreting the UTF-8 source representation of a an octet-string (o'...' ?) would generate the original binary octet sequence as the value of the internal data representation at run time. I think ;-) >>>Making Python as gibberish as Perl is. And all that only to >>>have Windows path be written without double-\ >>Not 'only'. I said 'also' ;-) Perhaps my choice of '|' delimiter triggered >>your 'gibberish as Perl' detector? > >;-) Maybe. I wonder why Perl novices do not know about "dochere" >capabilities of Perl. > I don't know. It's not that prominent in the camel book, but I found it ;-) Regards, Bengt Richter From cpbotha at crabtree.cpbotha.net Sun Mar 31 08:37:07 2002 From: cpbotha at crabtree.cpbotha.net (Charl P. Botha) Date: Sun, 31 Mar 2002 13:37:07 GMT Subject: GUI programming References: <4fsdauofmus28t630866pgf4cu3n6bp16m@4ax.com> Message-ID: In article <4fsdauofmus28t630866pgf4cu3n6bp16m at 4ax.com>, Dale Strickland-Clark wrote: > "Charl P. Botha" wrote: >>With wxPython, one has to get, configure and build wxWindows first (and this >>does take quite a while). > > Nonsense. > > 1. Download > 2. Run Setup > 3. Use it. > > The whole operation takes less than 5 minutes. Hmm, strange that Tkinter is still the default GUI then. As I mentioned, I think wxPython is a great library, but Tkinter is still easier to get running on the majority of different platforms. In addition, the wxWindows abstraction paradigm makes it more difficult to maintain and debug, as it sits above the widget level and has to cater for different widget sets on different platforms. This abstraction results in a more complex system and a much greater porting effort. You may try to negate this point, but keep in mind that people who have realised this are also working on a wxWindows that creates its own widgets by making use of system-dependent drawing calls, i.e. the abstraction is below the widget level. This makes for a wxWindows that is more easy to port and to debug. Also keep in mind that I tend to think in a platform-independent way, where you seem to focus on the Windows situation. To summarise: I think very highly of wxPython, but, at this stage, Tkinter is generally easier to get running on all the platforms that Python supports. This situation could obviously change as wxPython continues maturing. Not wishing to start a Python-GUI-debate again, -- charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/ From guido at python.org Sat Mar 30 00:39:10 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 00:39:10 -0500 Subject: PEP 285: Adding a bool type Message-ID: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> I offer the following PEP for review by the community. If it receives a favorable response, it will be implemented in Python 2.3. A long discussion has already been held in python-dev about this PEP; most things you could bring up have already been brought up there. The head of the thread there is: http://mail.python.org/pipermail/python-dev/2002-March/020750.html I believe that the review questions listed near the beginning of the PEP are the main unresolved issues from that discussion. This PEP is also on the web, of course, at: http://python.org/peps/pep-0285.html If you prefer to look at code, here's a reasonably complete implementation (in C; it may be slightly out of date relative to the current CVS): http://python.org/sf/528022 --Guido van Rossum (home page: http://www.python.org/~guido/) PEP: 285 Title: Adding a bool type Version: $Revision: 1.12 $ Last-Modified: $Date: 2002/03/30 05:37:02 $ Author: guido at python.org (Guido van Rossum) Status: Draft Type: Standards Track Created: 8-Mar-2002 Python-Version: 2.3 Post-History: 8-Mar-2002, 30-Mar-2002 Abstract This PEP proposes the introduction of a new built-in type, bool, with two constants, False and True. The bool type would be a straightforward subtype (in C) of the int type, and the values False and True would behave like 0 and 1 in most respects (for example, False==0 and True==1 would be true) except repr() and str(). All built-in operations that conceptually return a Boolean result will be changed to return False or True instead of 0 or 1; for example, comparisons, the "not" operator, and predicates like isinstance(). Review Dear reviewers: I'm particularly interested in hearing your opinion about the following three issues: 1) Should this PEP be accepted at all. 2) Should str(True) return "True" or "1": "1" might reduce backwards compatibility problems, but looks strange to me. (repr(True) would always return "True".) 3) Should the constants be called 'True' and 'False' (corresponding to None) or 'true' and 'false' (as in C++, Java and C99). Most other details of the proposal are pretty much forced by the backwards compatibility requirement; e.g. True == 1 and True+1 == 2 must hold, else reams of existing code would break. Minor additional issues: 4) Should we strive to eliminate non-Boolean operations on bools in the future, through suitable warnings, so that e.g. True+1 would eventually (e.g. in Python 3000 be illegal). Personally, I think we shouldn't; 28+isleap(y) seems totally reasonable to me. 5) Should operator.truth(x) return an int or a bool. Tim Peters believes it should return an int because it's been documented as such. I think it should return a bool; most other standard predicates (e.g. issubtype()) have also been documented as returning 0 or 1, and it's obvious that we want to change those to return a bool. Rationale Most languages eventually grow a Boolean type; even C99 (the new and improved C standard, not yet widely adopted) has one. Many programmers apparently feel the need for a Boolean type; most Python documentation contains a bit of an apology for the absence of a Boolean type. I've seen lots of modules that defined constants "False=0" and "True=1" (or similar) at the top and used those. The problem with this is that everybody does it differently. For example, should you use "FALSE", "false", "False", "F" or even "f"? And should false be the value zero or None, or perhaps a truth value of a different type that will print as "true" or "false"? Adding a standard bool type to the language resolves those issues. Some external libraries (like databases and RPC packages) need to be able to distinguish between Boolean and integral values, and while it's usually possible to craft a solution, it would be easier if the language offered a standard Boolean type. The standard bool type can also serve as a way to force a value to be interpreted as a Boolean, which can be used to normalize Boolean values. Writing bool(x) is much clearer than "not not x" and much more concise than if x: return 1 else: return 0 Here are some arguments derived from teaching Python. When showing people comparison operators etc. in the interactive shell, I think this is a bit ugly: >>> a = 13 >>> b = 12 >>> a > b 1 >>> If this was: >>> a > b True >>> it would require one millisecond less thinking each time a 0 or 1 was printed. There's also the issue (which I've seen puzzling even experienced Pythonistas who had been away from the language for a while) that if you see: >>> cmp(a, b) 1 >>> cmp(a, a) 0 >>> you might be tempted to believe that cmp() also returned a truth value. If ints are not (normally) used for Booleans results, this would stand out much more clearly as something completely different. Specification The following Python code specifies most of the properties of the new type: class bool(int): def __new__(cls, val=0): # This constructor always returns an existing instance if val: return True else: return False def __repr__(self): if self: return "True" else: return "False" __str__ = __repr__ def __and__(self, other): if isinstance(other, bool): return bool(int(self) & int(other)) else: return int.__and__(self, other) __rand__ = __and__ def __or__(self, other): if isinstance(other, bool): return bool(int(self) | int(other)) else: return int.__or__(self, other) __ror__ = __or__ def __xor__(self, other): if isinstance(other, bool): return bool(int(self) ^ int(other)) else: return int.__xor__(self, other) __rxor__ = __xor__ # Bootstrap truth values through sheer willpower False = int.__new__(bool, 0) True = int.__new__(bool, 1) The values False and True will be singletons, like None; the C implementation will not allow other instances of bool to be created. At the C level, the existing globals Py_False and Py_True will be appropriated to refer to False and True. All built-in operations that are defined to return a Boolean result will be changed to return False or True instead of 0 or 1. In particular, this affects comparisons (<, <=, ==, !=, >, >=, is, is not, in, not in), the unary operator 'not', the built-in functions callable(), hasattr(), isinstance() and issubclass(), the dict method has_key(), the string and unicode methods endswith(), isalnum(), isalpha(), isdigit(), islower(), isspace(), istitle(), isupper(), and startswith(), the unicode methods isdecimal() and isnumeric(), and the 'closed' attribute of file objects. Note that subclassing from int means that True+1 is valid and equals 2, and so on. This is important for backwards compatibility: because comparisons and so on currently return integer values, there's no way of telling what uses existing applications make of these values. Compatibility Because of backwards compatibility, the bool type lacks many properties that some would like to see. For example, arithmetic operations with one or two bool arguments is allowed, treating False as 0 and True as 1. Also, a bool may be used as a sequence index. I don't see this as a problem, and I don't want evolve the language in this direction either; I don't believe that a stricter interpretation of "Booleanness" makes the language any clearer. Another consequence of the compatibility requirement is that the expression "True and 6" has the value 6, and similarly the expression "False or None" has the value None. The "and" and "or" operators are usefully defined to return the first argument that determines the outcome, and this won't change; in particular, they don't force the outcome to be a bool. Of course, if both arguments are bools, the outcome is always a bool. It can also easily be coerced into being a bool by writing for example "bool(x and y)". Issues Because the repr() or str() of a bool value is different from an int value, some code (for example doctest-based unit tests, and possibly database code that relies on things like "%s" % truth) may fail. How much of a backwards compatibility problem this will be, I don't know. If we this turns out to be a real problem, we could changes the rules so that str() of a bool returns "0" or "1", while repr() of a bool still returns "False" or "True". Other languages (C99, C++, Java) name the constants "false" and "true", in all lowercase. In Python, I prefer to stick with the example set by the existing built-in constants, which all use CapitalizedWords: None, Ellipsis, NotImplemented (as well as all built-in exceptions). Python's built-in module uses all lowercase for functions and types only. But I'm willing to consider the lowercase alternatives if enough people think it looks better. It has been suggested that, in order to satisfy user expectations, for every x that is considered true in a Boolean context, the expression x == True should be true, and likewise if x is considered false, x == False should be true. This is of course impossible; it would mean that e.g. 6 == True and 7 == True, from which one could infer 6 == 7. Similarly, [] == False == None would be true, and one could infer [] == None, which is not the case. I'm not sure where this suggestion came from; it was made several times during the first review period. For truth testing of a value, one should use "if", e.g. "if x: print 'Yes'", not comparison to a truth value; "if x == True: print 'Yes'" is not only wrong, it is also strangely redundant. Implementation An experimental, but fairly complete implementation in C has been uploaded to the SourceForge patch manager: http://python.org/sf/528022 Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil fill-column: 70 End: From paul1brian at yahoo.com Tue Mar 26 08:19:13 2002 From: paul1brian at yahoo.com (Paul Brian) Date: Tue, 26 Mar 2002 13:19:13 -0000 Subject: Python UK - April 4th and 5th Message-ID: <1017148758.18693.0.nnrp-01.c1c3e11b@news.demon.co.uk> Dear all, This is another gentle reminder for those Python enthusiasts in the UK that the 2nd Python UK Conference will take place on April the 4th and 5th near Stratford upon Avon. The two day conference is packed full of talks on cutting edge applications of Python, with time to meet, socialise and even discuss code, life and love with fellow Pythonistas. You even get access to the full ACCU conference, attended by luminaries such as Bjarne Stroustrup. You can register online at www.accuconference.co.uk , and further details are available there too. Please note that Python attendees should pay the daily rate for the conference (?130 /day for ACCU members, ?155 else) for the one or two days they choose to attend. I hope to see you there :-) Yours Paul Brian From sjmachin at lexicon.net Thu Mar 28 21:41:14 2002 From: sjmachin at lexicon.net (John Machin) Date: 28 Mar 2002 18:41:14 -0800 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: "Emile van Sebille" wrote in message news:... > John Machin > > Python *could* be made like that with the explict dict() constructor > > ... something like: > > > > freq = dict(default=0) > > ... > > freq[word] += 1 > > Or you could subclass with something like: > > >>> class ddict(dict): > ... def __getitem__(self, ky): > ... return self.setdefault(ky, self.default) > ... def __init__(self, default=None): > ... self.default = default > ... You could indeed. However I'm interested in dicts with hundreds of thousands of entries and millions of accesses. How much extra (a) time and (b) memory would be taken up with this approach (subclassing in Python), compared with the approach of of building it into the core? My answers would be (a) lots (b) don't know, either minimal or lots. Will do some experimentation later. From kwg at renre-europe.com Thu Mar 28 06:37:35 2002 From: kwg at renre-europe.com (Ken Guest) Date: 28 Mar 2002 11:37:35 +0000 Subject: vwait in Python? Message-ID: <1017315455.8141.1.camel@lewis> Anybody know if there's an equivalent to TCL's vwait keyword in Python? k. -- Beware the fury of a patient man - John Dryden From emile at fenx.com Fri Mar 1 16:25:37 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 1 Mar 2002 13:25:37 -0800 Subject: mult-indexed xrange? References: Message-ID: for (x,y, z) in [(i,j, k) for i in range(2) for j in range(3) for k in range(2) ]: print x,y, z -- Emile van Sebille emile at fenx.com From purplebo1212 at yahoo.com Thu Mar 21 23:06:06 2002 From: purplebo1212 at yahoo.com (purplebo1212) Date: Fri, 22 Mar 2002 04:06:06 -0000 Subject: CGI, etc. Message-ID: Hi! I'm new to Python and was looking at writing an CGI script that would execute a program. Any pointers? thanx From bokr at oz.net Sun Mar 10 02:03:17 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Mar 2002 07:03:17 GMT Subject: should i learn it first ? References: Message-ID: On Sat, 9 Mar 2002 12:59:31 -0600, "Jason Orendorff" wrote: >Qiang.JL wrote: >> I am a student who have learned perl,java and other like data structure >> stuff. Now i want to take some further step to learn one or two >> languages to improve my language view. There are two languages are on >> the list: python and C++ > >Learn C first. > I'd say if you don't know C, C++, or Python, then start with Python. Then C++, then C. In that order, you won't have to unlearn patterns of design you absorb solving problems with C. If you start with C, you will get used to a procedural way of looking at problems, and when you get to C++ you will be tempted to see it as just C with extra features. You'll have to dislodge yourself from C habits of thinking in order to "think objects" in C++. Coming from Python you shouldn't have that problem (unless you've carried bad baggage into Python from something else ;-) If you start with Python, you will have a pleasant experience, and if you learn to use classes effectively, you will then more readily see the object-oriented aspects of C++ that really differentiate it from C, and lets you design in ways that aren't practical or fun in C. >> do i need to learn C/C++ to be a good programmer? > >You can be a good Java programmer without knowing C. >You can be a good Python programmer without knowing C. >But every good *all-around* programmer I've met knows C. > No argument. Also, you will find C for more processors than any other language, which is important for embedded and to-be-portable work (like CPython itself), if not so much for app-level work. Regards, Bengt Richter From bkc at Murkworks.com Thu Mar 14 11:00:38 2002 From: bkc at Murkworks.com (Brad Clements) Date: Thu, 14 Mar 2002 11:00:38 -0500 Subject: Has Mark Hammond attained pariah status yet? References: <3C8E7E90.6000608@skippinet.com.au> <3C907711.4030004@skippinet.com.au> Message-ID: <3c90ca29$1_2@news.newsgroups.com> "Mark Hammond" wrote in message news:3C907711.4030004 at skippinet.com.au... > But if I combine this with the fact that new .NET beta releases often > breaks the Python compiler but I have only received 2 complaints in a > year, I concluded that interest is not yet high :) > > Mark. > And .NET is expensive to actually deploy, and we're all cheap. -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! Check out our new Unlimited Server. No Download or Time Limits! -----== Over 80,000 Newsgroups - 19 Different Servers! ==----- From zlu at extremenetworks.com Wed Mar 13 19:43:24 2002 From: zlu at extremenetworks.com (Zihong Lu) Date: 13 Mar 2002 16:43:24 -0800 Subject: is time.sleep a thread safe function? References: Message-ID: Thanks for those of you replied. While I could not 100% exclude this possibility, I did find out that our problem is related to the threading module's t.join() function. -Zihong From usenet at microtonal.co.uk Sat Mar 9 05:51:00 2002 From: usenet at microtonal.co.uk (Graham Breed) Date: Sat, 9 Mar 2002 10:51 +0000 (GMT Standard Time) Subject: PEP 284, Integer for-loops References: Message-ID: Tim Legant wrote: > Out of curiosity I ran a couple of quick greps over the TMDA source. > TMDA doesn't really fall into either of your "alternative" categories; > it's small, but definitely not throwaway and it's an application, not > a core library. It's a mail processor to eliminate SPAM. However, > it's pure Python; there's no integration with C or Java. How small is small? I have a script at with around 1490 lines (including comments and blank lines) and 35 uses of range, some probably evil, most for for loops. Two warty examples for n in range(1,n+1,2): and for element in range(firstIndex, maxBasis+1): where the +1 is used for inclusive boundaries. 7 straight range(len(..))s. > The results were that I found 52 or 53 'for' loops (scanned the > results of the grep by eye, since the word 'for' appears in comments > as well) and exactly no uses of [x]range at all. I have 107 instances of the word "for", which may include comments. > So either Jason and I are significantly better than you and your team > at expressing ourselves naturally in Python or it's the need to > interface with Java that's forcing you to use integer indices all the > time. I'm betting big money on the latter. Well, I've stuck my head above the parapet. Have a look at the code, and see if I'm expressing myself badly. It doesn't integrate with C, Java or COM but does do a lot of work with integers. That's not something Python excels at, but it's such a good language generally that it's still worth using outside its niche. I still don't see a need for language changes, but I can see that people doing heavier number theory than me would. Graham From ajeru at vknn.org Mon Mar 4 00:14:22 2002 From: ajeru at vknn.org (Alexander Jerusalem) Date: 3 Mar 2002 21:14:22 -0800 Subject: mx odbc result strings with special characters? References: <24c39b2c.0203021850.7679418c@posting.google.com> <24c39b2c.0203031100.33d57b3d@posting.google.com> Message-ID: <24c39b2c.0203032114.3df9e523@posting.google.com> Hmm, ok, can you tell me how I can convert such a string back to the ISO8859-1 character set so that I can write it to a text file? The strange thing is, that when I read umlauts from a textfile and print them to standard out, they remain intact. Only when they come from the database driver are they converted to this hex representation. Alexander "Fredrik Lundh" wrote in message news:... > Alexander Jerusalem wrote: > > > Ok, thanks for your reply. Here's my output: > > > > >>> import mx.ODBC.Windows as odbc > > >>> con = odbc.connect("se", "scienceexile", "x") > > >>> c = con.cursor() > > >>> c.execute("select * from country") > > >>> print c.fetchone() > ('aa1', '\xd6sterreich-Ungarn', None, None) > > >>> c.close() > > >>> con.close() > > > > And it's the same when I write the resultset to a file, so I don't > > believe that it's just a display problem. > > on the other hand: > > >>> print '\xd6sterreich-Ungarn' > ?sterreich-Ungarn > > more info here: > > http://www.python.org/doc/current/tut/node5.html > > "The interpreter prints the result of string operations in the > same way as they are typed for input: inside quotes, and > with quotes and other funny characters escaped by back- > slashes, to show the precise value" > > http://www.python.org/doc/current/ref/strings.html > http://www.python.org/doc/current/ref/exprstmts.html > http://www.python.org/doc/current/ref/print.html > (etc) > > > > From shomon at softhome.net Thu Mar 28 06:12:09 2002 From: shomon at softhome.net (skoria) Date: Thu, 28 Mar 2002 11:12:09 -0000 Subject: Extending/embedding versus separation In-Reply-To: Message-ID: Hi Thanks for your help. No, I didn't write the hash tables. I'm writing a stats program based on webalizer. Webalizer and Analog were the fastest and least memory hungry of all the programs I know of, and webalizer is GPL so I was able to use it as a basis for my work, so I get to make free software at work! The hash tables are already written there. This program is intended to run on all the sites hosted by the company I work for, and also on sites not hosted by it, hence the memory/disk space concerns. The way I see it, the python side of things will be a python script that imports the C parts, and can therefore process the logfiles and turn them into hash tables. These are then fed back to the python part, which processes them further, and turns them into graphs and html. The reason for this is I need to be able to quickly develop and expand on the reports produced, so we can do complicated things like, say, visitor paths or percentage increase graphs. As I see it now, the only difference I get if extending python with my adapted webalizer, is that I save writing a little output to file and parsing it into python again. Is this going to be worthwhile? Ale --- In python-list at y..., sjmachin at l... (John Machin) wrote: > > My take on a project like yours would be to write *everything* (that's > not available off the shelf) in Python first, even parts that you > think you know for sure are going to have to be implemented in C > later. Those parts can be coded up in Python modules that can be > replaced by C extensions if really needed. The infrastructure stuff > like command-line-arg handling (or GUI input), file handling, etc is > so much easier to bolt together in Python than in C that I would > prefer extending Python (if necessary) to embedding Python in C. > > Hash tables in C? Are you using a package like Cdt, or did you write > your own? If you can process data into hash tables in C and then get > the data into Python faster than you can process the data into > dictionaries in Python, then please divulge your deep dark magic > spells to Tim Peters the Python-dict-shaman. > > You seem to be a bit concerned about memory usage. My advice is to > write a prototype of your application in Python, bearing memory > efficiency in mind, but not obsessively -- i.e. use the most > appropriate data structures and don't distort your Python code into > unreadability. Then you either have enough memory or you don't. Do > some back-of-the-envelope calculations, like: a 256MB stick of memory > costs how few hours of developer time? If you can't for whatever > reason get more memory, then it's time to consider your next step. If > your application has some large dictionaries that only have objects of > type X as keys and type Y as values (where Y is a simple type like int > or float) then it might be a good idea to take a copy of dictobject.c > and make a specialised intdict (say) module that instead of managing > (PyObject *) pointers, managed int values directly -- this would save > you heaps (pardon the pun) of memory; see recent thread in this > newsgroup about amount of memory taken up by Python objects. > > For another (already implemented) variation on this memory-saving > theme, google("c.l.py", "Machin intern memory"). > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list From gimbo at ftech.net Thu Mar 21 05:24:04 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Thu, 21 Mar 2002 10:24:04 +0000 Subject: #define equivalents and config files In-Reply-To: <20020321085307.GB10214@software.plasmon> References: <3C9963BD.1040304@verizon.net> <3C9964FF.46805590@engcorp.com> <20020321085307.GB10214@software.plasmon> Message-ID: <20020321102404.GA1667@andy.tynant.ftech.net> On Thu, Mar 21, 2002 at 08:53:07AM +0000, Dave Swegen wrote: > I'm basically after a single file where such values can be stored, and > then used in various parts of the program without having to pass extra > configuation variables around. Well, this might be overkill depending on the size of your system, but I quite often use the singleton design pattern for this purpose: I have a module called Config which has a Config() function for accessing the singleton. Working demo: -- begin Config.py #!/usr/bin/env python _configInstance = None def Config(): # This function, and _only_ this function, should be used to # access _configInstance. global _configInstance if _configInstance is None: _configInstance = _config() return _configInstance class _config: def __init__(self): # Initialise from wherever, eg hard-coded, read from file on # disk (maybe using ConfigParser), checking command-line # parameters using getopt, etc. self.foobar = 'spam!' -- end Config.py -- begin client.py #!/usr/bin/env python import Config def foo(): config = Config.Config() print config.foobar foo() -- end client.py As I say, this may be overkill depending on the size of your system, but for largish systems it can be quite handy because it saves you from, as you put it, "having to pass extra configuation variables around". I typically use it when I've got more than, say, three modules which need to share config information. -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From tim.one at comcast.net Sun Mar 17 19:40:30 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 17 Mar 2002 19:40:30 -0500 Subject: pyclbr _modules cache - why? In-Reply-To: <3c9501d5.588674328@news.wlg.ihug.co.nz> Message-ID: [Culley Angus] > Does anyone know the reasoning behind forcing use of the cache in the > pyclbr module. Same reason anyone ever uses a cache: speed. > I am implementing a simple ide where changes to modules are being > updated in the gui... Alas I have had to hack the pyclbr module to > stop it using cached data. Consider calling pyclbr._modules.clear() instead, at such times your app believes the cache may be stale. > Surely if someone is implementing a classbrowser, it is a fair > assumption that they may be updating the classes being browsed. Sure. I'm not sure pyclbr.py was written solely for you and your particular app, though . From trentm at ActiveState.com Thu Mar 14 21:08:48 2002 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 14 Mar 2002 18:08:48 -0800 Subject: Python2.2 and expat In-Reply-To: ; from cfox@crystalcherry.com on Fri, Mar 15, 2002 at 01:17:27AM +0000 References: Message-ID: <20020314180848.A13193@ActiveState.com> [Colin Fox wrote] > Hello, everyone. > > I'm trying to build garnome, which requires Python2.2 + Python2.2-xml. > I've got Python2.2 built, but for some reason it doesn't seem to build > expat. And when I try to "import xml.parsers.expat" I get: > > >>> import xml.parsers.expat > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/lib/python2.2/xml/parsers/expat.py", line 4, in ? > from pyexpat import * > ImportError: No module named pyexpat > > Where is pyexpat supposed to come from? There is a section on building the pyexpat extension in dist\src\PCbuild\readme.txt. Basically you need a separate build of expat in the right place so that Python pyexpat build can find and use it. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From mapler at erinet.com Fri Mar 1 21:06:10 2002 From: mapler at erinet.com (RMaple) Date: Fri, 01 Mar 2002 21:06:10 -0500 Subject: Stop image shift on tkinter button press? Message-ID: <3c8035a8$0$35568$4c5ecdc7@news.erinet.com> Hello, Is there any way to suppress the annoying right/down shift a button image gets whenever the button is rendered with SUNKEN relief? Thanks, Ray From tejarex at yahoo.com Sat Mar 23 10:26:03 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 23 Mar 2002 15:26:03 GMT Subject: New SIG on logic/CLP programming in Python References: Message-ID: "Magnus Lie Hetland" wrote in message news:slrna9ou47.ajb.mlh at vier.idi.ntnu.no... > Logic programming (or even something similar, with implicit > backtracking etc.) would be very nice to have, IMO. The backtracking > stuff itself ought to be easy to implement (efficiently, even) with > generators. There are some very interesting examples of using generators to do backtracking in, I believe, test_generators.py in the distribution. As I remember, both n-queens and knights tour examples are present. Terry J. Reedy From gbreed at cix.compulink.co.uk Tue Mar 12 12:15:34 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Tue, 12 Mar 2002 17:15:34 +0000 (UTC) Subject: ADO and Store Procedure References: Message-ID: Joel Quinet wrote: > There is a Unique Contsraint on that table. If I try to insert an > existing > value in that table with the following script, > I receive no error .... > I would like to receive an error and be able to deale with it. > Moreover, My store procedure return 1 in case of problem. How can I > rescue > that ? > How can I do that ? Try returning a negative number, and you should get an exception triggered. Otherwise, it's an ADO problem, and nothing in particular to do with Python. Try microsoft.public.inetserver.asp.db > rs, res = cmd.Execute() You might find res has the right value, or you might have to initialize the recordset first. cmd.Paramters.Refresh()? I forget. If you do something like cmd.Parameters("continent").Value = "Europe" that might do the trick as well, depending on what the parameter is called. The return value might then be one of the parameters after you run the procedure. Graham From python at rcn.com Sun Mar 31 20:05:26 2002 From: python at rcn.com (Raymond Hettinger) Date: Sun, 31 Mar 2002 20:05:26 -0500 Subject: Most important extensions? References: Message-ID: "Aahz" wrote in message > I'm teaching Python for [Perl] Programmers at OSCON this July. I've > already decided to mention mxODBC, NumPy, and PIL, plus PythonPoint (aka > ReportLab) gets a mention on my title page. I'd like this group to vote > on the most important extensions for me to add to this list. Please vote > for no more than three. There's only one: ActiveState's win32all -- the COM access to other programs is worth millions. Actually, make that two: PyChecker -- because who's perfect all the time (except for timbot and f/bot) No, no, it's three: Gadfly -- who doesn't need portable, full blown SQL capabilities every now and again. Darn, three is the limit. I must not mention htmlgen or piddle no matter how useful there are. Yes, I definitely will play by the rules and not mention them or even python mega-widgets. Lips sealed, I won't say their names even under intense questioning. That's all I have to say and you can't make me name any more than three. The psycho optimizer is right out. Unmentionable and way, way off the list of three. Raymond Hettinger, CPA From michael at stroeder.com Fri Mar 8 08:39:33 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 08 Mar 2002 14:39:33 +0100 Subject: [ANN] istring 1.0.1 released; announce list created References: <7x3czbag9q.fsf@ruckus.brouhaha.com> Message-ID: <3C88BF15.1010202@stroeder.com> Paul Rubin wrote: > "Steven D. Arnold" writes: > >>>>>from neo.istring import istring as i >>>>>l = [1,2,3] >>>>>i('first value is $l.0') >>>>> >>'first value is 1' >> > > It occurs to me, you could get rid of the parentheses by making the > i object an instance of a class that overrides (say) division: > > >>> from neo.istring import istring as i > >>> l = [1,2,3] > >>> i/'first value is $l.0' > 'first value is 1' Seems this thread shifts to code obfuscation... ;-) Ciao, Michael. From brobbins333 at shaw.ca Mon Mar 11 13:51:01 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Mon, 11 Mar 2002 18:51:01 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> <3c8a9c23.152007063@news> <3c8b8112.27836128@news> Message-ID: <3c8cf137.2639944@news> I understand and agree with what you are saying. However, it is possible in some languages (VB, for example) to return a numerical result from a function with only two (or any other number) of decimal places. Not a formatted string representation, but an actual numerical value that can be used in further calculations. This value is, of course, an approximation and has really been truncated rather than "rounded." Anyway, we are arguing now over how many angels can dance on the head of a pin. I understand the problem and can work around it. This group is a great resource. Thanks for all your help and time. Bruce On Sun, 10 Mar 2002 16:31:51 GMT, grante at visi.com (Grant Edwards) wrote: >In article <3c8b8112.27836128 at news>, brobbins333 at shaw.ca wrote: > >> OK, that makes perfect sense. In my case, I was simply looking >> for a predictable way to return a number with two decimal >> places > >That's just not possible. The "number" you're talking about >doesn't _have_ decimal places. It's a binary floating point >number. It has "binary places". In theory you could write a >function that rounds to N binary places, but I don't know how >useful that is going to be. > >In order to talk in a meaningful way about decimal places, you >have to use a base-10 representation: BCD floating point or BCD >fixed point. Strings such as "123.456" are sort-of BCD >floating point, and you can round to N decimal places when >converting from binary floating point to "String/BCD FP": > > f = 123.4567 > s = "%0.2f" % f > >>>> f = 123.456 >>>> s = "%0.2f" % f >>>> f >123.456 >>>> s >'123.46' > >"String/BCD FP" as I've termed it can represent numbers just >fine, but since you can't do any mathematical operations on them >it's of limited value. > >Since you're using binary floating point, the round() function >is actually converting it's binary floating point input value >to the closest value to X such that if X were converted to BCD >in the future it will have the requested number of decimal >places. But, X may not be exactly representable. If you're >using round(x,N) your probably just fooling yourself. > >If you _really_ do want a number with N decimal places: > >the topic of base-10 numbers for Python comes up occasionally, >and I believe that there are BCD packages available. If you >really want to do your calculations in base 10, you might want >to search the newsgroup archives for "BCD". > >-- >Grant Edwards grante Yow! Please come home with > at me... I have Tylenol!! > visi.com From tchur at optushome.com.au Sat Mar 30 20:33:25 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 31 Mar 2002 11:33:25 +1000 Subject: CGI/modpython ??? References: Message-ID: <3CA66765.CC818762@optushome.com.au> Michael Hall wrote: > > Sorry folks, I just found the modpython docs, so I can RTFM. Still, I'd be > interested in any comments about modpython versus Python CGI. > There is a note on deploying Albatross apps with mod_python at http://www.object-craft.com.au/projects/albatross/albatross/app-popview5.html In a private communication, Dave Cole, the principal developer of Albatross, indicated that he was able to get some impressive performance out of this type of mod_python arrangement. Tim C From geoff at gerrietts.net Fri Mar 8 16:31:17 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 8 Mar 2002 13:31:17 -0800 Subject: PEP Parade In-Reply-To: References: Message-ID: <20020308213117.GG4569@isis.gerrietts.net> Quoting Donn Cave (donn at u.washington.edu): > Quoth Roy Smith : > | "Tim Peters" wrote: > | > Note that Guido wants to keep 2.3 free of new core language features. You > | > can deduce that from reading the essay, or-- like me --you can just believe > | > it because it's true . There's a huge backlog of good ideas for > | > improving the internals and libraries, and I wouldn't be surprised to see > | > the focus remain there for 2.4 too. > | > | Not touching the core language is a Good Thing. It's really tough to > | convince people that python is a viable tool when it's a moving target. > | > | It's been somewhat of an uphill battle to get my development group to > | accept the fact that I write tools for the whole group's use in python. > | Having the core language change from version to version just makes it > | worse, as we discover imcompatabilities between whatever version I'm using > | to develop on and whateve they're running on their boxes. Telling people, > | "Oh, you need to upgrade to version X" gets old pretty fast. As the saying > | goes, "if you're explaining, you've already lost." > > I have proposed before that those of us who are into having > a viable tool instead of a moving target, should just pick one > and stick with it. 2.1.1, for example. Of course you and I > can do that, solving the problems with our respective groups - > but putting us in kind of a backwater. If we sort of collectively > agree on 2.1.1 (or whatever) for that role, though, that backwater > could get pretty lively. I agree with the sentiment expressed in these posts. I'm not sure if the proposed solution is the best one. On the other hand, I know that I would feel more comfortable pushing for adoption of a given version if I knew that six months from now, I wouldn't hafta start the whole push all over again because some new feature made everything uncertain again. I think a lot of people and projects froze on 1.5.2, because it was the last 1.* series release, but advice in this newsgroup tends to suggest this is a very bad idea; bugfixes haven't been pushed back into the 1.5 series, and there's no active maintenance. I think my fear about picking a version and sticking with it is that the same thing would happen, again, and trying to catch the moving target would be even harder than trying to keep up with it. --G. -- Geoff Gerrietts "Ordinarily he was insane, but he had lucid moments when he was merely stupid." --Heinrich Heine From thomas at weholt.org Sun Mar 17 14:52:41 2002 From: thomas at weholt.org (Thomas Weholt) Date: Sun, 17 Mar 2002 19:52:41 GMT Subject: How-to : Running profile from inside an class on the class' own methods ?? Message-ID: Hi, I want to profile a method inside a class from another method inside the same class. Example code below : >>> class A: ... def __init__(self): ... self.var1 = 'var1' ... def go(self): ... self.var1 = 'go1' ... def profile(self): ... import profile ... profile.run('self.go()') ... >>> a = A() >>> a.profile() Traceback (most recent call last): File "", line 1, in ? File "", line 8, in profile File "E:\Python21\lib\profile.py", line 71, in run prof = prof.run(statement) File "E:\Python21\lib\profile.py", line 356, in run return self.runctx(cmd, dict, dict) File "E:\Python21\lib\profile.py", line 362, in runctx exec cmd in globals, locals File "", line 1, in ? NameError: name 'self' is not defined >>> How can I profile the go-method inside the A-class from inside the A-class ?? Any hints? Thomas From jimd at vega.starshine.org Thu Mar 21 07:03:22 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 21 Mar 2002 12:03:22 GMT Subject: Word frequencies -- Python or Perl for performance? References: Message-ID: In article , Nick Arnett wrote: > Anybody have any experience generating word frequencies from short documents > with Python and Perl? Given a choice between the two, I'm wondering what > will be faster. And a related question... any idea if there will be a > significant performance hit (or advantage?) from storing the data in MySQL > v. my own file-based data structures? > I'll be processing a fairly large number of short (1-6K or so) documents at > a time, so I'll be able to batch up things quite a bit. I'm thinking that > the database might help me avoid loading up a lot of useless data. Since > word frequencies follow a Zipf distribution, I'm guessing that I can spot > unusual words (my goal here) by loading up the top 80 percent or so of words > in the database (by occurrences) and focusing on the words that are in the > docs but not in the set retrieved from the database. > Thanks for any thoughts on this and pointers to helpful examples or modules. > Nick Arnett I don't know what you're really trying to do, but I decided to code up a quickie "word counter" for the hell of it. I started with one that would simply count "words" (white space separated sequences of letters, hyphens and apostrophes). I then decided to also denote which of them were "known" words and keep a count of those as well. So, here's my very own version (in about 80 lines): #!/usr/bin/env python2.2 import sys, string class Wordcount: """Keep a count of all unique "words" in text Maintain a dictionary or words, each with a count of the number of occurences, Add arbitrary text to it, dump the dictionary on demand """ # for words like o'clock and O'Holloran and fiddle-faddle # what should we do about contractions? # ditto possessive forms? tr = string.maketrans('','') rm = string.punctuation + string.digits rm = string.translate(rm, tr, "'-") # Don't remove apostrophes and hypens from "words" knownWords = {} knownWordsRead = 0 def __init__(self): self.words = {} self.count = 0 # total words processed self.nword = 0 # number of words in our instance dictionary self.known = 0 # number of our words found in the class dict. # Each instance gets its own word list and total count if not Wordcount.knownWordsRead: # We'll try to create the "known words" dictionary # But we only do that on first instantiation # since all instances share this one dictionary try: Wordcount.knownWordsRead = 1 wlist = open('/usr/share/dict/words','r') for i in wlist: i = i.lower().strip() if not i in Wordcount.knownWords: Wordcount.knownWords[i] = 0 except: pass # but we won't try very hard # print "debug: ", word def add (self,text): for each in text.split(): word = string.translate(each, Wordcount.tr, Wordcount.rm).lower() word = word.strip() while word.endswith("'"): word = word[:-1] # strip quotes while word.startswith("'"): word = word[1:] # if word.startswith('-'): continue if word.endswith('-'): continue if word.endswith("n't"): word = word[:-3] # can't include these if word.endswith("'ll"): word = word[:-3] # or you'll wonder if word.endswith("'s"): word = word[:-2] # who's if word == '-' or word == "'" or len(word) < 1 : continue self.count += 1 if not word in self.words: self.words[word] = 1 self.nword += 1 else: self.words[word] += 1 if word in Wordcount.knownWords: self.known += 1 def dump (self): self.items = [ (y,x) for x,y in self.words.items() ] self.items.sort() self.items.reverse() return self.items if __name__ == '__main__': wcount = Wordcount() for i in sys.argv[1:]: file = open(i,"r") for line in file: wcount.add(line) # handle hyphenation? ## poss. by cutting last word IFF ends in hyphen ## and prepending to next line. print wcount.count, wcount.known, wcount.nword, \ wcount.known/float(wcount.count), wcount.nword/float(wcount.known) for count, word in wcount.dump(): if count > 1: # Skip "unique" words if word in Wordcount.knownWords: word += "*" print "%7d %s" % (count, word) print wcount.count, wcount.known, wcount.nword, \ wcount.known/float(wcount.count), wcount.nword/float(wcount.known) It's a bit crude, particularly in handling the apostrophes (vs single quotes) and hyphens/dashes. However, it seems to work okay. I made NO effort to optimize it. (I'd at least use for i in file.readlines(): rather than iterating over each one individually, if I was concerned about speed). I tested by running the following commands: for i in /bin/* /usr/bin/*; do bname=$(basename $i); man $bname | col -b > /tmp/$bname.man done time ./wordcount.py /tmp/*.man | hea speed. Here's the output from that: 1602048 1361723 36978 0.849988889222 0.0271553025101 117960 the* 41673 to* 36275 is* 34975 a 32191 of* 27045 and* 22881 in* 20336 for* 17571 be* Traceback (most recent call last): File "./wordcount.py", line 81, in ? print "%7d %s" % (count, word) IOError: [Errno 32] Broken pipe real 1m48.212s user 1m47.950s sys 0m0.250s $ ls /tmp/*.man | ./wc.py 1761 1761 31804 $ du /tmp/*.man .... 15836 total $ find /tmp/*.man -printf "%s\n" \ | awk '{n++; t+=$1}; END { print t/n ; }' 7104.33 ... so it handled over 1700 medium size files (average 6K each, about 14Mb total) in less than two minutes. Of the words I counted it looks like about 84% of them were "known" words from /usr/share/dict/words; and it looks like I found about 2% of the known words. (In other words, the Linux man pages only use about 2% of the English vocabulary). I doubt the top ten words from my list will surprise anyone: the, to, is, a, of, and, in ... I don't have the urge to write a version in Perl. Not tonight anyway. Of course this script is free for any use you can think of. From return at trafficmagnet.net Fri Mar 29 09:52:38 2002 From: return at trafficmagnet.net (Christine Hall) Date: Fri, 29 Mar 2002 22:52:38 +0800 (CST) Subject: http://news.linuxprogramming.com Message-ID: <47CR1000037431@emaserver.trafficmagnet.net> Hi I visited http://news.linuxprogramming.com, and noticed that you're not listed on some search engines! I think we can offer you a service which can help you increase traffic and the number of visitors to your website. I would like to introduce you to TrafficMagnet.net. We offer a unique technology that will submit your website to over 300,000 search engines and directories every month. You'll be surprised by the low cost, and by how effective this website promotion method can be. To find out more about TrafficMagnet and the cost for submitting your website to over 300,000 search engines and directories, visit www.TrafficMagnet.net. I would love to hear from you. Best Regards, Christine Hall Sales and Marketing E-mail: christine at trafficmagnet.net http://www.TrafficMagnet.net This email was sent to python-list at python.org. I understand that you may NOT wish to receive information from me by email. To be removed from this and other offers, simply go to the link below: http://emaserver.trafficmagnet.net/trafficmagnet/www/optoutredirect?UC=Lead&UI=421800 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwh at python.org Mon Mar 18 16:35:59 2002 From: mwh at python.org (Michael Hudson) Date: Mon, 18 Mar 2002 21:35:59 +0000 (GMT) Subject: RELEASED: Python 2.2.1c1 Message-ID: We've released a release candidate for the next bugfix release of Python, 2.2.1. Get the scoop (and the files) here: http://www.python.org/2.2.1/ In order to make 2.2.1 a solid release, please help by + Building the release, and running the test suite on your platform. + Building your extension modules and applications against this release, and running *their* test suites. + Reporting any problems to the bug tracker at sf: http://sourceforge.net/bugs/?group_id=5470 This being a bugfix release, there are no exciting new features -- we just fixed a lot of bugs. For a moderately complete list, please see: http://http://sourceforge.net/project/shownotes.php?release_id=80208 Depending on how many problems are found in this release, 2.2.1 final or a second release candidate will follow next week. Extra note for keenies: One of the bugs addressed in this release relates to the behaviour of floating point numbers with respect to under- and over-flow. This has traditionally been an obscure platform-dependent mess. To make sure that this is still the case, I would ask those of you with access to the more unusual platforms (i.e. not Linux/x86, Win32/x86) to run test_math in verbose mode and *email me* the results, including details of platform and OS tested. Thanks. Cheers, The Python development team. From stephen at xemacs.org Fri Mar 8 23:44:57 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 09 Mar 2002 13:44:57 +0900 Subject: PEP Parade References: Message-ID: <87henqe4dy.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Roy" == Roy Smith writes: Roy> It's really tough to convince people that python is a viable Roy> tool when it's a moving target. Tell that to Bill Gates, hey! Not to deny your point. Rather to point out that if Bill can do it, somehow, so can we. And if we manage it better than the infamous Word (whichever, 96?) transition, there's a lot of good will to be had. Roy> Having the core language change from version to version just Roy> makes it worse, as we discover imcompatabilities between Roy> whatever version I'm using to develop on and whateve they're Roy> running on their boxes. So you standardize locally. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From philh at comuno.freeserve.co.uk Fri Mar 29 13:01:46 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Fri, 29 Mar 2002 18:01:46 +0000 Subject: number of lines in a file References: Message-ID: On Fri, 29 Mar 2002 06:36:14 -0800, Emile van Sebille wrote: >Joseph Youssef >> hello, I am nwe to Python and I'm trying to write this >> script but I need it to check how many lines is in >> the file and I don't know how so I'm hoping someone >> could tell me. > > >len(open('/path/and/filename').readlines()) Alternatively: os.system("wc -l %s" % filename) -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From Chris.Barker at noaa.gov Wed Mar 6 14:49:47 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Wed, 06 Mar 2002 11:49:47 -0800 Subject: Twain Scanners and some other questions References: Message-ID: <3C8672DB.28AD17B5@noaa.gov> Steven Majewski wrote: > I don't know of any reason the spec couldn't be implemented on unix, > but I also don't know if any implementation. ( And without commercial > apps that use it like Photoshop, there's probably not much demand. ) This looks like a good place to start looking: http://www.twain.org/docs/twain_20_unix.htm -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From cliechti at gmx.net Thu Mar 28 15:52:34 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Mar 2002 21:52:34 +0100 Subject: Pippy References: <20020328153333.69176.qmail@web21110.mail.yahoo.com> Message-ID: "Jeffery D. Collins" wrote in news:mailman.1017333598.12973.python-list at python.org: > I have recieved patches that I plan to integrate into Pippy, but > wanted to wait until my sourceforge project was up and running. > However, it's been approximately a month since I submitted the > application and still haven't heard a word, even after inquiring a > week ago (or so). i have two projects there: pyserial.sf.net and mspgcc.sf.net and both got approved within two days or less. are you sure that the regitartion worked? maybe the request was inclomplete due to broken connections or so. chris > Perhaps I should look to host the project > elsewhere. Can anyone suggest an alternative with similar > capabilities? -- Chris From frederic.giacometti at arakne.com Sun Mar 3 23:29:24 2002 From: frederic.giacometti at arakne.com (Frederic Giacometti) Date: Sun, 03 Mar 2002 20:29:24 -0800 Subject: Stackless Platform Independence? References: <987e7uoo5v87fsjruq0ug6bff0vha5ear0@4ax.com> <3C829AA2.1B21E205@arakne.com> <15490.51249.422151.234776@12-248-41-177.client.attbi.com> Message-ID: <3C82F824.5EEE9310@arakne.com> Skip Montanaro wrote: > Frederic> Just reverse the paradigm: have the python VM run in a single > Frederic> thread, using stackless microthreads for python > Frederic> multithreading, and run the C calls in a pool of threads. > Frederic> This way: no lock is needed, since only one thread runs the > Frederic> VM, with the help of microthreads, and C calls run in other > Frederic> threads. > > I don't think this will work without a lot of effort. There is code that is > not strictly speaking part of the virtual machine that assumes the presence > of the global interpreter lock. It can perfectly cohabitate with the current thread implementation; there is no incompatibility. An implementation would begin with defining a new CFunction flag (the 3rd field of the CFunction data structure. This flag would have the PVM instead call a function that would: - remove the microthread from the queue of active microthreads - pick an OS thread from the thread pool, place the CFuntion and its args in its exec queue, and return to the PVM Upon return of the CFunction, the OSThread would put back the thread on the queue of active threads of the PVM, along with its result object, "et le tour est joue'". The C programmation of this new type of CFunction would be a little bit different: 1) on one hand, no global interpreter lock to release :)) 2) on another hand, by default, nothing should be done that modifies the reference count of PyObjects referenced in other OS threads (note: the OS thread can however create plain new Python objects); but this is actually no different that current Python C programming after releasing the Python lock. Helper functions/macros could provided to circumvent 2): - either recourse to the global Python lock (nothing to invent/implement, here) - create a function that create a microthread that will have the PVM increment/decrement the count(s) (and maybe to something else too), place it on the PVM queue, and wait synchronously until it returns. There is a third venue too: Add a field to the PyObject structure that describes 'OS Thread ownership' (the 0 value would certainly refer to the master PVM). Then: - Rule: OS threads can only modified reference count of objects they own - Helpers: provide functions that gives the possibility to an OS thread to ask the thread that owns the object(s), to transfer ownership. Such functions would be used whenever local ownership is not certain (there's no point in testing ownership on each reference counting operation) .... Technically, this addition to the PyObject structure would open the door to: - multiple PVM on multiprocessing machines - remote Python object transparency Such a schema would require some elaboration, like any; but there's no wizardry here, and it could be done with a minimal imprint on the current PVM code, too. But: - microthreads are a preamble - stackless is a preamble to microthreads... Frederic Giacometti, Arakne > > > -- > Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From hfoffani at yahoo.com Fri Mar 8 17:37:18 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Fri, 8 Mar 2002 23:37:18 +0100 Subject: uniq, was Re: PEP Parade References: Message-ID: <20020308173734.951$gl@news.newsreader.com> "Roman Suzi" > On Fri, 8 Mar 2002, Skip Montanaro wrote: > >Nothing new is necessary since 2.2 was released: > > > > >>> mylist = [1,2,3,5,6,6,9,9,1,2,3,4] > > >>> mydict = dict(zip(mylist,mylist)) > > >>> mydict > > {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 9: 9} > > >>> mydict.values() > > [1, 2, 3, 4, 5, 6, 9] > > Wow. Then I am a bit underinformed. What uniq is for then? > To cover lengthy: > > def uniq(x): > return dict(map(None, x, [None])).keys() > > ? > keys in a dictionary have to be inmutable objects. The list we want to remove duplicates can contain other object type. See Tim's recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560/index_txt -Hernan From db3l at fitlinxx.com Fri Mar 15 17:18:12 2002 From: db3l at fitlinxx.com (David Bolen) Date: 15 Mar 2002 17:18:12 -0500 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <_kqk8.25881$N7.5410299@ruti.visi.com> Message-ID: grante at visi.com (Grant Edwards) writes: > TCP/IP networking that was pasted on as an afterthought, and > that's when select came into the picture. Well, the IP stack came later but with the current WinSock2 there's a pretty flexible architecture for protocols and service providers which isn't too bad, and IP is just one of the "providers". So multiple network stacks (not just IP) can be treated the same. > Are TCP/IP connection native kernel objects? In a literal sense I'd have to say no - you don't get a kernel handle to them (at least at the application level). I'm sure they have some internal handles they managed, but the socket itself is a higher level abstraction managed by the winsock library. However, Win32's winsock does provide clean ways to tie them to signaling kernel objects (events) which let's them play equally (be processed simultaneously) with other kernel objects to signal completion of operations. And that's pretty much the same way that asynchronous file I/O works, providing an event object for completion. So in practical terms, they behave just as other resources do for I/O when using the Win32 functions. Of course, to make this work you need to use the Win32 aware (Microsoft extensions) version of the socket functions, which of course are non-portable. But that would let you incorporate socket selections as well as waiting for file, pipe, mailslot, etc... or any other I/O or events simultaneously. It's not the same as the Unix use of 'select' but that gets to the question of the basic underlying model differences between Unix v. Win32 as opposed to better or worse. In some ways for most uses I find the Unix approach more streamlined, but there are times when the Win32 approach is more flexible. For example, Unix select can only wait on file handles for read/write/exception. Under Win32 you typically set up asychronous activities and then wait on a collection of event objects (or other native objects that can signal themselves). You can easily add in your own event objects into the mix for any arbitrary signaling. In more concrete terms (and more to the context of this thread), it provides perhaps a cleaner approach to interrupting the blocked select. With select you might try to forceably interrupt the select by closing the socket, or sending fake data to another (or the same) socket, or having a fairly quick timeout and check for a flag. But all of those approaches are really ways to try to work around the fact that select only works on I/O operations to file handles. With Win32 native functions, I'd just define an extra event object, and wait on that event object along with the event objects related to the sockets. To shut it down, just signal the special event object. It's interesting that all of these approaches do have one thing in common - they tend not to be portable. I think it basically shows that the pure sockets-based select() model, which is really what different systems have standardized on as portable, just doesn't address this aspect of things well, thus needs along these lines tend to devolve into platform-specific solutions. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From mhammond at skippinet.com.au Mon Mar 25 19:39:25 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 26 Mar 2002 00:39:25 GMT Subject: pythonwin and raw_input References: Message-ID: <3C9FC358.2080608@skippinet.com.au> logistix wrote: > I could've swore I posted this yesterday, so please have mercy on my soul if > my news server is just messed up. > > Does anyone know how to access the builtin raw_input function in pythonwin? > Pyhtonwin overrides it with a dialog box. This doesn't work out too well > with the following: > > import code > code.interact() The short answer is "no" :( It could be done by someone suitably motivated though :) It is quite tricky due to the event processing requirements of the GUI. Pythonwin's interact.py module uses the code module to implement the interactive window, and it jumps through nasty hoops to make it work. Mark. From rjones at ekit-inc.com Wed Mar 6 17:43:10 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 7 Mar 2002 09:43:10 +1100 Subject: The language vs. the environment In-Reply-To: References: Message-ID: <200203062243.WAA15402@crown.off.ekorp.com> On Thu, 7 Mar 2002 09:36, Sean 'Shaleh' Perry wrote: > On 06-Mar-2002 Steve Lamb wrote: > > On Wed, 06 Mar 2002 13:21:35 -0800 (PST), Sean 'Shaleh' Perry > > > > wrote: > >> help release more python modules so perl mongers will quite wagging CPAN > >> in front of our faces. > > > > Quality over Quantity. :) > > not to disagree, however there are FAR more interesting perl modules out > there than python ones. Excellent! Skip's marvellous post about how people could contribute to python's growth has already reduced itself to a slanging match that _completelty_ misses the point he was trying to make! What was that, about 10 minutes? Wow. Sorry Skip, I know you meant well. Richard From tejarex at yahoo.com Thu Mar 7 13:46:03 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Thu, 07 Mar 2002 18:46:03 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> Message-ID: "Bengt Richter" wrote in message news:a67ehl$uhi$0 at 216.39.172.122... > How does it seem if you go along the steps I took?: > > 1. You have an arbitrary sequence of characters that are to be > the value of a string. > 2. The sequence may contain both ''' and """ and may even end > with \ and it must be unchanged. > 3. (2) Means you need a different delimiter than " or ' or """ or '''. Since (3) does not follow from (2), it seems like this proposal is unnecessary. Strings read from a file (this includes raw_input() from users) already meet desiderata 1 and 2. >>> s=raw_input('Hi: ') Hi: Python delimiters include ', ", ''', """, and \ >>> print s Python delimiters include ', ", ''', """, and \ In the extremely rare case in which one really *needs* all 4 string delimiters within a single string and the string *must* get its value from a programmer-writter string literal rather than a file, one can use octal escapes (or \\ for \). >>> print """Python's string delimiters are ', ", ''', and \042\042\042.""" Python's string delimiters are ', ", ''', and """. >>> print '''Python's string delimiters are ', ", \047\047\047, and """.''' Python's string delimiters are ', ", ''', and """. Terry J. Reedy From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Fri Mar 29 11:39:39 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 29 Mar 2002 17:39:39 +0100 Subject: multicast test program References: Message-ID: <3ca498c2$1@news.mt.net.mk> > Is there any python code which test multicast? I want > to send and receive multicast packet by python code. Any > docs or links about this? Interesting subject. A little of google-searching revealed this: http://www.menet.umn.edu/~curt/lists/fgfs/archive-200102/msg00599.html Very interesting... There's no reason import regsub in that. -- ?????? To boldly go where I surely don't belong. From gerhard at bigfoot.de Tue Mar 19 06:31:15 2002 From: gerhard at bigfoot.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 19 Mar 2002 03:31:15 -0800 Subject: RELEASED: Python 2.2.1c1 References: Message-ID: <3C972183.3050804@bigfoot.de> Michael Hudson wrote: > I would ask those of you with access to the more > unusual platforms (i.e. not Linux/x86, Win32/x86) to run test_math in > verbose mode How would I do that? Gerhard From newsgroups at thomas-guettler.de Sun Mar 17 16:39:23 2002 From: newsgroups at thomas-guettler.de (Thomas Guettler) Date: Sun, 17 Mar 2002 22:39:23 +0100 Subject: Zope Question References: Message-ID: <3C950D0B.60602@thomas-guettler.de> Colin Fox wrote: > Hi, everyone. > > I realize that this isn't the best place to post Zope questions, but hey, > it's written in python...:) > > Anyway, I'm trying to create a form for editing database entries. Part of > the form includes a pair of radio buttons for gender. I want to seed this > from with values from the database. > > The problem is, radio buttons have a special attribute called 'checked' > to indicate when they are selected. The Zope page templates allow me to > alter things of the form ' value="xxx" ', but apparently not where the > keyword itself is the value. If there was something like > 'state="CHECKED"', it would be easy. But I can't figure out how to insert > either CHECKED or nothing depending on the state of a variable. > One solution would be to do it like this (I use pseudo-code since I am new to page templates, and don't want to look up the syntax): if checked==true else I know it is not the best solution since you have to type the line twice but it should work. thomas From marijn at sanity.dhs.org Fri Mar 1 02:30:57 2002 From: marijn at sanity.dhs.org (marijn Vriens) Date: 28 Feb 2002 23:30:57 -0800 Subject: import Random: NV_MAGICCONST deviates too much. Message-ID: <29575ad6.0202282330.16226275@posting.google.com> Hi all... I have get a strange exception when importing random. I brought it down to: Python 2.1.2 (#1, Jan 18 2002, 18:05:45) [GCC 2.95.4 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import gnome.ui >>> import random Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.1/random.py", line 93, in ? _verify('NV_MAGICCONST', 1.71552776992141) File "/usr/lib/python2.1/random.py", line 88, in _verify raise ValueError( ValueError: computed value for NV_MAGICCONST deviates too much (computed 2,82843, expected 1) >>> If I first import random and then gnome.ui I have no problems. my distr is debian woody with the standard python packages (not self-compiled) on an AMD-K6 Anybody know what's going on ? Cheers, Marijn. PS: Thanks to the #python crew for helping me out on this one! From rnd at onego.ru Sun Mar 3 07:16:47 2002 From: rnd at onego.ru (Roman Suzi) Date: Sun, 3 Mar 2002 15:16:47 +0300 (MSK) Subject: PEP 262 (database of installed Python packages) In-Reply-To: <3wgg8.685$Qo2.70120@news02.tsnz.net> Message-ID: On Sun, 3 Mar 2002, Andy Elvey wrote: >Hi all. >problematic ..... > Anyway - just thought I'd test the waters on this - is there anyone else >out there who'd love to see a single "search database"? ( Imagine - no more >fiddling with this path, or that path , blah blah .... ) Thanks for your >time, and for your comments ! It is an interestin idea to have a registry for Python modules. However, PEP262 is so full with XXXs and question marks that it is more of intention than recipe. What to do for example, if I have 3 versions of Python in my system? Will I have 3 INSTALLDBs or one shared between? Why not just use RPM to keep track of all files? RPM is not just for Linux RedHat,SuSe,Mandrake, but I recall some people use it for other systems. So, the intention of PEP 262 is to make RPM-like thingie for Python platform. On RPM-based system it is not needed. All the fucntionality is already present in rpm program. So, probably better idea is to enable Distutils use system-specific solutions. RPM on RedHat, DEB on Debian, whatever-it-is-(if-is) on MS Windows, etc. However, I am both hands pro CPAN for Python. Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Sunday, March 03, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "Why build a wall round a cemetery when no-one wants to get in?" _/ From robinjim at earthlink.net Tue Mar 26 07:46:13 2002 From: robinjim at earthlink.net (robin and jim) Date: Tue, 26 Mar 2002 12:46:13 GMT Subject: implementing a constant singleton Message-ID: Is this the way to implement a constant singleton class using Python 2.2 "new-style" classes? class Message(str): def __new__(this_class, specification): print 'Message.__new__ applied by %s' % str(this_class) return str.__new__(this_class, specification) def __init__(self, specification): print 'Message.__init__ applied by %s' % str(self) self.subject = specification[0] self.body = specification[1:] # additional Message class methods go here class Constant_Singleton_Message(Message): def __new__(this_class): it = this_class.__dict__.get('__it__') if it is not None: return it this_class.__it__ = it = Message.__new__(this_class, this_class.set_string()) return it ## def init(self): ## Message.__init__(self, self.set_string()) def __init__(self): Message.__init__(self, self.set_string()) def set_string(): return "I'm a constant singleton" set_string = staticmethod(set_string) ## end implementation-------------------------- I'm troubled by the fact that Message.__init__ is applied each time Constant_Singleton_Message is "created", but I see no way to avoid it. Thanks in advance for your feedback. From jimd at vega.starshine.org Sun Mar 3 00:07:35 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 3 Mar 2002 05:07:35 GMT Subject: Deitel and Deitel Book... References: <3C7D8DCA.119D52EC@earthlink.net> <899f842.0203010812.6151d817@posting.google.com> Message-ID: In article <899f842.0203010812.6151d817 at posting.google.com>, Anthony_Barker wrote: >"DeepBleu" wrote in message >> Deitel and Deitel book on Python? I personally would not touch it... ... >> You want books on Python: Buy Beazley, Lundh, Holden, Hammond, Greyson >> etc.... >> Leave Deitel alone! >> DeepBleu > I agree with you to a point. They don't seem passionate about ... > presentations are excellent, as is his dead tree book. Eckel's, "The > thinking in Python", is very good. ... I thought Eckel's TiPy and his "Thinking in Patterns (with Python)" had been merged. I didn't realize that either of them had been released in dead tree editions. (I've read parts of them online at his web site) Bruce Eckel's MindView, Inc: Thinking in Patterns with Java http://www.mindview.net/Books/TIPatterns/ Bruce Eckel's MindView, Inc: Thinking in Python http://www.mindview.net/Books/TIPython (Actually it seems, if I believe his web pages, that these are still developmental versions, and have not yet been set to print). > I would love to see books on Algorithms with Python (makes a perfect > fit), and more advanced topics such as threads and extending python. I would love to see a good book on "patterns" in Python. I'd like it to be a simple booklet listing each of the GoF patterns, with a couple of examples of each. It would be fine if it also covered some additional patterns or some controversies or alternatives to the classic GoF patterns (like the Alex Martelli's Borg vs. the GoF Singleton). Don't even ask for my opinion on Thomas W. Christopher's _Python_Programming_Patterns_ book (PTR/PH Prentice Hall, (c) 2002), it has almost nothing to do with OODP (one chapter with superficial coverage of 20 out of the GoF 23 patterns, and the example code is convoluted, opaque and mostly irrelevant to Patterns). (As a saving grace his chapters on threads and concurrency are somehwat better. I think my best bet so far is to study online at: Python Patterns http://www.thinkware.se/cgi-bin/thinki.cgi/PythonPatterns ... and this seems to be the rule for Python. The best material seems to be live and online. However, I still need something to take to the coffee shop or into the can with me (no I don't have a computer in *there* yet; and I haven't set up sitescooper to fetch Python stuff to my Palm/Visor, yet). I've been enjoying Steve Holden's book, though it is pretty basic and a little slow in places. I thought his approach to introducing OOP by starting with strawman procedural examples going through a "objects as data structures" phase and iteratively refactoring that into an OO design with constructors and other methods was interesting, though a bit repetitive in the written form. (It would make alot of sense in a lecture format, though). I also picked up Robert W. Bill's new Jython book from New Riders. Based on that, Holden's work and Beazeley's _Python_Essential_Reference_ I'd say that New Riders is kicking @$$ in the Python arena. Although I like most of the classic O'Reilly titles, I have to say that I'm a little disappointed in Fredrik Lundh's _Python_Standard_Library_ --- it's just too short and doesn't offer comparisons among related or similar modules. For example the coverage of the curses module consists of one sentence of running prose and one 14-line code example. That code example doesn't mention the curses.wrapper() function, doesn't show his code in a try: finally: block (which could leave the terminal in an unusable state if any exception is thrown) and doesn't show or even mention ncurses color (which is a common source of confusion in this NG). (Of course it might not be fair to pick on the curses coverage, which seems to be relegated and accursed in all Python documentation; but this is just one example). Meanwhile I thought both the Lutz books were tedious (though I haven't read the 2nd edition of Programming Python). Meanwhile the O'Reilly book on _Python_&_XML_ by Christopher A. Jones and Fred L. Drake, is very good. From donnal at donnal.net Sun Mar 3 17:35:04 2002 From: donnal at donnal.net (Donnal Walter) Date: 3 Mar 2002 14:35:04 -0800 Subject: pydoc and packages Message-ID: <918bc22f.0203031435.511bbf3c@posting.google.com> I have separated my application code into three packages: Lib.core, Lib.control, and Lib.model with four to twenty modules per package. Using pydoc -w I am able to generate HTML documentation for one module at a time, but is there a way to generate an integrated set of HTML documents for all the modules in all three packages (and the packages themselves) with one command? Thanks From ballabio at mac.com Thu Mar 7 13:08:48 2002 From: ballabio at mac.com (Luigi Ballabio) Date: Thu, 07 Mar 2002 18:08:48 +0000 Subject: SWIG and abstract base class In-Reply-To: Message-ID: <5.1.0.14.0.20020307180445.00a53530@mail.mac.com> At 08:01 AM 3/7/02 -0800, Helmut Zeisel wrote: >I want to use SWIG to create a Python module for >a C++ class hierarchy using abstract base classes: Helmut, I'm assuming that you're using a reasonably recent version of SWIG (let's say >= 1.3.9). If you actually tell SWIG that Base is abstract (e.g., if you declare purely abstract methods as such, with the = 0 at the end) it should not try to instantiate it. If you don't want to expose the purely abstract methods or the above doesn't work in some way, you should be able to inhibit instantiation by declaring Base to SWIG as: class Base { private: Base(); public: // whatever }; hope this helps, Luigi From roy at panix.com Mon Mar 11 07:41:56 2002 From: roy at panix.com (Roy Smith) Date: Mon, 11 Mar 2002 07:41:56 -0500 Subject: How to compute sunset and dawn times with python? References: <22722a23.0203080841.3ed7166a@posting.google.com> Message-ID: tist at subdimension.com (Tist Verdonck) wrote: > Does anyone know how to compute sunset and dawn times with python? For anything having to do with calculating astronomical data with a computer, the standard reference book is Jean Meeus's Astronomical Algorithms (http://www.willbell.com/math/mc1.htm). From jkraska at san.rr.com Wed Mar 13 19:57:26 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 14 Mar 2002 00:57:26 GMT Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: >Question: Which is better: items(x) or x.items()? Note the question in the PEP, but leave the decision to Guido. C// From jeff at ccvcorp.com Thu Mar 28 15:15:31 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 28 Mar 2002 12:15:31 -0800 Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> <37j6auohv35hg3kfol3m5hnrelvd4i4vdk@4ax.com> Message-ID: <3CA379E3.5604D622@ccvcorp.com> Dale Strickland-Clark wrote: > > Alternatively, capitalise Java-style: 'matchOn' or 'switchOn' Ugh. Please, no. I wince every time I see that horrid capitalization style. If *any* letters are capitalized, the first letter *must* be, also. (At least, in my mind... I realize that this is a matter of personal taste, but it's one that I feel *very* strongly about.) But since currently, all Python keywords are all lower-case, then we should maintain that tradition. I think that if we're going to add a keyword for this, that "switch" is a good choice. It's familiar to C/C++ programmers (at least), it's reasonably intuitive, and it avoids capitalization monstrosities. ;) It does risk breaking old code, of course, but then, *any* keyword change does that. I do prefer the re-use of "else" instead of adding "any", though. A lot. :) Jeff Shannon Technician/Programmer Credit International From ponderor at lycos.com Tue Mar 26 14:42:33 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 26 Mar 2002 13:42:33 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) Message-ID: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> QOTW: "A feature in isolation is a feature doomed to misuse." timbot "The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code -- not in reams of trivial code that bores the reader to death." Guido van Rossum Peter Hansen masterfully applies The Python Way of exception-handling and object orientation in a tidy little response on the os module. http://groups.google.com/groups?th=6e7fa04735bf0b52 Python plays a role in unraveling Balkan atrocities. http://www.wired.com/news/politics/0,1283,51106,00.html Kris Zaragoza and others explain how to make your own use of MS SQL Server with Python. http://groups.google.com/groups?th=efccf3faf8d7eb11 Python-bz2 "provides a comprehensive interface for the bz2 compression library." http://python-bz2.sourceforge.net/ ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning, ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From donn at u.washington.edu Fri Mar 15 13:19:33 2002 From: donn at u.washington.edu (Donn Cave) Date: 15 Mar 2002 18:19:33 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <15505.33265.747862.25428@12-248-41-177.client.attbi.com> <15506.10262.578727.665781@12-248-41-177.client.attbi.com> Message-ID: Quoth grante at visi.com (Grant Edwards): | In article , Rich Cook wrote: ... |> So do I have to read the data byte by byte using read(1) and |> examine each character to avoid blocking? Is there any way to |> find out how much data is actually waiting for me in the file |> object so I can read it in bigger increments, or must I call |> select then read(1) for every byte? | | You don't have to read it 1 byte at a time. Just call | f.read(1024) and it will give you however many bytes are | available, up to the max of 1024. You can use a max different | than 1024 if you want. I think you're making the problem worse here. import popen2 t = popen2.Popen3('echo L1; sleep 2; echo L2; sleep 2; echo L3') print 'First read: ', repr(t.fromchild.read(1024)) $ python /tmp/x First read: 'L1\nL2\nL3\n' C I/O basically sucks for this application. When you ask for 1024, fread is bound to get that amount, just as it is if you ask for a line via fgets ("readline".) If you omit the amount, you're asking for all the data, won't return until the socket's other end closes. If you read byte by byte, you won't know when to stop, because select doesn't look at stdio I/O buffers and after the first byte all the existing data was probably read up from the device, so select won't see anything there. Rich, I thought Grant identified your real problem (calling select wrong) in his first followup. I added some comments relevant to the above issues in other followups. Did you miss all that stuff? Donn Cave, donn at u.washington.edu From eric.brunel at pragmadev.com Thu Mar 14 09:56:33 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 14 Mar 2002 14:56:33 +0000 Subject: Tkinter BUG: memory loss for tag bindings in Canvas References: Message-ID: Hi again all, Considering my memory loss problem with tag bindings, I went a little deeper into the Tkinter module and found out what happened: whenever a binding is created, a new tcl command is created by the Tkinter/_tkinter modules. This command in fact just calls the Python function, but is required to do the binding at the tk level, which of course knowns nothing about Python. This is this command that cause the memory leak: when the graphical item is deleted or even when the binding is cancelled, the command is not destoyed in the tcl interpreter... So I tried to explicitely delete the complete binding by doing something like: ---------------------------- from Tkinter import * root = Tk() ## Create the canvas c = Canvas(root) c.pack() ## Create the item tId = c.create_text(100, 100, text='spam') ## Create the binding def foo(event): print 'bar' c.tag_bind(tId, '', foo) ## Get the binding f = c.tag_bind(tId, '') ## Print it for debugging purposes print f ## Explicitely remove the binding c.tag_unbind(tId, '', f) root.mainloop() --------------------------- This doesn't work, and here is the result: if {"[136128196foo %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D]" == "break"} break Traceback (most recent call last): File "tkCanvasBindings2.py", line 16, in ? c.tag_unbind(tId, '', f) File "/usr/local/lib/python2.1/lib-tk/Tkinter.py", line 1904, in tag_unbind self.deletecommand(funcid) File "/usr/local/lib/python2.1/lib-tk/Tkinter.py", line 297, in deletecommand self.tk.deletecommand(name) TclError: can't delete Tcl command The "if {...} ..." is the result of the print. If I understand correctly, the binding at the tk level is not made directly to the created command, but to this expression, allowing Python callbacks to stop executing the bindings by doing "return 'break'". But by doing so, the result of "c.tag_bind(tId, ''" is not the name of the created tcl command (which seems to be "136128196foo"), and so cannot be used in the tag_unbind method, which tries to delete the command, resulting in the traceback above. To me, this sounds like a bug, doesn't it? Any maintainers of Tkinter around here? TIA - eric - From skip at pobox.com Tue Mar 19 09:22:44 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 19 Mar 2002 08:22:44 -0600 Subject: socket.gethostbyname() AttributeError In-Reply-To: References: Message-ID: <15511.18868.287275.971963@12-248-41-177.client.attbi.com> ralph> I assumed that for scoket.gethostbyname(host), I was to pass a ralph> host of the type "theodore.chipmunks.com" and that I would get ralph> back an IP address as a doted quad. Obviously I am wrong about ralph> the form of the arguement I am to pass to the function, because I ralph> am getting an AttributeError message. Probably a typo on your part. Works for me: >>> import socket >>> socket.gethostbyname("www.yahoo.com") '64.58.76.222' -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From tim.one at comcast.net Tue Mar 12 23:56:56 2002 From: tim.one at comcast.net (Tim Peters) Date: Tue, 12 Mar 2002 23:56:56 -0500 Subject: Is there a good reason why we cannot (as of 2.1.1) deepcopy complex objects? In-Reply-To: Message-ID: [Carl Banks] > Subject: Is there a good reason why we cannot (as of 2.1.1) deepcopy > complex objects? I doubt it. Works fine in 2.2: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import copy >>> z = 1-1j >>> copy.copy(z) (1-1j) >>> copy.deepcopy(z) (1-1j) >>> The copy module got quite an overhaul for 2.2, and that likely fixed many odd old bugs. > Strangely, I've found no mention of this anywhere: the docs, the > Python FAQ, or the Google archives. The right place to look would have been the Python bug database on SourceForge, but I didn't find a specific bug report there either. That is mildly strange. It's not strange that the 2 people using complex numbers in Python didn't add a FAQ entry, though . From jbell at iinet.net.au Wed Mar 27 03:14:53 2002 From: jbell at iinet.net.au (John Bell) Date: Wed, 27 Mar 2002 16:14:53 +0800 Subject: Symbolic imports and manipulation of the namespace? References: Message-ID: <3CA17F7D.9020907@iinet.net.au> VanL wrote: > Hello, > > I was recently solving a problem which required that the config file > (just a python file) lie outside of the pythonpath. Is it possible to > do symbolic importation of a module? > > For example, I had: > > # cfgpath is passed in on the command line > cfgpath = os.path.basename(cfgpath) > sys.path.insert (0, cfgpath) > import sc_cfg #Hardcoded config module name! > > > How do you do this: > > # cfgpath is passed in on the command line > cfgpath, cfgfile = os.path.split(cfgpath) > sys.path.insert (0, cfgpath) > import cfgfile #Hardcoded config module name! > > So that any file name (ending with .py, of course, but that's another > matter) could be the configfile? > I tried the above, but I got an ImportError (no module named cfgfile) Basically it depends what you want to do with the file. If you simply want to execute it in-line (which given that it's a config file is most probably the case) then use execfile. This by default executes the file within the namespace of the caller, so is somewhat like an include or import statement in other languages. NOTE THE CAVEAT RE EXECUTION WITHIN A FUNCTION BODY. Check the manual page re manipulation of the namespace. If the file has classes you want to create or functions you want to call you should use __import__. The idea is to put your file (say myfile.py) in your search path. Then if you want to create an instance of myobject defined in myfile.py: modname='myfile' objname='myobject' _module=__import__(name) _class=getattr(_module,objname) _object=_class(instantiation parameters) where _object is the instance. Function invocation works in a parallel fashion. Once again, see the manual page re namespace manipulation. John > > Thanks, > > Van > > From h_schneider at marketmix.com Tue Mar 19 05:24:42 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Tue, 19 Mar 2002 11:24:42 +0100 Subject: Gadfly mirrors? References: Message-ID: Thanks for this valuable hint! For all others outside, the exact link is: ftp://ftp.debian.org/debian-archive/dists/slink/main/binary-i386/interpreter s/ One prob left: How do you unpack a *.deb file ? All the best, Harald "Konrad Anton" schrieb im Newsbeitrag news:slrna979jf.dp.usenet at fohnhab.minus1.de... > matt at swordfish.havenrock.com schrieb: > >Hi, folks-- > > > >Does anyone know of an alternate download site for Gadfly? I have been > >unable to reach www.chordate.com all evening. > > It is also in a Debian package called "gadfly" in section > "interpreters", available from ftp.Debian.org mirrors. > > HTH > Konrad. > > -- > Konrad Anton ; Web: www.minus1.de ; gpg: 0x22954D8A > Tel. +49-761-881-2122, Fax +49-721-151318943. Alice: > It's generally why? From jessw at loop.com Wed Mar 6 23:47:07 2002 From: jessw at loop.com (Jesse W) Date: Wed, 6 Mar 2002 20:47:07 -0800 Subject: Status of PEP's? Message-ID: <3C86804B.21161.A65A21@localhost> The reason I don't like PEP 276 It is too broad. The Rationale in PEP 276 assumes that the iterator for ints would only be used as a shorthand for the indexed list idiom; but in fact, making an iterator for ints allows many other possibliites, many of which(see below), are errors or confusing. I don't disagree with trying to simplify the indexed list idiom, but not if the solution allows in such a lot of odd looking posiblities as shown below. The ugly posibiliites: for i in 5: print i*2, #Would print: 8 6 4 2 0 #Why? What posible sense would this make? var=-2 for i in var: print i #Would generate an error of some kind because var is negative. #What a sneaky and hard to understand bug! The loop will not #execute because some variable(which could be defined far away, #and in some complicated fashion) is negitive. Huh? A more clear #example: while var < 10: var=(var-2)*3 for i in var: print i #If var is defined as 0, 1 or 2 then you get an error; else, it runs. #Huh? #Or, look at this: def foo(var): var=int(var) var=var*5 var=var/3 var+= 12.3 for i in var*2: print i #Will this generate an error? #Yes, because on the line that begins var+=, var is changed into a #float, which will make the loop choke. Is this something anyone is #likely to notice? I am sure that others can think of more unpleasent posibilities. The basic problem is that the proposal is simply too broad. Jesse Weinstein From gimbo at ftech.net Wed Mar 6 09:18:16 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 6 Mar 2002 14:18:16 +0000 Subject: Tkinter: can widgets automatically resize to fit parent? Message-ID: <20020306141816.GC10985@andy.tynant.ftech.net> Howdy, Hopefully a quickie, although I've got a bad feeling that it'll be a quickie because the answer is "no, you can't do that". Anyway: I want my Tk widgets (some of them, at least) to resize dynamically with the window. Trivial example: #!/usr/bin/env python from Tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.action = Button(self.master, text="Go") self.action.grid(sticky=N+E+W+S) def main(): root = Tk() app = Application(root) root.mainloop() if __name__ == '__main__': main() I want the button to resize with the window. I was hoping the call to grid() would do it, but alas no: the button just sits there in the middle of the window. Worse, I can't see anything in the docs about how to do it (unless I'm being blind/stupid). If I can't do this, it's back to Qt... :-( Thanks in advance, Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From Oschler at earthlink.net Sun Mar 31 19:50:05 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 31 Mar 2002 19:50:05 -0500 Subject: Python quick setup URL for Linux setup? References: Message-ID: Aahz, Yep, says I've got 2.1.1. But is there an equivalent to PythonWin on Linux? I'm GUI spoiled :) thx Aahz wrote in message news:a886l2$t17$1 at panix1.panix.com... > > > First of all, you should already have Python installed on your system > (although an older version). What happens if you just type "python"? > From lbut at stny.rr.com Mon Mar 18 16:36:56 2002 From: lbut at stny.rr.com (Les Button) Date: Mon, 18 Mar 2002 21:36:56 GMT Subject: Problem using pexports & Cygwin to build Python 2.2 extension modules References: Message-ID: "Anton Vredegoor" wrote in message news:a74hef$ejq$1 at news.hccnet.nl... > try: > setup.py build --compiler=mingw32 > Works great! (and doesn't have problem with undefined SIZEOF_INT etc). Thanks very much indeed, --Les Button From klaatu at evertek.net Sun Mar 17 15:58:54 2002 From: klaatu at evertek.net (Mike Dean) Date: Sun, 17 Mar 2002 14:58:54 -0600 Subject: syntax question: "<>" and "!=" operators In-Reply-To: ; from mertz@gnosis.cx on Sun, Mar 17, 2002 at 03:08:08PM -0500 References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: <20020317145854.B2468@evertek.net> * David Mertz, Ph.D. [2002-17-03 15:08]: > Nonetheless, I think of the natural language semantics of the > symbols--or maybe better "insinuations"--prefers '<>' to '!='. The > (good) one suggests "is greater than or less than (but not equal to)". > I know that not everything is technically in an order relation, but it > still "makes sense" at a first approximation. The (bad) one looks like > some odd sort of augmented assignment. "Hmmm... assign, what? The > negation of the right side to the left side?! The LHS negated with the > RHS?!" One thing that's always baffled me on this issue (along these lines) - why does Python have != as a not-equal operator, when ! is not the not operator? -Michael -- The generation of random numbers is too import to be left to chance -- OpenBSD Fortune database From tdelaney at avaya.com Sun Mar 3 18:30:49 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 4 Mar 2002 10:30:49 +1100 Subject: experimental patch to allow importing from file-like objects Message-ID: > From: gerson.kurz at t-online.de [mailto:gerson.kurz at t-online.de] > > # redirect import hook ****************************** > old_import_func = __import__ > > def my_import_func(name, globals=None, locals=None, fromlist=None): > global old_import_func > > if name == "encrypted_test": > return imp.load_module(name, > my_file_class("test.raw"), > "test.raw", > ('.raw','rb',imp.PY_FILEOBJECT_SOURCE)) > > > # use original code > return old_import_func( name, globals, locals, fromlist ) > > __builtins__.__import__ = my_import_func One thing you may like to do (but don't hurry) # redirect import hook ****************************** def my_import_func(name, globals=None, locals=None, fromlist=None, old_import_func=__import__): if name == "encrypted_test": which has three advantages and one disadvantage: A1: avoids polluting your namespace A2: prevents other code from rebinding old_import_func A3: old_import_func will exist in the locals of the function, leading to faster lookup D1: It is possible (but highly unlikely) that someone could call your function (either directly or indirectly via __builtins__.__import__) with the wrong arguments. Tim Delaney From wayne at mishre.com Fri Mar 1 21:52:42 2002 From: wayne at mishre.com (Wayne Pierce) Date: Fri, 01 Mar 2002 18:52:42 -0800 Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: <3C803E7A.6000200@mishre.com> Mats Wichmann wrote: > Note: this is not a Python question per se. > > I'm looking for a piece of software to aid in reviewing a document > through the web - click on a paragraph tag, have the comment added > (highlighted in some way). The wiki style doesn't seem to quite do it, > as the core document is not protected. I haven't found much in web > searches, and nothing where the software seems to be free. If Wiki allowed for password protection would it fit your requirements? I run a Wiki on Zope (ZWiki), which allows for password protection. You could also use Apache and setup the httpd.conf file to require authentication when someone accessed that part of the site. Something like Zope's CMF Workflow[2] might also be a good fit....then there's OpenFlow[3] (also running on Zope :). > I'd of course love it if this were done through Python since I'm on a > bit of an advocacy kick...but in the end it doesn't matter much. > Anybody know if anything like this is happening in any of the web > services projects? I don't know if these __exactly__ match what you are looking for, but hopefully they will get you started. [1] http://www.zwiki.org/FrontPage [2] http://cmf.zope.org/design/design/interfaces/tools/IF_portal_workflow [3] http://openflow.sourceforge.net/ -- Wayne Pierce web: http://www.mishre.com email: wayne at mishre.com "What you need to know." From loewis at informatik.hu-berlin.de Mon Mar 4 07:35:23 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 04 Mar 2002 13:35:23 +0100 Subject: File Attributes conversion References: <2030665d.0203040431.1279d1ab@posting.google.com> Message-ID: sam_collett at lycos.co.uk (Sam Collett) writes: > e.g. > File Size to display in bytes (if < 3kb), kilobytes (if < 2MB) and > megabytes (> 2MB). How would you do that (the value I get is 12345L - > what is the L?) It indicates that that Python value was a 'long' integer (one that can exceed 4GB); you best format format these with %d > Modified/Created time to be displayed as GMT (DD mm YYYY, HH MM am/pm) > 14/09/2002, 5:54pm (is it in seconds currently [starting from which > year]?) You can use time.strftime for that. > I am doing this on Windows 98SE, is it possible to get the code to > work cross platform as well? As long as it is file sizes and time stamps, yes, certainly. > PS Can you also get other attributes (read-only, hidden, compressed, > system, archive, etc)? I think you need to use the Win32 extensions for these, since they are Microsoft-specific. Regards, Martin From anthony_barker at hotmail.com Fri Mar 1 10:54:47 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 1 Mar 2002 07:54:47 -0800 Subject: proxy authentication: how to hide password References: <9ff6b66.0201250109.1c68a130@posting.google.com> <899f842.0202120818.11412d4b@posting.google.com> <9ff6b66.0202270901.3837af8b@posting.google.com> Message-ID: <899f842.0203010754.33ab63f2@posting.google.com> vtail - what about prompting the first time a script is run? store the password to a text file (or in the registry) and encrypt it. Anthony > I _feel_ bad - Perl didn't ask me any password when I run similar > script. Neither did I defined any environment variables. > > > prompt for the password if need be. > > That's so painful to enter your login&password every time the script > is running... ;-( Perl uses http_proxy env variable. > > Anyway, thanks for you ideas. > > Vtail From boud at valdyas.org Sun Mar 24 17:14:44 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Sun, 24 Mar 2002 21:14:44 -0100 Subject: Stopping threads from the outside References: <3C9E173A.88BBDBB4@engcorp.com> <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> <3C9E2D31.E45278BC@engcorp.com> Message-ID: <3c9e33bc$0$24825$e4fe514c@dreader3.news.xs4all.nl> Peter Hansen wrote: > > I'm curious what the agent actually does if it doesn't share > anything. Does it not take input? And produce output? > No opening files, accessing Queues and such? If it does > any of those things, wouldn't that make it potentially a > problem if you killed it? > Sending and receiving messages -- messages which are, very carefully, _not_ shared objects. > I realize it may be only a theoretical problem in some specific > applications, since one might be able to guarantee that one will > not attempt to kill a thread when it is in a particular subroutine > and therefore unsafe. It might be nice to have the option, if > one really wanted, especially if there are simple conditions > under which one could guarantee a thread is safe to kill (not > blocking and without shared resources locked). > It would be _very_ nice. -- Boudewijn Rempt | http://www.valdyas.org From emile at fenx.com Fri Mar 22 15:45:30 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 22 Mar 2002 12:45:30 -0800 Subject: a website information gathering script References: <3C9B33FA.3D853D65@lmco.com> Message-ID: Scott Hathaway > I have a simple python script which gathers information about a website > and produces an html report about what it finds. The way it works is > very clunky and I would appreciate some feedback and help improving it. ---------- if (file.endswith('html')==1) or (file.endswith('htm')==1) or (file.endswith('asp')==1) or (file.endswith('php')==1) or (file.endswith('js')==1) or (file.endswith('vbs')==1) or (file.endswith('inc')==1) or (file.endswith('css')==1) : checkedFiles.append(file) Why not: if file.split('.')[-1] in ('html','htm','asp','php','js','vbs','inc','css'): checkedFiles.append(file) ---------- Concatenating strings is expensive so you might eliminate it, changing to lists: a = "\n" a += " \n" a += "" + str(len(unReferencedFiles)) + "\n" to: a.extend(["" ,str(len(referencedFiles)),"\n"]) although I'm not sure if that would be preferred over: a.append("%s\n" % str(len(referencedFiles))) finally, do the string conversion something like: html = str(a) + str(b) becomes: html = ''.join(a+b) ---------- You really, really want this to work, don't you? ;-) try: fc = open(cFile,'r').read() except: fc = open(cFile,'r').read() ---------- I'm not real strong on regular expressions so check my code, but it seems to me that the code that sets found could be something like: (posting this is a good way to entice someone who knows into cleaning it up... ;-) ) >>> for afile in allFiles: ... if re.search('''['"\\/]'''+'file', afile): found = 1 ... HTH, Emile van Sebille emile at fenx.com --------- From thomas at weholt.org Mon Mar 18 14:53:28 2002 From: thomas at weholt.org (Thomas Weholt) Date: Mon, 18 Mar 2002 19:53:28 GMT Subject: Format profile-data into "nice" HTML ? References: <0S9l8.11822$TU3.312633@news4.ulv.nextra.no> Message-ID: Posting a notice to let the group know of my very early and very simple attempt at html-formatting on output from the profile/pstats-module. The module is available at http://home.online.no/~t-weh/releases/hspstats.py and a preview of the output is available here http://home.online.no/~t-weh/releases/prf.html Please let me benefit from comments and improvements ( there are room for plenty :-) ) by sending me a mail etc. Best regards, Thomas Weholt From jamie.carl at salientnetworks.com.au Thu Mar 21 23:53:23 2002 From: jamie.carl at salientnetworks.com.au (Jamie Carl) Date: Fri, 22 Mar 2002 04:53:23 GMT Subject: Execute external program References: <3c9a7d0e_1@news.iprimus.com.au> Message-ID: <3c9ab8a8_1@news.iprimus.com.au> brilliant! Knew it'd be easy. J "Emile van Sebille" wrote in message news:a7e3c1$kldi4$1 at ID-11957.news.dfncis.de... > > "Jamie Carl" wrote in message > news:3c9a7d0e_1 at news.iprimus.com.au... > > Hopefully this is a simple question. How can I get python to execute > an > > external program such as 'bash' or whatever? > > Is there a line of code that will do this. No interface with STDIO > needed > > so i can run blind. > > > > C:\>python > ActivePython 2.1, build 210 ActiveState) > based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> os.system('dir') > Volume in drive C is DISK2PART01 > Volume Serial Number is 36C1-7E27 > > You should also look into spawn and pipe variants. > > HTH, > > -- > > Emile van Sebille > emile at fenx.com > > --------- > From James_Althoff at i2.com Mon Mar 4 20:27:36 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 17:27:36 -0800 Subject: Status of PEP's? Message-ID: [David Eppstein] > The proposal is to extend it to > also include three-way comparisons. And, I assume, you mean three-way comparisons that are restricted to using certain combinations of "< <= > =>"? Since, for example, this kind of 3-way wouldn't work in a for-loop with this proposal: >>> i = 5 >>> 0 < i != 10 1 >>> Jim From martinkaufmann at yahoo.com Tue Mar 12 17:32:01 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Wed, 13 Mar 2002 11:32:01 +1300 Subject: Question about scientific calculations in Python References: Message-ID: On 12 Mar 2002 19:25:50 GMT, Paul Hughett wrote: >You might want to take a look at bblimage, which is an extension to >Python written in C; it emphasizes high performance, but the set of >operations implemented so far is oriented toward medical image >processing. It supports pretty much all the basic operations (+,-, ... >sin, cos, exp, etc) on n-dimensional images in the usual integral and >floating point types (but not complex, alas; I haven't starting playing >with FFTs yet). The URL is > > http://www.uphs.upenn.edu/bbl/bblimage Thanks, I had a look at the webpage. It really looks interesting to me. But the basic calculations really faster than the one in SciPy or Scientific Python? >It really depends on how many diffraction patterns you need to do. It >doesn't make sense to spent two months learning C to save even 99% of >a ten-hour computation that you're going to do only once. (Unless >your real purpose is to learn C.) On the other hand. if you have to >do a few hundred patterns, then it might be a good investment of time. I will have to do it several times I guess... So 99% improvement in speed would really be nice. >For what it's worth, my own experience is that (b) using C for the >heavy lifting and Python to glue the pieces together can be very >effective if you implement the right piece in the right language. I'm >using bblimage for registration and segmentation of hundreds of volume >images at half an hour apiece. The current code runs almost as fast >as plain C (about 4 times faster than a competing C++ implementation >not particularly optimized for speed) but the Python code that glues >it all together is easier to modify and experiment with than a C++ >implementation would be. How do you glue C and Python together? Do you use any of the wrappers (SWIG, weave etc.) or do you do it the hard way? I just didn't understand the whole story about these PyObjects. >One general comment: The performance killer in many applications like >this is doing the innermost loop in the interpreted language (Python, >Matlab, etc). If you can recast your algorithm as operations on >arrays rather than individual numbers, and your language does the >implicit loops over the elements efficiently, you typically get 10x or >so improvements in speed. Do you mean the array calculation of NumPy? Thanks, Martin From aahz at pythoncraft.com Sun Mar 31 15:41:16 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 15:41:16 -0500 Subject: New-style exceptions? References: Message-ID: In article , Magnus Lie Hetland wrote: > >Is there a reason why new-style objects can't be used in the raise >statement? Because that's the way it currently works. Inherit from Exception and Bob's your uncle. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From James_Althoff at i2.com Wed Mar 27 19:29:45 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 27 Mar 2002 16:29:45 -0800 Subject: list comprehension question Message-ID: [Tim Peters] > No. len([f(x) for x in y]) == len(y) whenever no exception occurs, > regardless of the form of f() or type of y. >>> >>> class Y: ... def __iter__(self): ... return iter(xrange(5)) ... def __len__(self): ... return 10 ... >>> def f(x): return x ... >>> y = Y() >>> >>> len([f(x) for x in y]) == len(y) 0 >>> Jim From jon+usenet at unequivocal.co.uk Mon Mar 4 10:50:45 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Mon, 04 Mar 2002 15:50:45 -0000 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: In article , Tim Peters wrote: > For the rest of it, it looks like the "1e-200**2 raises OverflowError" > glitch is unique to platforms using glibc. No, it happens on OpenBSD 2.7 also. Python 2.2 (#2, Feb 3 2002, 18:27:17) [GCC 2.95.2 19991024 (release)] on openbsd2 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Result too large') From peter at engcorp.com Fri Mar 29 13:29:49 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 13:29:49 -0500 Subject: Anyone need a program written? References: Message-ID: <3CA4B29D.DDDEA281@engcorp.com> rasmussn at lanl.gov wrote: > > On Friday, March 29, 2002, at 10:46 AM, phil hunt wrote: > > >> "Fused" wrote in > >> message news:3ca43ef4.3666136 at news.tudelft.nl... > >>> I'm currently trying to master Python, but to succeed I need to > >>> exercise. However, I detest building programs that have already been > >>> built a kazillion times and aren't of use to anyone. > >>> Can anyone think of a program that I could build that would actually > >>> have use to someone (you?)? I'm trained in Delphi, know some Java and > >>> rudimentary C, so the programs don't need to be newbie-easy ( I like a > >>> challenge: the greater the challenge, the faster I'll learn ;-) ). > > How about a Python substitute for make. Waste of time to compete with http://scons.sourceforge.net/ right now... From wayne at mishre.com Fri Mar 8 15:00:02 2002 From: wayne at mishre.com (Wayne Pierce) Date: Fri, 08 Mar 2002 12:00:02 -0800 Subject: ANN: Python User Groups page at python.org References: <2AWh8.478$eT3.149538@news.uswest.net> <3C883D30.1030905@attbi.com> Message-ID: <3C891842.6080307@mishre.com> Sheila King wrote: > On Fri, 08 Mar 2002 04:17:55 GMT, Pete Shinners > wrote in comp.lang.python in article <3C883D30.1030905 at attbi.com>: > > >>Kevin Altis wrote: >> >>>Python User Groups now have their own page on the Python web site: >>> >>>http://www.python.org/UserGroups.html >>> >>sadly nothing ever in the southern california area. anyone in OC or LA >>who enjoys this crazy python? >> > > Me. Actually, about 6 months ago or so, someone was going to start up one > (like at UCI) and went so far as to set up a time and place and got a few > responses, but then it fell through somehow. > > I don't really have the time or facilities to be an organizer, so I laid > low when it fell apart. But if someone else organizes it, I will come. > (Assuming I can make my schedule work, of course.) > > I'm in the Pomona/Chino/Brea area. I'm at Pendleton for the next few months, depending on the schedule I may be able to attend. I don't want to take on starting anything since I'll only be out here for about another 5 months or so. -- Wayne Pierce web: http://www.mishre.com email: wayne at mishre.com "What you need to know." From weeks at vitus.scs.agilent.com Sat Mar 30 09:49:01 2002 From: weeks at vitus.scs.agilent.com (Greg Weeks) Date: Sat, 30 Mar 2002 14:49:01 +0000 (UTC) Subject: PEP 285: Adding a bool type References: Message-ID: <1017508741.607098@cswreg.cos.agilent.com> Guido van Rossum (guido at python.org) wrote: : I offer the following PEP for review by the community. If it receives : a favorable response, it will be implemented in Python 2.3. Having read this note (and nothing else on the subject), I vote "no". I would, though, be happy to see built-in variables bound to 0 and 1. Here is the argument that I find most compelling. The annoyance of seeing >>> true 1 is more than offset by the value of being reminded that Python, unlike Java, attributes truth and falsity to objects that are not explicitly boolean. Greg From tim-dated-1016242653.c3a0c9 at catseye.net Fri Mar 8 20:37:32 2002 From: tim-dated-1016242653.c3a0c9 at catseye.net (Tim Legant) Date: 08 Mar 2002 19:37:32 -0600 Subject: PEP 284, Integer for-loops In-Reply-To: References: Message-ID: <86lmd2bjxf.fsf@skitty.catseye.net> James_Althoff at i2.com writes: [...] > I just did the same for a small section of our code. My quick little scan > turned up 293 uses of [x]range. Most -- as in nearly all -- of them are in > for-loops and *are* used in conjunction with the indices of collections. > > Our mileage might be different from others because our use of Jython is for > large-scale, shipping, production-level, commercial applications rather > than for small, throw-away scripts or core-language libraries. Also (as > mentioned) we use Jython and have to deal with tables and other kinds of > collections written in Java outside the scope of core C-Python. So I guess > we lose. Out of curiosity I ran a couple of quick greps over the TMDA source. TMDA doesn't really fall into either of your "alternative" categories; it's small, but definitely not throwaway and it's an application, not a core library. It's a mail processor to eliminate SPAM. However, it's pure Python; there's no integration with C or Java. The results were that I found 52 or 53 'for' loops (scanned the results of the grep by eye, since the word 'for' appears in comments as well) and exactly no uses of [x]range at all. So either Jason and I are significantly better than you and your team at expressing ourselves naturally in Python or it's the need to interface with Java that's forcing you to use integer indices all the time. I'm betting big money on the latter. Tim From rjones at ekit-inc.com Sun Mar 31 17:14:00 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Mon, 1 Apr 2002 09:14:00 +1100 Subject: Call for kjBuckets.c [was Re: relational database?] In-Reply-To: <3CA7192C.E1C8974A@engcorp.com> References: <5yEp8.5051$hi7.18667@news-server.bigpond.net.au> <3CA7192C.E1C8974A@engcorp.com> Message-ID: <200203312214.WAA03905@crown.off.ekorp.com> On Mon, 1 Apr 2002 00:11, you wrote: > Trung Hoang wrote: > > "Martin v. Loewis" wrote in message > > news:m3eli1m2dt.fsf at mira.informatik.hu-berlin.de... > > > > > "Trung Hoang" writes: > > > > What relational database is easy to setup and use with python? > > > > > > Gadfly. It is a pure-Python database, and requires little > > > administrative interaction. It does not provide good performance, > > > though... > > > > where can i get this ? > > Try Google? Actually, that's not going to help much - last I looked www.chordate.com wasn't answering its calls. I'm currently in the process of repackaging gadfly, including the updated code from the Zope version (regex->re conversion mostly). There'll be the usual sort of announcement when I'm done. Does anyone have a copy of kjbuckets.c that they could send me? Richard From brian at sweetapp.com Fri Mar 29 12:59:38 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 29 Mar 2002 09:59:38 -0800 Subject: Anyone need a program written? In-Reply-To: Message-ID: <002e01c1d74b$7f1842e0$445d4540@Dell2> Craig wrote: > How about a Python substitute for make. Trent Mick was working on something like this a billion years ago. Here is the sourceforge project url: http://sourceforge.net/projects/black From inigoserna at terra.es Mon Mar 4 07:43:14 2002 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: 04 Mar 2002 13:43:14 +0100 Subject: Useful, robust shell utilities In-Reply-To: <%8Wf8.518$Az6.2357@news.hananet.net> References: <%8Wf8.518$Az6.2357@news.hananet.net> Message-ID: <1015245795.1614.42.camel@lethe.infernus.org> Hello all, El s?b, 02-03-2002 a las 02:57, Jonathan Gardner escribi?: > Donn Cave scribbled with his keyboard: > > > Quoth Jonathan Gardner : > > | I tried to use the shutil module... and to tell you the truth, it > > | stinks. Is there an effort to make a robust, useful shutil module that > > | has the equivalent of the unix shell utilities? [...] > It was just that the copytree function has this little comment: > > The source code for this should be considered an example rather than a tool. > > And it also won't copy to a directory that already exists... this is very > different than what 'cp' does. > > > | I think it would be nice to make things like 'grep' even... > > | > > | Here is my wish list. Each of these should implement a significant > > | portion of what the GNU utils do. They should be robust, and give > > | reasonable results, and reasonable exceptions. > > | > > | touch, chmod, chown, chgrp, touch > > | df, du > > | cp, dd, install, mv, rm, shred in a program I'm developing (lfm, a mc clone (*)), I've had to write my own functions/wrappers to many of these functions. Though it's not hard to develop them for a concrete platform (posix OS) I think they are not easily extensible to other platforms such as windows or Mac. Finally, after thinking (and coding, and erasing, and coding) and thinking, I chose a mix of os module functions, my own functions and os.system() calls. I think this is the best solution. Moreover, a shutil2 module wouldn't be exactly what you need, so you'll have to modify/extend some functions to adequate to your needs always. In most cases, my own functions are just wrappers that take data from the curses ui which format properly to pass to os module functions. Regards, I?igo (*) http://www.terra.es/personal7/inigoserna/lfm NOTE: in a few days I'll release a new version of lfm. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 240 bytes Desc: This is a digitally signed message part URL: From gtalvola at nameconnector.com Thu Mar 21 18:54:57 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Thu, 21 Mar 2002 18:54:57 -0500 Subject: Why do Windows sockets break after exactly 4 minutes? Message-ID: I've noticed that Windows sockets seem to close all by themselves if there is no activity for 4 minutes. Does anyone know why? Is it possible to control this behavior? Just a link to some documentation of this behavior would be greatly appreciated. I don't think the same thing happens on Linux, or maybe it does but the timeout is longer than 4 minutes there. I've attached a set of 2 test scripts that provoke the behavior. Start up server.py first, then client.py, then wait 4 minutes. - Geoff -------------- next part -------------- A non-text attachment was scrubbed... Name: client.py Type: application/octet-stream Size: 507 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: server.py Type: application/octet-stream Size: 563 bytes Desc: not available URL: From andrewm at object-craft.com.au Thu Mar 21 19:37:38 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Fri, 22 Mar 2002 11:37:38 +1100 Subject: Python embedded like PHP In-Reply-To: Your message of "21 Mar 2002 18:17:38 MDT." <1016756258.554.46.camel@localhost> Message-ID: <20020322003738.A273C38F4C@coffee.object-craft.com.au> >> The intention is that Albatross templates be valid XML - while Albatross >> will do the expected thing in the example you give above, it generally >> provides a "better" way, such as: >> >> > >Do you mean that you have a template tag for every kind of tag for which >you would want to modify an attribute? That's every single HTML tag -- >IMG is hardly the only one. A dynamic CSS class attribute, for >instance, or events (onMouseOver, etc), id tags, background colors... >there's a million possibilities. No, we don't, although we're considering some options (such as abusing the XML namespace - for example: - thoughts? -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From max at alcyone.com Fri Mar 1 12:10:43 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 01 Mar 2002 09:10:43 -0800 Subject: Python's Syntax References: Message-ID: <3C7FB613.BA4B2A7A@alcyone.com> David Russell wrote: > I've had a look at a couple of tutorials for Python and it appears > like > this: > > if condition == TRUE: > do this > > How do you tell it when to stop? I just can't figure out how to do it. > Could > somebody explain it to me please, even though I have a strange > suspicious > that it is one of the simplest deatils imaginable. That's an if statement, there's no "stopping" involved; it simply tests the condition and then executes the "then" clause if it evaluates to true. You probably meant somethinng like a while loop: while condition: statements this continues to execute the statements while condition evaluates to true. It's precisely the same as C's while (condition) { statements } > Also, another thing about Python's syntax. Are statements just > sperated by > their lines, or do they have some form of seperator (like a > semi-colon)? You can use semicolons to separate multiple statements on the same line: x = 1; print x -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Laws are silent in time of war. \__/ Cicero Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ An Esperanto reference for English speakers. From James_Althoff at i2.com Fri Mar 1 15:16:21 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Fri, 1 Mar 2002 12:16:21 -0800 Subject: PEP 276 (was Re: Status of PEP's?) Message-ID: [James_Althoff] > (On the other hand, if anyone knows *how* to "lure" any of > them, be sure to let me know ). [Tim Peters] > Well, I'm particularly swayed by posters who have a "" key > and know how to use it. Still, my take remains what it was at the > start: it isn't even half as disgusting as most people will say it > is . Ah, very good. It's certainly encouraging to see that the ratio hasn't yet exceeded that crucial "49.999% disgusting" level . (Assuming decimal arithmetic on a calculator for this one). Jim From tim.one at comcast.net Fri Mar 22 16:39:52 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 22 Mar 2002 16:39:52 -0500 Subject: Customisation of comparison operators In-Reply-To: Message-ID: [Dave Haynes] > Which of __lt__, __le__, __eq__, __ne__, __gt__, __ge__ are used when > sorting lists of objects with .sort()? Only __lt__, provided it's defined. > Which of them is used for the 'in' and 'not in' comparisons? Impossible to say unless you first tell me the types of all objects involved. If you're talking about builtin lists, only __eq__, provided it's defined. The meaning of 'x in y' is, in general, determined by y's __contains__ implementation (provided it's defined). > Is __cmp__ no longer used at all if the above are defined? Impossible to say unless etc . > This might be dodgy practice, but I have some objects for which I > want to provide subtly different behaviour for the comparison > operators than for testing 'in' and 'not in'... Yup, that's dodgy all right. From netlangau at yahoo.com.au Wed Mar 13 20:44:26 2002 From: netlangau at yahoo.com.au (Patrick) Date: Thu, 14 Mar 2002 12:44:26 +1100 Subject: Has Mark Hammond attained pariah status yet? References: <3C8E7E90.6000608@skippinet.com.au> Message-ID: "Mark Hammond" wrote in message news:3C8E7E90.6000608 at skippinet.com.au... > [...] The book I am working on now is *not* Python for .NET, > but just .NET. Python doesn't get much of a mention :( Mark, out of curiosity: how did you conclude that the Python community is not interested in .NET compatibility? Was it based on the lack of contributions to your trial implementation? Or was it a perception that Python *users* are not interested? From scarblac at pino.selwerd.nl Thu Mar 21 08:27:41 2002 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 21 Mar 2002 13:27:41 GMT Subject: #define equivalents and config files References: <3C9963BD.1040304@verizon.net> <3C9964FF.46805590@engcorp.com> Message-ID: Dave Swegen wrote in comp.lang.python: > I'm basically after a single file where such values can be stored, and > then used in various parts of the program without having to pass extra > configuation variables around. How about just putting them in a module? Have a file constants.py that just reads name = "My Program" pi = 3.1415926536 Then you can import constants and use constants.name, constants.pi, etc. You can even "from constants import *" to directly put them in another module as variables. -- Remco Gerlich From sorpippo at libero.it Thu Mar 21 15:07:22 2002 From: sorpippo at libero.it (Giuseppe Ricioppo) Date: Thu, 21 Mar 2002 21:07:22 +0100 Subject: Painful apache compilation Message-ID: Hi folks!!! I am attempting to compile apache+mod_perl+php+mod_python. When I run make the result is... ##################### ......snipped for brevity..... ........................................... /usr/src/Python-2.2/libpython2.2.a(thread.o): In function `PyThread_start_new_thread': /usr/src/Python-2.2/Python/thread_pthread.h:174: undefined reference to `pthread_sigmask' /usr/src/Python-2.2/Python/thread_pthread.h:176: undefined reference to `pthread_create' /usr/src/Python-2.2/Python/thread_pthread.h:201: undefined reference to `pthread_sigmask' /usr/src/Python-2.2/Python/thread_pthread.h:210: undefined reference to `pthread_detach' collect2: ld returned 1 exit status make[2]: *** [target_static] Error 1 make[2]: Leaving directory `/usr/src/apache_1.3.22/src' make[1]: *** [build-std] Error 2 make[1]: Leaving directory `/usr/src/apache_1.3.22' make: *** [build] Error 2 ########################### Wow!!! But... What does it mean? How can I solve the problem? Thanks a lot. Giuseppe Ricioppo. From scarblac at pino.selwerd.nl Sun Mar 3 07:50:24 2002 From: scarblac at pino.selwerd.nl (Remco Gerlich) Date: 3 Mar 2002 12:50:24 GMT Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: Cromwell, Jeremy wrote in comp.lang.python: > If python was to allow "for i in 5:", is there any other meaning that would > be appropriate besides the one detailed in PEP 276? Yes. It should give an error - 5 is not a sequence, so 'i in 5' is nonsense. If you really want to change that, making it equivalent to for i in [5]: seems the most natural meaning to me. For iterating over the values 0..4, we have the nicely explicit and Pythonic for i in range(5):. I haven't seen one very good reason why we need a second way to do that - saving a few characters surely isn't enough. -- Remco Gerlich From mail at andreas-penzel.de Tue Mar 12 05:11:26 2002 From: mail at andreas-penzel.de (Andreas Penzel) Date: Tue, 12 Mar 2002 11:11:26 +0100 Subject: IDv2/IDv3 Tag on mp3-files Message-ID: Hello NG! Is it possible, to read the IDv2 or IDv3 Tag from mp3-files? Thanks, Andreas From jason at jorendorff.com Mon Mar 11 03:39:53 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 11 Mar 2002 02:39:53 -0600 Subject: Python daemon instead of CGI programs In-Reply-To: <88bc63c6.0203061444.30ad9c44@posting.google.com> Message-ID: Doug Farrell wrote: > I work for a company that develops big content web sites using > CGI's built with C++ as the primary programming model. [...] > I'm of the opinion this is akin to killing a fly with a sledgehammer > and am thinkin of some other mechanism. It's more like killing a fly with a steamroller that you built yourself from parts. > What do you think of this idea? Am I completely off base and missing > some other obvious solution? Does iPlanet support servlets? With Jython, you can write servlets in Python. The Servlet API is a bit different from CGI, but it's generally a *good* difference. Plus, this works to decrease your dependence on any particular server vendor, rather than the opposite. But, you'll have to learn the Java way of doing some things. ## Jason Orendorff http://www.jorendorff.com/ From gerson.kurz at t-online.de Tue Mar 5 04:14:44 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Tue, 05 Mar 2002 09:14:44 GMT Subject: I've got the unicode blues References: <3c846d80.95456984@news.isar.de> Message-ID: <3c848c0e.103279375@news.isar.de> On 05 Mar 2002 10:36:26 +0100, Martin von Loewis wrote: >There was a bug in the UTF-16 stream reader of Python 2.1, where it >would not remember the byte order across .readline invocations. That >bug is fixed in Python 2.2. ... >Please try Python 2.2 first; if there is any remaing problem, report >it to SF. All tests were made using PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 from inside PythonWin. From antoni3 at otenet.gr Thu Mar 14 17:08:21 2002 From: antoni3 at otenet.gr (Kaklis Antonis) Date: Fri, 15 Mar 2002 00:08:21 +0200 Subject: Good book on Python? References: Message-ID: 1) "Learning Python" --Mark Lutz & David Ascher Little old (covers Python1.5.2), but excellent for a begginer 2) "Core Python Programming" --Wesley J.Chun Details the core Python fundamentals and much more 3) And of course the Python tutorial http://www.python.org/doc/current/tut/ 4)"How to think like a computer scientist in Python http://www.ibiblio.org/obp/thinkCSpy/ Antonis From ayinger1 at pacbell.net Thu Mar 14 22:53:19 2002 From: ayinger1 at pacbell.net (andrew) Date: 14 Mar 2002 19:53:19 -0800 Subject: how do i get xml.sax.make_parser() to work on solaris and cygwin python Message-ID: hi. following the basic sax tutorial, i can get an xml parser to work fine on win32 like so: xmlparser = make_parser() xmlparser.setContentHandler(myHandler()) xmlparser.parse(xmlFile) but, when i run under cygwin or solaris, i get this error: >>> p = make_parser() Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.1/xml/sax/__init__.py", line 88, in make_parser raise SAXReaderNotAvailable("No parsers found", None) xml.sax._exceptions.SAXReaderNotAvailable: No parsers found it looks like neither cygwin nor solaris python installation includes expat libraries. any idea how i can get this working? i am using python 2.1/2.2. thanks, andrew From mwh at python.net Fri Mar 1 07:10:56 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 1 Mar 2002 12:10:56 GMT Subject: import Random: NV_MAGICCONST deviates too much. References: <29575ad6.0202282330.16226275@posting.google.com> Message-ID: marijn at sanity.dhs.org (marijn Vriens) writes: > Hi all... > > I have get a strange exception when importing random. > I brought it down to: > > Python 2.1.2 (#1, Jan 18 2002, 18:05:45) > [GCC 2.95.4 (Debian prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> import gnome.ui > >>> import random > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.1/random.py", line 93, in ? > _verify('NV_MAGICCONST', 1.71552776992141) > File "/usr/lib/python2.1/random.py", line 88, in _verify > raise ValueError( > ValueError: computed value for NV_MAGICCONST deviates too much > (computed 2,82843, expected 1) > >>> > > If I first import random and then gnome.ui I have no problems. my > distr is debian woody with the standard python packages (not > self-compiled) on an > AMD-K6 > > Anybody know what's going on ? At a guess, something in gnome.ui is buggering around with locale settings. Don't know if this actually helps -- I can't see quite how it could produce the above error... Cheers, M. -- The Internet is full. Go away. -- http://www.disobey.com/devilshat/ds011101.htm From i-have at no.mail Sat Mar 16 15:45:30 2002 From: i-have at no.mail (Jeffrey-man) Date: Sat, 16 Mar 2002 23:45:30 +0300 Subject: Begginers Guide - Exrcise. Help me, plz! Message-ID: Hello, everybody! I'm a newbie and I'm just learning. I know, it's a stupid question, but I want to resolve it. Learning the Begginers Guide, I found an exercise. It tells me: "Write a program that continually reads in numbers from the user and adds them together until the sum reaches 100." Can anybody help me? ----- sum_stop = 100 num = input("Please enter the number: ") for sum in range(num+num,sum_stop): print "Now the sum is", num+num sleep(1) print "The sum is >/= 100!" ----- Maybe I'm doing something wrong? Best regards. From mcherm at destiny.com Fri Mar 15 15:12:58 2002 From: mcherm at destiny.com (Michael Chermside) Date: Fri, 15 Mar 2002 15:12:58 -0500 Subject: unittest.py: what is TestResult.__repr__ ? Message-ID: <3C9255CA.8080907@destiny.com> The names with leading and trailing double underscores (like "__repr__") are "special" names. These correspond to methods (or other things) which have special meaning to Python. For instance "__init__" is the special method which is called to initialize new instances of a class when they are created. "__repr__" is the special method which is called to create a string which represents the class. Actually, that's a little bit misleading, because I'd give the SAME definition for the special method "__str__". Python has two different convert-to-cannonical-string-form methods, because in certain cases (eg: strings) it's useful. Normally, __str__ will be a "normal" convert-to-string method, and __repr__ will convert to some form which would, if executed, re-create the object. For more information see http://python.org/doc/current/ref/specialnames.html -- Michael Chermside From martin at v.loewis.de Sat Mar 30 16:58:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 22:58:45 +0100 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> <3CA5F90F.BF37B528@engcorp.com> <3CA622EF.B7C84035@geneva-link.ch> Message-ID: "Boris Qar?" writes: > How's that ? What's the point of making bool a type if we > can't subclass methods for __and__, __or__, __or_not__, > etc ? we could still save the shortcut semantics ... Those are redefined in bool (although the third one is name __xor__); but they refer to the bitwise operators, &, |, ^. The shortcut construct (and, or) won't change under this PEP. Regards, Martin From usenet at thinkspot.net Fri Mar 22 20:41:21 2002 From: usenet at thinkspot.net (Sheila King) Date: Fri, 22 Mar 2002 17:41:21 -0800 Subject: Begginers Guide - Exrcise. Help me, plz! References: <3C9B7A1E.451453BA@ccvcorp.com> Message-ID: On Fri, 22 Mar 2002 10:38:22 -0800, Jeff Shannon wrote in comp.lang.python in article <3C9B7A1E.451453BA at ccvcorp.com>: > > > Jim Dennis wrote: > > > Shouldn't all these (helpful) examples be using raw_input() rather > > than input(). Do we really want the new user to be implicitly and > > blindly using eval(raw_input())? > > Yes, they should. :) The calls to input() should, in this case, all be > replaced by int(raw_input()), and optionally wrapped in a try/except and while > loop, so that the program can prompt again if a non-numeric value is given. I > almost mentioned this in my earlier response, but decided not to overly confuse > the O.P. -- this essentially doubles the code size. I think it is important, when someone new asks one of their first questions, to just focus on answering the question at hand. Someone brand-new to programming has a difficult time to learn: ok...to repeat your program, you need a loop, and here's how the loop works, and you need to initialize your variables, and also it's a good idea to check your input and... Too many things thrown at them at once can be quite overwhelming. Simply ignoring the input issue for now is fine. As they work with their code, they will probably hit a wrong key occassionally, and notice that the program produces and error message. It's a good thing, to have that type of experience. If it becomes annoying because it happens often, or if they become curious about whether there is a way to avoid such error messages, they will probably come back and ask about that then, when they are more ready to learn about that. "Say, thanks for your help with the loop thing. I've been working on my code and I noticed that if I enter a value that isn't an integer, it causes problems in my program..." When they ask about it, is when they are ready to learn about it. You don't have to give them perfect code as a response to early programming questions. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From mlerner at rastan.gpcc.itd.umich.edu Fri Mar 15 12:08:43 2002 From: mlerner at rastan.gpcc.itd.umich.edu (Michael George Lerner) Date: Fri, 15 Mar 2002 17:08:43 GMT Subject: YANRQ (yet another regex question) References: <4f5k8.435$zT5.13755@news.itd.umich.edu> Message-ID: Mats Kindahl wrote: > Mats Kindahl writes: >> Michael George Lerner writes: >> >> > I wanted to match this: >> > >> > (?Pfoo | foo | foo | foo | foo) >> > >> That's what I get for not reading the manual... :/ > > r = re.compile(r'(?P(?=.{7}$) *foo *$)') > ^ ^ > ! ! > notice missing dollars --+--------+ Cool! .. but still not quite what I wanted .. And that's what *I* get for snipping information out when I post a followup :/. In my original post, I mentioned that I wanted something like r'(?Pstart)(?P foo )(?Pend)' i.e. other patterns on the same line before and after foo. placing-?=-in-my-bag-of-regex-tricks-ly yours, -michael From calves at coelce.com.br Mon Mar 11 13:18:43 2002 From: calves at coelce.com.br (Alves, Carlos Alberto - Coelce) Date: Mon, 11 Mar 2002 15:18:43 -0300 Subject: RES: lambda question Message-ID: <29A97D00F387D411AC7900902770E148044AB618@lcoeexc01.coelce.net> Sorry, but your code doesn't work also. See below: >>> def exe1(f,list): return map(lambda x,list=list:eval(f),list) SyntaxError: local name 'f' in 'exe1' shadows use of 'f' as global in nested scope 'lambda' (, line 1) >>> By the way, where can I find the Python's LGB scoping rules. I would like to read that. > -----Mensagem original----- > De: Fredrik Lundh [mailto:fredrik at pythonware.com] > Enviada em: segunda-feira, 11 de mar?o de 2002 14:59 > Para: python-list at python.org > Assunto: Re: lambda question > > > lambda questionAlves, Carlos Alberto wrote: > > > first code: > > f='x**3+2*x' > > list=[0,1,2,0] > > map(lambda x:eval(f),list) > > > > second code: > > > > def exe1(f,list): > > return map(lambda x:eval(f),list) > > > > Can someone explain to me why the first code works while > > second doesn't. > > because you're running under Python 2.1 or earlier, and > haven't read up on Python's LGB scoping rules? > > if so, the following should do the trick: > > def exe1(f,list): > return map(lambda x,list=list:eval(f),list) > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimd at vega.starshine.org Thu Mar 28 04:36:23 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 28 Mar 2002 09:36:23 GMT Subject: problems with circular references References: Message-ID: In article , jimh wrote: >> It sounds as though somehow or other you want to put the >> actual error number data for each class into MessageCatalog >> and give the 50 classes some interface for registering >> their error numbers with MessageCatalog. Then MessageCatalog >> is oblivious to what other classes there are, except that >> at run time they tell it about themselves. You could add >> another object for holding the error number data >> and have one instance per class---if that provides a convenient >> structure for accessing the error number data... >> susan >I will have to think about that one. When a class accesses the >MessageCatalog, it may be requesting message text from _other_ classes' >errors. Also, these are often called from cgi scripts, so they are run as a >one-shot deal. Also(!), the case of an error is (theoretically) uncommon >and the MessageCatalog is only instantiated if an error occurs. That way, >if no error occurs, there is no overhead with importing the MessageCatalog. >One thought I had was to split out all the error numbers from the class >files (kind of like .h versus .c files). Then MessageCatalog.py would only >import the ".h" files and I wouldn't have the circular import reference. >However, that would add another 50(!) files. >Jim That's abhorent! Just put the list of 50 error codes in the MessageCatalog.py file directly. Let all 50 modules (or other scripts, or whatever they are) load that on demand (when they need their own or ANY other error code. The message catalog module can't possibly be big enough and/or slow enough to create any measurable overhead for the various component scripts. If there is any measurable latency then look at some sort fast CGI or mod_pyton, mod_snake or some other way to give these CGI scripts some persistence. From bac at OCF.Berkeley.EDU Mon Mar 11 00:07:24 2002 From: bac at OCF.Berkeley.EDU (Brett Cannon) Date: Sun, 10 Mar 2002 21:07:24 -0800 Subject: Internships and summer jobs Message-ID: Is there any place out there to find a list of Python-related internships or summer jobs? How about entry-level Python jobs? I don't know about others, but I am graduating from school and looking for any of the three types of jobs mentioned above and would love to know of a place online listing such opportunities for people like me with Python experience. And I really doubt I am the only Python programmer graduating come summer. -Brett C. From martinkaufmann at yahoo.com Wed Mar 13 06:40:38 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Thu, 14 Mar 2002 00:40:38 +1300 Subject: Question about scientific calculations in Python References: Message-ID: <9gcu8u483cn544anr78k67jsknuv4tb6ks@4ax.com> On Tue, 12 Mar 2002 22:15:43 -0700, "Andrew Dalke" wrote: Thanks a lot for you long answer! >Here's some performance improvements you can make [lots of very helpful stuff snipped...] >Some of these changes are only faster for sufficiently long arrays, >so you should test them out yourself. The biggest trick is to >precompute as much as possible (Python doesn't optimize constant >expressions). This includes precomputing lookups of functions >references, like the "local_sin". Yes, I heard about this "local" trick, but I didn't try it yet. >That code is almost identical with the previous code, so you can do >the same optimization tweaks. You could also precompute which hist >elements have entry[1] == 0 so you don't do that check every time >in the loop. (As it is now, the "if" check is probably more expensive >than the calculation, even if you know it's zero, unless there are a >lot of zeros.) I didn't quite understand this part. How should I precompute the zero entries? How do I know where they are? Or should I just cut them out before and access the histogram differently? >If your lists are really long (O(100,000) or more?) then you might find >that the append starts taking too long -- append is asymptotically O(n**n) >in Python -- so that precomputing > > i_vector = [None] * len(s_vector - 1) > >then keeping an index 'n' to replace > i_vector.append( ...) >with > i_vector[n] = ... >is faster. But this is unlikely. The list are not that long. Probably only a couple of thousands entries. >Probably the best optimization you can do, if PyInline is an acceptable >approach, is to write put that sinc sum into C code. It reduces to >taking two lists and returning a float. I tried to use weave.inline. Here is my code. But put your coffee away before you read it (you might spill it otherwise over your keyboard) and _please_ don't laugh out loudly.. I really didn't know what I was doing, but it somehow worked... ----------- code begin ------------- code = """ PyObject *intens=PyList_New(s_length); double sum, x, s, h, f_s, i; for (long t=1;t Message-ID: "Carel Fellinger" > You specify that the > integer to iterate over should be possitive, why not allow for > negative values and do the sensible thing, like: > > >>> [i for i in -3] > [-1, -2, -3] If you change the sensible thing to mean: [-3, -2, -1] I'd like it better. ;-) Emile van Sebille emile at fenx.com From mwh at python.net Thu Mar 14 06:23:25 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 14 Mar 2002 11:23:25 GMT Subject: Python Version Strategy? References: Message-ID: Trent Mick writes: > [Bo Vandenberg wrote] > > I'm confused by what is going on with the python versions from various > > sources. > > > > Python.org has a final 2.2 (I use that) but Activestate has a python 2.1 as > > its recommended python and only a 2.2 beta last I looked. > > 2.2 is the latest stable Python release (modulo your own definition of > stable). It was released 21 Dec 2001. > > If your definition of stable is pretty high then you might want to consider > using Python 2.1.2 (i.e. Python 2.1 with two addition bugfix releases). > > ActivePython (from ActiveState) does not have a final 2.2 build just because > we are behind (discliamer: I work at ActiveState). Expect an ActivePython 2.2 > very soon. Are you going to wait for 2.2.1? That shouldn't be all that far off. > > Redhat, and most (all?) of the linux distros seem to be slow to fully > > upgrade and I feel like this is raining in my cornflakes. > > Yup. As I understand it the core Python folks don't really have any pull for > what default Python version gets installed for the various Linux distros. > > > > I'm not even beginning to think of when the next version of python (3?) > > comes out. > > The next version of Python will almost certainly be 2.3. The release schedule > is here: Well, the next version to be released will be 2.2.1, which is 2.2 + bugfixes (there are quite a lot). This will be released more-or-less when I get round to it, but "fairly soon". There will be at least one release candidate first. Cheers, M. -- 8. A programming language is low level when its programs require attention to the irrelevant. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From fperez528 at yahoo.com Thu Mar 28 01:12:03 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 27 Mar 2002 23:12:03 -0700 Subject: interactive python shell References: Message-ID: ian reinhart geiser wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Greetings > I have an python application and I would like to provide a "console" in the > application where users can have an interactive session with python that has > all of the applications enviroment. This is for debugging the system in > real time. > > Is there an easy way to do this? All it needs to do is execute commands and > return data. I am using PyQt for my GUI, so it would be cool to fit into > there, but I can get away with a input line and a display view if that is > easier. This is not for production, only to make a more useful debug tool. Check out http://www-hep.colorado.edu/~fperez/ipython/ Please grab the latest version (.10pre3 as of now), as it includes a number of fixes specifically for what you want to do. With IPython, there's a class for embedding exactly as you want, docs and examples are provided. If you end up using it, let me know how it goes. Cheers, f. From evebill8 at hotmail.com Sun Mar 17 12:33:03 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Sun, 17 Mar 2002 17:33:03 GMT Subject: time out socket Message-ID: Would anybody please tell me how time out the socket.connect() if the host does not exists or is unable to connect, thanks! Billy From sumner-nntp5 at forceovermass.com Sat Mar 9 12:35:14 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Sat, 09 Mar 2002 17:35:14 GMT Subject: should i learn it first ? References: Message-ID: In article , Qiang.JL wrote: > I am a student who have learned perl,java and other like data structure > stuff. Now i want to take some further step to learn one or two languages to > improve my language view. There are two languages are on the list: python > and C++ You say C++ here, but later you say C/C++. C and C++ are different languages. IMO, C is worth learning simply because it's a very low-level language (relative to the others you know) and lots of interesting software (e.g.perl, java, and python) is implemented in C. It'll also expose you to explicit memory management, pointers, etc. and to a procedural programming style. In my daily work, I do 90% of my coding in Python, occasionally dropping down to C when necessary, and occasionally using another language. While C++ was the first language I learned, I basically never use it. At any rate, learn plain C before you learn C++ and consider strongly whether or not you need C++ at all (this will be partially platform driven). I'd say to learn Python first, but it really depends on what you want to do with the language. > How many language do you think one should _master_? I think one or two is > enough.learning others are letting you to learn the language concept and > structure etc certainly helpful. I think a good progammer should master at least one statically typed functional language (ocaml is my preference, other examples are ML, Haskell), one high-level dynamic language (Python, or Ruby, Smalltalk, etc) and C for pragmatic reasons. That gives some exposure to many different kinds of programming. After that, Lisp, Prolog, and eiffel are worth a look (not necessarily master) from a mind-expansion POV (and some assembly language) and from a pragmatic POV Perl, Java, and C++ (on Windows) or Objective C (on Mac) or the Unix scripting environment (awk, sed, [k]sh, etc) on Unix. Sumner > > > > > > -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From thoa0025 at mail.usyd.edu.au Sat Mar 30 22:39:50 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 31 Mar 2002 03:39:50 GMT Subject: web - recommended authentication? Message-ID: Greetings, i wish to create authentication for a section of my website. what is a good practiced way to do this? via cookies? via .htaccess? (but i do not wish to use directories is it possible to restrict a script & query string? suppose script.cgi?request=specialarea via .htaccess??) what are your thoughts? cheers From donn at drizzle.com Tue Mar 26 10:28:47 2002 From: donn at drizzle.com (Donn Cave) Date: Tue, 26 Mar 2002 15:28:47 -0000 Subject: I imaplib reliable? References: Message-ID: <1017156522.615917@yasure> Quoth "Roger Binns" : | > I'm just not sure if Python's imaplib has been war tested. | | When I last tried it about 6 months ago, I found it to be full of | problems. In particular it pretty much just returned raw IMAP | protocol strings for most operations. The user of the library | then has to do far too much parsing work. Pardon me if I'm a little defensive of people who have contributed useful software to the python library. "Full of problems" is not "doesn't do everything I hoped it would." imaplib basically handles IMAP4 as a network protocol. Everyone who has used it will agree that there's a lot of work left to the user. But that's arguably the only way to go. Should imaplib parse everything? Well, that would be nice, maybe, but into what kind of structure? If I set out to do that, I'd probably use MxTextTools and return that kind of result - ever seen what that looks like? Others would probably prefer a parser that performs user-supplied actions as it parses the input. The difference is significant. The amount of work necessary to do either one right is fairly substantial, and probably requires a C module (like MxTextTools) if it's to be done efficiently, and yet whatever you do, it's highly likely it will work out best for you and not so well for anyone else, because we're fairly deep in the application specific area at this point. I'm not saying it wouldn't be a great idea for someone to take this on, but it's totally unfair to dismiss imaplib as "full of problems" because it doesn't do it. Donn Cave, donn at drizzle.com From grante at visi.com Sat Mar 16 00:43:27 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 16 Mar 2002 05:43:27 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <1016173476.645562@yasure> <2b57f654.0203151021.7f709e4c@posting.google.com> <2b57f654.0203151908.33413282@posting.google.com> Message-ID: In article <2b57f654.0203151908.33413282 at posting.google.com>, wealthychef wrote: > "Donn Cave" wrote in message news:... >> Quoth wealthychef at mac.com (wealthychef): >> ... >> |> The complementary problem, of course, is that once you have invoked >> |> readline(), it will read all the data available on the file descriptor, >> |> or a lot of it anyway, and return only the first line. The next time, >> |> it will return the next line from its buffer, but you have no way to >> |> know that it has another line waiting there. select() can't see it. >> |> There are solutions, I think the easiest thing in most cases is to >> |> throw away the file object and just use the file descriptor (fileno()) >> |> (or sockets in this case.) >> | >> | This is even more frightening. I don't want to lose any data! How >> | can I protect myself from this? Why is using the file descriptor >> | better? >> >> Well, you're not exactly losing data, it's just buffered, though that >> may be too fine a point depending on the circumstances. > > Here's what I mean. If I do a select.select() and it says, "there's > data," then I do a readline() on the file object, but select() was > talking about 2 lines of data, I will lose a line of data, because my > next select() will say "nothing left." Is that right? No. If there is two lines of data and you only read one, the second one is still there. Calling select will return immediately since there is data ready. > I just want to be sure I understand this. You're saying that > os.read() somehow get what select.select() was talking about, but that > f.fromchild.readline() will read less than that? If I understand correctly, the answer is yes. -- Grant Edwards grante Yow! My mind is a potato at field... visi.com From jimd at vega.starshine.org Thu Mar 7 03:38:37 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 7 Mar 2002 08:38:37 GMT Subject: select.select() on Regular Files? References: Message-ID: In article , Grant Edwards wrote: >In article , Jim Dennis wrote: ... > You've misunderstood what select() is telling you. When select > returns a read fd, that doesn't mean there's data available. It > means that a read() call on that fd will not block. A read() > call on a regular file's fd never blocks: it always returns > immediately with data or with EOF. Therefore, select() will > always return a read fd immediately for a regular file. > IOW, select() is supported for regular files, but the semantics > aren't very useful. >> This seems to contradict the documentation: >> Wait until one or more file descriptors are ready for some kind >> of I/O. > "ready for some kind of I/O" means that the read() or write() > call will not block. In the case of a read fd it doesn't imply > that there is data available. >> Is this a bug? I'm using Python2.2 as packaged by Debian (unstable) >> on a Debian GNU/Linux system (what a surprise, a Debian package >> on a Debian system!) under 2.4.9 SMP kernel). > Probably -- in the sense that the documenation was not > sufficient to prevent a surprise. Not in the sense that the > select() call doesn't do what the designers intended. >> Would poll() be a better choice? The __doc__ for that is a bit >> terse. > IIRC, poll() will do the same thing. O.K. so what can I do for asynchronous I/O notification on regular files? How can I efficiently block and wake up when I/O is available on any of my file descriptors? Don't tell me I have to go into a sleep and poll stat() or seek() loop! It's hard to imagine that UNIX got this far without offering a better solution than that! From holger at trillke.net Sun Mar 24 15:25:06 2002 From: holger at trillke.net (holger at trillke.net) Date: Sun, 24 Mar 2002 21:25:06 +0100 Subject: Stopping threads from the outside In-Reply-To: <3C9E2D31.E45278BC@engcorp.com>; from peter@engcorp.com on Sun, Mar 24, 2002 at 02:46:57PM -0500 References: <3C9E173A.88BBDBB4@engcorp.com> <3c9e2692$0$24819$e4fe514c@dreader3.news.xs4all.nl> <3C9E2D31.E45278BC@engcorp.com> Message-ID: <20020324212506.G12768@prim.han.de> > > Peter Hansen wrote: > > > Yes, that's the case. It's generally considered to lead to > > > undefined behaviour if you do manage to kill a thread from > > > the outside, because of resource locking issues and such. > > > > That's the received opinion indeed. It still leads to problems. > > I mean -- it's why you can kill a process, but not a thread. But in > > an agent system, every agent (presumably running a thread, although > > I've implemented systems where agents share threads, cooperative > > multi-tasking agents) is on its own, and shouldn't own objects > > or locks. > > I'm curious what the agent actually does if it doesn't share > anything. Does it not take input? And produce output? > No opening files, accessing Queues and such? If it does > any of those things, wouldn't that make it potentially a > problem if you killed it? Well. my agents share a namespace (named share:-) through which they can get to one another. You don't neccessarily need to brutally kill the thread without the running code in that thread to notice it. Something like this would be nice: def run(self): # thread's run try: while something: do_something() except ThreadInterruptException,e: niceley_free_locked_resources_or_such() or "simply" let the python interpreter switch the program flow to "destroy(self)" or so. This might require the thread to notify external modules e.g. a mt-safe Queue that all locks associated with this thread are to be released. But it would help. And somehow i think the interpreter must know about the threads as it is managing it (e.g. the global interpreter lock). So this should be possible? I don't know if this run-method would be possible if the thread sits in socket.accept() or such. But this issue has not much to do with locked resources hanging around. holger From shalehperry at attbi.com Thu Mar 28 17:43:46 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 28 Mar 2002 14:43:46 -0800 (PST) Subject: Newbie Question about os.removedirs() In-Reply-To: Message-ID: > > IMPORTANT (to me, anyway) NEWBIE QUESTION: What does Debian mean? > it stands for 'Deb and Ian'. Ian Murdock invented the Debian Linux distribution and named it after his wife and himself. it is pronounced as if you said their two names. From jkraska at san.rr.com Tue Mar 26 22:59:19 2002 From: jkraska at san.rr.com (Courageous) Date: Wed, 27 Mar 2002 03:59:19 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Message-ID: >I'd say the skills required to write clear, readable >software and clear, readable novels are not entirely >disjoint! Oh certainly not, you just haven't backed up to a big enough perspective of the cognitive domain. :) C// From shalehperry at attbi.com Fri Mar 29 16:29:03 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 29 Mar 2002 13:29:03 -0800 (PST) Subject: string copying In-Reply-To: Message-ID: On 29-Mar-2002 Robin Becker wrote: > Is there some special reason why python inhibits string copying. I > suppose there's some attempt being made to make these constants. To make > differing versions of 'abc' one has to resort to silliness like 'ab'+'c' > yes, the documentation is pretty clear that a string is a constant once defined. The current copy is a reference implementation is supposed to be an optimization for standard usage. What are you trying to accomplish where this is a hindrance rather than a gain? From danielm at cronus.res.cmu.edu Thu Mar 28 14:51:23 2002 From: danielm at cronus.res.cmu.edu (Dan Moskowitz) Date: 28 Mar 2002 11:51:23 -0800 Subject: rexec: I don't seem to understand "nok_builtin_names" Message-ID: <39503ed5.0203281151.25d2cdda@posting.google.com> Can someone tell me why execing "open" works, but not "len"? >>> from rexec import RExec >>> >>> class MyRExec(RExec): ... nok_builtin_names = RExec.nok_builtin_names + ("len",) ... >>> r = MyRExec() >>> print 'invisible names: '+`r.nok_builtin_names` invisible names: ('open', 'reload', '__import__', 'len') >>> r.r_exec('open') >>> r.r_exec("len('foo')") Traceback (most recent call last): File "", line 1, in ? File "/usr/local/depot/python2/lib/python2.1/rexec.py", line 264, in r_exec exec code in m.__dict__ File "", line 1, in ? NameError: name 'len' is not defined From stefan.heimann at web.de Sun Mar 3 15:17:56 2002 From: stefan.heimann at web.de (Stefan Heimann) Date: 3 Mar 2002 20:17:56 GMT Subject: Problems with print str, Message-ID: Hi! I have the following code-snippet: while 1: prompt = '> ' print prompt, a = sys.stdin.readline() print a and get the following: > hello hello > but I want it to look like: > hello hello > As you can see, there is a space in the 2nd line that should not be there. I played around with >>> sys.stdin.softspace 0 >>> sys.stdout.softspace 0 but couldn't figure out, how to avoid the leading space. Any help would be great! Thanks, Stefan From gbreed at cix.compulink.co.uk Mon Mar 4 11:48:20 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Mon, 4 Mar 2002 16:48:20 +0000 (UTC) Subject: Win32 2.2 & 2.1.2 References: Message-ID: Robin Becker wrote: > Is there a way to install Python 2.2 after 2.1.2 and keep 2.1.2 as the > default for a win32 box. It would allow us to dip a toe in the water > without drowning. Well, it's a bit of a roundabout solution, but if you install CygWin you get the latest version of Python and it doesn't interfere with anything else. Graham From jim at jim.jim Thu Mar 28 12:44:27 2002 From: jim at jim.jim (jimh) Date: Thu, 28 Mar 2002 09:44:27 -0800 Subject: problems with circular references References: <3CA298C1.6F5791AE@earthlink.net> Message-ID: > Like some others already pointed out, exceptions are probably > a better and more Pythonic way to handle this. But maybe, for > some reason, you cannot use them. I cannot see your code, > so I can't tell. Regardless of using exceptions or not, each class still has a list of errors that can occur, and those errors need to be mapped to (possibly localized) strings. > How about putting all error codes in one file? E.g. errors.py: > > FOO_ERROR = 1000 > BAR_ERROR = 1001 > BAZ_ERROR = 1002 > ...etc... > > Now all your 50 files can import errors.py and use the error > codes, rather than having to define them themselves. You lose modularity when you do this. The way it is now, each class is self-contained - everything about that class is in a single file. It is much easier to share classes with other developers (which we do) this way. Having said that, this may be preferable over having an additional 50 ".h" files. I was just hoping there would be a good "Pythonic" way to deal with this situation. > > All your MessageCatalog class needs to do is import that > errors.py file as well. Since it seems to be used for > mapping, have you considered using a dictionary? E.g. > > error_mappings = { > FOO_ERROR: "Foo not implemented", > BAR_ERROR: "Ixnay on the bar", > ...etc... > } > > Again, I can't see your code, so maybe I'm oversimplifying. > Still, knowing your description only, this is how I > would set it up. > > HTH, > From amund.tveit at pvv.org Wed Mar 6 09:22:19 2002 From: amund.tveit at pvv.org (Amund Tveit) Date: 06 Mar 2002 15:22:19 +0100 Subject: PDF solutions? References: Message-ID: "Steven D. Arnold" writes: > I'm looking for low- or no-cost solutions to the following PDF > problems. > > (1) I need to be able to replace form data in a PDF file with > arbitrary strings. > > (2) I need to be able to merge multiple PDF files together. > > I have found several commercial solutions; I'm looking for open-source > options. I have looked at ReportLab and on the surface it doesn't > appear to have ready-to-go functionality in this regard, but maybe I'm > missing something. Any solution that solves even one of these > problems would be great. > > Thanks in advance for any feedback. Etymon PJ (www.etymon.com/pj/) is possibly an alternative for manipulating pdf documents. (It is java-based, so jython may be the way to go) Amund http://www.jfipa.org/amund/ From che at debian.org Wed Mar 20 02:48:58 2002 From: che at debian.org (Ben Gertzfield) Date: Wed, 20 Mar 2002 16:48:58 +0900 Subject: [mimelib-devel] Re: Still same bug even with email ver. 1.2 In-Reply-To: <15512.12906.262129.702973@anthem.wooz.org> (barry@zope.com's message of "Wed, 20 Mar 2002 01:55:38 -0500") References: <7876a8ea.0203180837.4aaa1542@posting.google.com> <15512.12906.262129.702973@anthem.wooz.org> Message-ID: <87ofhjptlh.fsf@nausicaa.interq.or.jp> >>>>> "BAW" == Barry A Warsaw writes: BAW> What I think we ought to do is to deprecate BAW> Message.add_payload() but leave its semantics unchanged, BAW> change Message.attach() to not be an alias for add_payload(), BAW> and define the semantics of attach() to always set the BAW> payload to a list. Thus, the first time you call attach(). BAW> I think attach() should retain the semantics that if the MIME BAW> type isn't multipart/* it should throw an exception (i.e. you BAW> can't attach() to a non-multipart; use set_type() first). I don't really see any other way to deal with this without incurring extra breakage. BAW> For Python 2.2, I /think/ I can fix BAW> Generator._handle_multipart() to watch out for subparts that BAW> are scalar[1]. If so, then the patch to the Parser described BAW> above probably ought to be backed out. As long as the unit BAW> tests pass, I think we'd be okay. This is probably a good BAW> patch to keep for Python 2.3, just to be safe. That will be a good work around for the time being, IMHO. Ben -- Brought to you by the letters X and U and the number 17. "It makes my nipples hard!" Debian GNU/Linux maintainer of Gimp and Nethack -- http://www.debian.org/ From jbublitzNO at SPAMnwinternet.com Sat Mar 23 04:42:54 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Sat, 23 Mar 2002 09:42:54 GMT Subject: C++ Embedding Problem - Import Error Message-ID: <3C9C4D48.7010000@SPAMnwinternet.com> I'm building a plugin module (basically a dynamic library) under Linux that embeds Python. It links fine and using PyRun_SimpleFile I can load and run scripts. The scripts work fine when I import a module (.so) generated with sip from my own C++ libraries. Where it fails is when I want to import a non-built-in Python module (in this case I'm trying 'import time' in the script). The script fails at runtime with: ImportError: /usr/lib/python2.1/lib-dynload/timemodule.so: undefined symbol: PyExc_IOError nm says that PyExc_IOError is in libplugin.so as type 'B' (global, uninitialized data section). I can also reference the undefined symbol from within my own C++ code without a problem. I'm using libtool and have included the switches the Python docs say are required for all symbols to be exported: plugin_la_LDFLAGS = -avoid-version -module -no-undefined\ -Xlinker -export-dynamic Just to be clear, I'm linking libpython into another .so lib that's dlopened by an app. There is no possibility of linking Python directly with the app (or I wouldn't be writing a plugin in the first place). Anybody have an idea of what's going on and if/how this can be fixed? Jim From tripps81 at yahoo.com Sun Mar 24 23:19:44 2002 From: tripps81 at yahoo.com (Tripp Scott) Date: Mon, 25 Mar 2002 11:19:44 +0700 Subject: list comprehension question In-Reply-To: References: <5.1.0.14.2.20020324115311.0457dbb8@202.95.131.154> Message-ID: <5.1.0.14.2.20020325111055.044fbd08@202.95.131.154> At 25/03/2002 07:37, brueckd at tbye.com wrote: > > [SOMETHING for x in 1,2,3] > > > > and without using side effects like this? > > > > result=[] > > [(result.append(x), result.append(x+1.1)) for x in 1,2,3] > >You gotta give us more info on the 1,2,3 part. Does that just represent >a sequence of integers? If so, you can go with something like: > > >>> lo, hi = 1, 3 > >>> [x/2 + 0.1*(x%2) for x in xrange(lo*2, (hi+1)*2)] thanks for the tip. actually, the essence of what i wanted to ask was: "can that SOMETHING be a list of more than one elements which will be _flatly_ added to the result list." as another example, can i generate this list [1,1 2,2,2, 3,3,3,3, 4,4] with a list comprehension that contains one 'for' clause? t From lgrossi at bigpond.net.au Sun Mar 17 06:15:07 2002 From: lgrossi at bigpond.net.au (Luca Grossi) Date: Sun, 17 Mar 2002 11:15:07 GMT Subject: Python using EditPlus Message-ID: <%U_k8.5513$Hz2.19187@news-server.bigpond.net.au> Hello everyone , I'm sorry if this question has been asked before but could anyone give me instructions on how to debug and interpret python scripts using Edit Plus ? I download the python modules for edit plus so it recognise the syntax. But how do I setup the user tools , so I can check for bugs in the script and run it J Thanks Luca From gimbo at ftech.net Wed Mar 13 08:59:24 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 13 Mar 2002 13:59:24 +0000 Subject: MySQL Library or Interface? In-Reply-To: References: Message-ID: <20020313135924.GC12560@andy.tynant.ftech.net> On Wed, Mar 13, 2002 at 12:35:21PM +0000, Stephen Cox wrote: > Is there a MySQL library or some kind of framewrok available for Python? http://sf.net/projects/mysql-python/ -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From python at dejazzd.com Mon Mar 18 14:26:33 2002 From: python at dejazzd.com (Glenn Stauffer) Date: Mon, 18 Mar 2002 14:26:33 -0500 Subject: dealing with paths, multiple OS versions, cgi's Message-ID: <20020318192717.6A92617E88@juniper.its.swarthmore.edu> I have a cgi program that accepts an uploaded file through a web form and then attaches that file to an email message. I've run into a problem in testing that I haven't yet found a solution for and am hoping that someone could steer me in the right direction. When a file is uploaded through certain browsers - like the AOL web browser - the form['file'].filename value is a path. >From a Windows browser, the path will be something like c:\temp\file.doc >From a Unix browser, it might be: /home/user/file.doc Now, the CGI runs on a linux server, so os.path.basename() will return the base filename for the files being uploaded from a unix browser, but they will not properly handle the files being uploaded from a Windows browser. What I need is some method for stripping off the basename regardless of the browser OS. Any ideas? Thanks, Glenn From mlerner at asteroids.gpcc.itd.umich.edu Thu Mar 14 12:39:12 2002 From: mlerner at asteroids.gpcc.itd.umich.edu (Michael George Lerner) Date: Thu, 14 Mar 2002 17:39:12 GMT Subject: YANRQ (yet another regex question) References: Message-ID: <4f5k8.435$zT5.13755@news.itd.umich.edu> I wanted to match this: (?Pfoo | foo | foo | foo | foo) without typing in all of the different combinations of 'foo' and spaces. (Tim kindly pointed out the typos in the above, which I've corrected) Mats Kindahl wrote: > Depending on the definition of easy, this is the alternative I would > use. > r = re.compile(r'(?P(?=.{7}) *foo *)') > > Of course, your milage may wary. Doesn't quite work for me: >>> import re >>> r = re.compile(r'(?P(?=.{7}) *foo *)') >>> s = r.match('foo ').groupdict()['foo'] >>> s 'foo ' >>> len(s) 12 >>> and I only want to match things that are seven characters long here. It does, however, match all of the correct seven character strings, and I'll have to remember that trick in the future. Thanks! -michael From jeff at ccvcorp.com Tue Mar 5 14:46:19 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 05 Mar 2002 11:46:19 -0800 Subject: PEP 262 (database of installed Python packages) References: <3wgg8.685$Qo2.70120@news02.tsnz.net> Message-ID: <3C85208B.70951F13@ccvcorp.com> Andy Elvey wrote: > Hi all. > I've just been mulling over this (_very_ good and welcome!) PEP. In fact, > this suggestion is _so good_ that I'd like to "widen" it somewhat. Allow > me to explain .... (and please forgive the slight diversion past "Rubyland" > .... :-) > I've spent a _frustrating_ amount of time with a _Ruby_ package that can't > find various files. Now, I knew about PEP 262, so I was thinking in general > terms, it would be *truly* wonderful if there were a (standard?) database > of *all* installed packages (Python, Ruby, and whatever else) - maybe in a > directory called "search". In Linux, this could be "/search" , in Win32 > "C:\search". If I understand correctly what you're proposing, I'm not sure what this would gain. You want a single database which describes all installed modules/packages for Python *and* Ruby *and* etc... ?? How does this "integration" benefit? Your Ruby packages don't do Python any good. Your Python packages don't do Ruby any good. Putting them all in the same place just makes it easier to confuse things. (Hm, is that 'serial' directory for Python or Ruby?) While it might be beneficial for Ruby to have a parallel database, that follows the same general pattern as Python's, I can't see the gain for making them be the *same* database. Especially since separating them makes it possible for Ruby to use a different scheme, that it more appropriate to Ruby, and let Python use a scheme customized to Python, instead of both making compromises to accomodate the other. Jeff Shannon Technician/Programmer Credit International From Oschler at earthlink.net Sun Mar 31 18:24:22 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 31 Mar 2002 18:24:22 -0500 Subject: Python/Linux Message-ID: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Hey all. Just got my Linux web server system Linux ready. Moving on to Apache configuration in a bit. Note, I'm a long-time Windoze developer but a 3-day old Linux newbie (Suse 7.3 Pro, last Friday night. Already up and running and loving it.) I'd like to know which Web site development tool you like the best, because I'm going to assume that you're using one that integrates well with Python. Bear in mind that I'm one of those who like to be spoiled by a nice WYSIWIG IDE if possible. Here's is the choice list I've built up after surfing much, post much, and reading much replies: Quanta Bluefish PHP (Will I need to learn this or any other scripting lang if I'm using Python for all my custom site stuff?) Open Office's HTML tool Delph/Kylix with perhaps kbmWABD (I'm Delphi prog'er too) IBM's WebSphere home page builder (yes I know it cost a little) Really appreciate your input. thx P.S. - All of you that get the BBC channel and did not watch the Python marathon last night, shame (and spam) on you! :) From slzatz at hotmail.com Tue Mar 26 21:47:41 2002 From: slzatz at hotmail.com (Steve Zatz) Date: 26 Mar 2002 18:47:41 -0800 Subject: radiobutton menu item problem Message-ID: <6747bc9d.0203261847.5c56c42b@posting.google.com> On W2K and XP, when I run Tkinter programs with radiobutton menu items, the check mark is only partially visible until I roll the mouse over the selected menu item. To be clear, the menu item was selected previously, however when you return to that menu, the selected menu item only has a partially visible check until you move the cursor over the item. And when you do bring the check mark 'to life' by rolling the cursor over it, the check mark overwrites most of the first letter of the menu text. Has anyone seen this? I realize the problem is more aesthetic than fatal, but would like to fix if possible. I am using whatever version of Tkinter and Tcl/Tk came with the standard Python 2.2 Windows release. From guido at python.org Sat Mar 30 08:35:11 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 08:35:11 -0500 Subject: [Python-Dev] RE: PEP 285: Adding a bool type In-Reply-To: Your message of "Sat, 30 Mar 2002 04:35:32 EST." References: Message-ID: <200203301335.g2UDZB601508@pcp742651pcs.reston01.va.comcast.net> > > How will bool influence '__nonzero__'? Currently, Python insists that > > '__nonzero__ should return an int'. Will this be changed to 'should > > return a bool'? > > I hope so. Actually, it doesn't matter. This is only called by C code that must then return a *C* 0 or 1, and this code is entirely oblivious to the difference between int and bool. --Guido van Rossum (home page: http://www.python.org/~guido/) From James_Althoff at i2.com Mon Mar 4 16:29:06 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 13:29:06 -0800 Subject: Status of PEP's? Message-ID: [Jeff Hinrichs] > How can one iterate over something that is not a > sequence/collection? By defining the method __iter__(self) to return an iterator object . Iterators are very useful and general-purpose. No need to confine them just to sequences. > I haven't seen any argument on why range/xrange is less preferrable to iterable integers. The advantage that iter(n) has over range(n) and xrange(n) is that Python calls iter automatically. > I've heard the philosophical debate but not seen how python > would be better for this addition. If a good, tangible case > were made I could be influenced. > It would have to be a stronger case than: > for i in 5: is better than for i in range(5): > print i print i Please refer to the PEP. There is a "rationale" section. "for i in 5" happens to work and I would wager would become popular when typing into the intepreter, for example. But, it is not the motivating example in the PEP. > **Not everything is an object.** Fortunately, in Python it is . > Numbers don't perform operations ... and they can >>> -3 .__abs__() -3 >>> > It is not natural to consider a number as a collection of other > numbers. So don't consider that. Just consider whether or not it would be useful to get an iterator from a number . Jim From jlh at cox.net Tue Mar 26 23:26:04 2002 From: jlh at cox.net (Jeff Hinrichs) Date: Wed, 27 Mar 2002 04:26:04 GMT Subject: What am I doing wrong with urllib.urlopen() ? References: <11e94203.0203191617.46008366@posting.google.com> <11e94203.0203232201.4dde9883@posting.google.com> <20020324081829.193$iP@news.newsreader.com> <11e94203.0203261527.89fb2ca@posting.google.com> Message-ID: curl/libcurl http://curl.haxx.se/ with pycurl http://pycurl.sourceforge.net/ hth -jeff "Jose Rivera" wrote in message news:11e94203.0203261527.89fb2ca at posting.google.com... > >>Is there a better way? > > A better way of what? I missed the original post. > > I mean a better way of fetching the info from the Web Page, I like > Python, but if anyone knows of any utiliy that can download that pages > automatically to text files... that would be great. Because it would > be more easy for me to process the info in Python from files saved on > disk, than from WEB PAGES. > > Taking in account that this is the first time I am using urllib > library. > > Thanks... From sumner-nntp5 at forceovermass.com Sun Mar 17 16:34:48 2002 From: sumner-nntp5 at forceovermass.com (G. Sumner Hayes) Date: Sun, 17 Mar 2002 21:34:48 GMT Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: In article , Mike Dean wrote: > One thing that's always baffled me on this issue (along these lines) - > why does Python have != as a not-equal operator, when ! is not the not > operator? Even in C, I never thought of != as being the not operator applied to the assignment operator. I thought of it as an ASCII art approximation of the "real" not equal symbol (= with a line running through it). ! is the closest thing to a vertical line on older keyboards (/= and |= are already assignment operators), and represents the vertical stroke through the equal sign. Like the accent marks in TeX and similar. Just my $.02, Sumner -- rage, rage against the dying of the light Usenet email address changes periodically. sumner-nntp at forceovermass period com is more permanent. From phr-n2002a at nightsong.com Fri Mar 1 17:41:07 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 01 Mar 2002 14:41:07 -0800 Subject: Rotor in Jython? References: Message-ID: <7xr8n329oc.fsf@ruckus.brouhaha.com> writes: > Put another way: sorting by key length, AES beats rotors hands down. > Sorting by computational cost, rotors always win because you can just make > the keys longer (without having to reimplement your crypto). Longer keys are only relevant if breaking the cipher requires searching for the key. From mxp at dynalabs.de Wed Mar 6 19:41:04 2002 From: mxp at dynalabs.de (Michael Piotrowski) Date: Thu, 07 Mar 2002 01:41:04 +0100 Subject: Compiling Python 2.2 with GCC in HPUX 10.20 does not work References: <3C848CBF.9000201@vip.fi> <3C84F129.70905@vip.fi> Message-ID: pekka niiranen writes: > True, HP-UX's default compiler is only meant for compliling the kernel > therefore I installed binutils v2.11.2, gcc v3.01 and gmake v3.79.1 from > HP's software repository and tried compiling with this script: > > #! /usr/bin/sh > export CCOPTS='+z' > unset LANG > gmake distclean > CC=gcc ./configure --with-gcc --with-threads=no --without-cxx > --prefix=/opt/python Just a note: The CCOPTS environment variable is only used by HP's ANSI C compiler, gcc doesn't use it. > gmake fails twice: > > 1) > /osasto/home/niirape/python_softa/Python-2.2/Modules/getaddrinfo.c:544: > warning: `h_error' might be used uninitialized in this funcn [...] Use -D_XOPEN_SOURCE_EXTENDED to get the definition of h_error. > ld -b build/temp.hp-ux-B.10.20-9000/777-2.2/_cursesmodule.o > -L/usr/local/lib -lncurses -o > build/lib.hp-ux-B.10.20-9000/777-2.2/_curl > ld: DP relative code in file /usr/local/lib/libncurses.a(lib_addch.o) > - > shared library must be position > independent. Use +z or +Z to recompile. > WARNING: building of extension "_curses" failed: command 'ld' failed > with exit status 1 The ncurses library must either be a shared library, or it must contain only position-independent code. Thus, you need to rebuild ncurses with the appropriate options: +z for the HP ANSI C compiler, -fpic for gcc. -- Michael Piotrowski, M.A. From martin at v.loewis.de Fri Mar 1 15:36:35 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 01 Mar 2002 21:36:35 +0100 Subject: SAX-Parser entity References: Message-ID: fabi.kreutz at gmx.de writes: > I spend the last 3 hours browsing FAQs and Mailinglist - without success - > but have nevertheless the feeling, that this is a very easy question: It is indeed very easy: There is an error in your document. It has no encoding declaration in the xml header. The parser rightfully rejects it. Regards, Martin From carifio.nospam at nospam.usys.com Wed Mar 13 12:57:50 2002 From: carifio.nospam at nospam.usys.com (Mike Carifio) Date: Wed, 13 Mar 2002 17:57:50 GMT Subject: augmented arithmetic operations References: Message-ID: I asked the question badly and even botched the example. Worst yet, I could have answered it for myself if I had read the documentation a little better. It appears that you get a simple, but useful "automatic" implementation of __iadd__ if you've already defined __add__ (and __isub__ for __sub__ and so forth). If you decide, for whatever reason, that you'd like to override that default, you can do so. In fact, the doc's recommendation is to try to update self "in place" without making intermediates and then return the result. Which is pretty cool, actually, because you can get your class up and running then improve it's performance at some later date. Blame it on newbie impatience. From eppstein at ics.uci.edu Wed Mar 6 19:57:03 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 16:57:03 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , Steve Lamb wrote: > Fine, don't like range(n-1,-1,-1) and don't feel like taking the <60s to > look it up? I give you: > > foo = range(n-1,0) > foo.reverse() > for x in foo: > do_whatcha_like(x) > > Still too obtuse for you? I think you have made my point for me, that range is hard to use correctly. Did you try running range(n-1,0)? What list did it give you? From mszigety at cisco.com Fri Mar 29 09:12:08 2002 From: mszigety at cisco.com (Mark Szigety) Date: Fri, 29 Mar 2002 09:12:08 -0500 Subject: Python 2.2 chr representation errors with embedded C Message-ID: <000701c1d72b$b6a50c40$02ff1a42@peanut> Hello, I have recently made the upgrade to Python 2.2 from 1.5.2. In the Python application which I develop, we have several embedded C functions, one of which is a simple function to convert a hex string to octal--it simply chars each byte and returns the new buffer. However, I have noticed a 0.01% error rate in Python 2.2 which I did not see in Python 1.5.2 (it was 100% accurate). That is, 1 out of 10,000 hex strings will be converted incorrectly in the C function, usually one byte is returned as \x00 instead of what is should be. I also have noticed that in Python 2.2, chr(0xff) returns \xff instead of \377 in Python 1.5.2. Could this be the source of the communication breakdown? I should mention that writing a similar conversion function totally in Python is 100% accurate in Python 2.2 as well as Python 1.5.2, although it is an order of magnitude slower. Any information about the apparent source of this issue would be appreciated! Thanks, Mark From t.kloppenburg at billiton.de Wed Mar 27 09:47:40 2002 From: t.kloppenburg at billiton.de (Tjabo Kloppenburg) Date: Wed, 27 Mar 2002 15:47:40 +0100 Subject: list element of a class with the for statement In-Reply-To: References: Message-ID: hi Just, > But with the way you wrote the new-style iterator it won't. It's also > not thread-safe. Why wouldn't it work? I haven't tested the code, but I think it's the right way. I've seen this in http://www.amk.ca/python/2.2/index.html, "3 PEP 234: Iterators". > Python classes can define an __iter__() method, which should create and return a new iterator for the object; if the object is its own iterator, this method can just return self. In particular, iterators will usually be their own iterators. Extension types implemented in C can implement a tp_iter function in order to return an iterator, and extension types that want to behave as iterators can define a tp_iternext function. So, after all this, what do iterators actually do? They have one required method, next(), which takes no arguments and returns the next value. When there are no more values to be returned, calling next() should raise the StopIteration exception. > How can I do it thread safe? Willing to learn, :-) tk. From les_ander at yahoo.com Thu Mar 7 21:41:23 2002 From: les_ander at yahoo.com (les ander) Date: 7 Mar 2002 18:41:23 -0800 Subject: why is python slow? Message-ID: Hi, i am just curious as to why different programming languages have different speed. I understand that if a language has an extensive grammar (such as c++) the compiler would take longer. But what about execution? why is a perl program faster than similar python program? For example when java came out it use to be pretty slow, but now it is pretty fast. How was this speed-up acheived and why is it not possible to have such a speed up for python? thanks les P.S. I am just trying to understand and do not intend to put down python by any means. From landshark at verticaladdiction.net Fri Mar 1 00:16:31 2002 From: landshark at verticaladdiction.net (Dave Marotti) Date: Fri, 01 Mar 2002 05:16:31 -0000 Subject: what does this do? (really basic question) Message-ID: Hey, Hopefully this is a really basic question. I'm still in the learning phase, and came across this in a sample program: class Whatever: def __init__(self, user_list, cmd_list, **kw): code.... What does the **kw mean (specifically, the **) ? -dave -- +-----------------------------+----------------------------------------------+ | Dave Marotti | Looking for a Visio alternative for *nix? | | lndshark ! speakeasy net | Kivio : http://thekompany.com/projects/kivio | +-----------------------------+----------------------------------------------+ | I just don't trust anything | I suppose that in a few more hours I will | | that bleeds for 5 days and | sober up. That's such a sad thought. I think | | doesn't die. - Mr. Garrison | I'll have a few more drinks to prepare myself| +-----------------------------+----------------------------------------------+ From guido at python.org Sun Mar 31 21:35:47 2002 From: guido at python.org (Guido van Rossum) Date: Mon, 01 Apr 2002 02:35:47 GMT Subject: __name__ on new-style classes References: Message-ID: <3CA7C873.D1AC908A@python.org> "Gon?alo Rodrigues" wrote: > > One can change the name of a classic class but not of a new-style one > (see below for example). Is this a bug or a feature, and if the latter > is there any reason for the change? It's a feature. The reason for the change is that I've never seen an example of a use for it (as opposed to changing an instance's __class__). If you have one, let us know. --Guido van Rossum (home page: http://www.python.org/~guido/) From psage at ncaustin.com Wed Mar 27 10:27:44 2002 From: psage at ncaustin.com (Paul Sage) Date: Wed, 27 Mar 2002 09:27:44 -0600 Subject: menu.add_command options Message-ID: <03F53405C6ED434A986221919785A6A7106BEB@nca-postal.ncaustin.com> Tkinter: In the line: file_menu.add_command(label='Load Form', underline=0, command=self.open_file) Does anyone have a list of options that go with the menu.add_command? I need to pass the frame to the method open_file, but I don't know how to pass that as an argument. The book I have Python and Tkinter programming just says "options..." While I am all for a good mystery, it is somewhat disheartening to find in a $50+ book. From phd at phd.pp.ru Fri Mar 15 19:47:54 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sat, 16 Mar 2002 03:47:54 +0300 Subject: locale module broken? In-Reply-To: ; from martin@v.loewis.de on Sat, Mar 16, 2002 at 01:09:58AM +0100 References: <3C928042.BA50A5B3@snakefarm.org> Message-ID: <20020316034754.A4163@phd.pp.ru> On Sat, Mar 16, 2002 at 01:09:58AM +0100, Martin v. Loewis wrote: > Carsten Gaebler writes: > > > while playing around with Greg Lindstrom's "Pretty integers" (see his > > posting), my Python 2.2 got stuck here: > > > > >>> import locale > > >>> locale.setlocale(locale.LC_ALL, "fr_FR") > > 'fr_FR' > > >>> locale.format("%.1f", 12345.5, 1) > > > > It runs forever. This is on RedHat 6.2 and Debian Potato. Any hints? > > I can't reproduce this, with Python 2.3a0 on a SuSE 7.2 system: it > prints '12345,5'. If you care somewhat about this problem, submit a > bug report to SF. If you care a lot, please investigate. I reproduced this behviour on Debian 2.2 with all version of Python - 2.0, 2.1 amd 2.2... but only with FR locale. With ru_RU locale it works perfectly. It seems glibc has got broken FR locale. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From gimbo at ftech.net Mon Mar 25 10:49:45 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 25 Mar 2002 15:49:45 +0000 Subject: Root access with python In-Reply-To: <20020325123855.A1716@ibook.distro.conectiva> References: <7x663krjtp.fsf@ruckus.brouhaha.com> <20020325123855.A1716@ibook.distro.conectiva> Message-ID: <20020325154945.GD22091@andy.tynant.ftech.net> On Mon, Mar 25, 2002 at 12:38:55PM -0300, Gustavo Niemeyer wrote: > You have several options to do this, and all of them involve setting the > setuid bit in some executable. OTOH, setting setuid bit on scripts > usually doesn't work. If that's your case, you'll have to freeze your > script into a native executable, or build some kind of wrapper. Google > for "setuid bit scripts" for more information. As a general solution to this kind of problem, sudo is excellent, though it might be overkill for this particular case. http://www.courtesan.com/sudo/ -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From shalehperry at attbi.com Wed Mar 13 15:00:57 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 13 Mar 2002 12:00:57 -0800 (PST) Subject: Newbie regex question. In-Reply-To: Message-ID: On 13-Mar-2002 Omri Schwarz wrote: > > I have a regex = re.compile('yadda (widget1) (widget2) yadda') > and want to search a string I know to have multiple > instances of this regex. I'm a tad confused by > the RE Howto, so I'd like to ask, how do I properly > get a for loop to access the widget1 and widget2 > strings of each instance? > > for instance in regex.search(string).groups() > seems to be the right thing, but isn't working. > >>> import re >>> s= 'yadda widget1 widget2 yadda' >>> regex = re.compile('yadda (widget1) (widget2) yadda') >>> for match in regex.search(s).groups(): print match ... widget1 widget2 This works here. Although I would strongly caution you to do: re_match = regex.search(s) if re_match != None ...... just in case the regex fails. From tejarex at yahoo.com Thu Mar 21 21:51:15 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 22 Mar 2002 02:51:15 GMT Subject: Popular style document? References: <1016641355.370859@cswreg.cos.agilent.com> <3C9A797E.E6476BEE@spam.nada.kth.se> Message-ID: "Bj?rn Lindberg" wrote in message news:3C9A797E.E6476BEE at spam.nada.kth.se... > phil hunt wrote: > > > IMO the requirement to say self everywhere in methods is the worst > > feature of python. > > How come Python doesn't have an "automatic" this-variable, like C++ or > Java? Short answer: the language has to work together as a whole. If you mean requirement to say def meth(something, arg) instead of def meth(arg), compiler does not necesarily know when compiling whether function will be used as method or not. (Methods can be defined outside of class statement and assigned as method later.) If you mean requirement to say something.var instead of var, how else would you write equivalent of self.arg = arg within method? Terry J. Reedy From DavidA at ActiveState.com Thu Mar 28 15:00:11 2002 From: DavidA at ActiveState.com (David Ascher) Date: Thu, 28 Mar 2002 12:00:11 -0800 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! References: <001d01c1d67f$2eb81090$445d4540@Dell2> Message-ID: <3CA3764B.C46C7FD2@activestate.com> Brian Quinlan wrote: > I bet that after ActivePython 2.2 comes out, future releases will become > available in a more timely fashion. Spoken like someone who's worked with Trent for a while. =) FYI: ActivePython 2.2 is shipping imminently (really!) ActivePython 2.2.1 and 2.1.2 will ship soon thereafter. Thanks for all the interest in ActivePython. We hope to not have these kinds of delays in the future. -- David Ascher From bokr at oz.net Fri Mar 29 23:46:45 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Mar 2002 04:46:45 GMT Subject: Another stab at a "switch/case" construct (new proposal): References: Message-ID: On 29 Mar 2002 14:35:25 -0800, Ken.Peek at Engineer.com (Ken Peek) wrote: [... summary of attributed quotes ...] >[Bengt Richter]: >"case: Don't like it. We already have means to do what a case does >and do it more elegantly. It would add a needless redundant portion >to the language." > That wasn't I. This quotes me better ;-) ---- Kind of like it, but there would have to be some hot performance advantage. IMO the aesthetics aren't that much different from the above.[1] I definitiely wouldn't like break and continue to mean new things! --- ^--[sic] [1] (Referring to if/elif/else code using a condition-evaluating functor holding the switch value). Regards, Bengt Richter From gcordova at hebmex.com Tue Mar 12 12:31:24 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Tue, 12 Mar 2002 11:31:24 -0600 Subject: new to python - please help Message-ID: <19650FF08A99D511B19E00B0D0F0632301D6893A@SRM201002> > -----Original Message----- > From: owen_stevens at hotmail.com [mailto:owen_stevens at hotmail.com] > Sent: Martes, 12 de Marzo de 2002 11:16 a.m. > To: python-list at python.org > Subject: new to python - please help > > I made a dictionary with the following structure: > Damn, he got caught by the PSU *just* when he From cfelling at iae.nl Mon Mar 4 18:52:21 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 5 Mar 2002 00:52:21 +0100 Subject: Newbie ?:A more concise way? References: <8fc4b19e.0203031804.75d303a3@posting.google.com> <8fc4b19e.0203040130.17140530@posting.google.com> Message-ID: Brian wrote: > Carel Fellinger wrote in message news:... >> >>> class MyClass: pass >> >>> z = map(lambda x: C(), range(3)) ... > I'm happy with the performance of the expression too; I'm using a > similar map expression as an argument to Numeric.array() now and it > works very well for me. If it's performance and not code obfuscation you're after, maybe you'd better spent some time on profiling it. My gut feelings (and those are usualy wrong:) tell my to fear the lambda here as it introduces an extra function call (expensive in Python) for each instance to be made. -- groetjes, carel From peter at engcorp.com Sun Mar 17 23:30:52 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 17 Mar 2002 23:30:52 -0500 Subject: sunstring References: <0r4l8.22204$P4.1955815@newsread2.prod.itd.earthlink.net> <3C94DCC1.748EDC18@engcorp.com> Message-ID: <3C956D7C.401360DB@engcorp.com> Billy Ng wrote: > > "Peter Hansen" wrote: > > Billy Ng wrote: > > > > > > Would anybody tell me how to do substring in python? > > > > Use slices. And look at the string module. > > Have you gone through the tutorials yet? > > No, sir! I am very very new to python. I just bought the O'Reilly book > today. Then I gently suggest you make a small effort to read at _least_ the online tutorial, or skim through that book, before attempting to write real code. When you have a particular goal in mind (as I know you do) _and_ you have made a moderate effort to solve the problem on your own but encounter some difficulty, _then_ please ask away in this newsgroup. And _always_ post code snippets representing your best effort so we can understand what you've already tried (and that you _have_ tried) and our answers will be that much more helpful (and plentiful). Cheers, -Peter From marduk at python.net Sun Mar 17 18:52:58 2002 From: marduk at python.net (marduk) Date: 17 Mar 2002 17:52:58 -0600 Subject: syntax question: "<>" and "!=" operators In-Reply-To: References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: <1016409179.5343.5.camel@berkowitz> I've always wondered why you couldn't say "not ==" (as well as "not <", etc.) like you can say "not in" or "not x" since that seems to make more sense to me. --m Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From emmanuelgagniere at wanadoo.fr Sat Mar 30 05:46:13 2002 From: emmanuelgagniere at wanadoo.fr (Emmanuelgagniere) Date: Sat, 30 Mar 2002 11:46:13 +0100 Subject: wxPython install problems on linux References: Message-ID: I can't say where your error is coming from... but I can say you how I installed wxPython on my mandrake 8.0 1. Install from source python 2.2 2. Install gtk 3. Install wxGTK2.3.2 4. Install wxPython2.3.2.1 (check the install at http://wiki.wxpython.org/index.cgi/Getting_20Started#line57) it should works manouche hejduk a ?crit dans le message : da8db604.0203242126.267ab032 at posting.google.com... > Hi, I'm having a problem installing wxPython on linux (Slak 8). I have > all the necesarry prerequisites (wxGTK, python etc). When I run the > setup.py build script half way through i get the following error > messages: > > running build_ext > building 'wxc' extension > ... > src/helpers.cpp:26: gtk/gtk.h: No such file or directory > src/helpers.cpp:27: gdk/gdkprivate.h: No such file or directory > In file included from src/helpers.cpp:28: > /usr/local/include/wx/gtk/win_gtk.h:18: gdk/gdk.h: No such file or > directory > /usr/local/include/wx/gtk/win_gtk.h:19: gdk/gdkx.h: No such file or > directory > /usr/local/include/wx/gtk/win_gtk.h:20: gtk/gtkcontainer.h: No such > file or directory > /usr/local/include/wx/gtk/win_gtk.h:21: gtk/gtkadjustment.h: No such > file or directory > /usr/local/include/wx/gtk/win_gtk.h:22: gtk/gtkfeatures.h: No such > file or directory > error: command 'gcc' failed with exit status 1 > > > Not surprisingly when I try to run any of the demo programs I get an > error message about no wxc module. I know this is kind of specific and > obscure but if anyone can help it would be greatly appreciated. > Thanks. From phr-n2002a at nightsong.com Sat Mar 30 04:36:43 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 30 Mar 2002 01:36:43 -0800 Subject: PEP 285: Adding a bool type References: Message-ID: <7xhemy1jo4.fsf@ruckus.brouhaha.com> Guido van Rossum writes: > Dear reviewers: > > I'm particularly interested in hearing your opinion about the > following three issues: > > 1) Should this PEP be accepted at all. I don't see much need for it. There's no need to turn Python into Java. Python, C, and Lisp have all done fine without bools. What kinds of programming tasks in Python are bools supposed to make easier? > Some external libraries (like databases and RPC packages) need to > be able to distinguish between Boolean and integral values, and > while it's usually possible to craft a solution, it would be > easier if the language offered a standard Boolean type. Again, most of those libraries have C interfaces and (pre-C99) C didn't have bools. I could imagine adding some kind of bool objects in a loadable class for purposes like this, but don't see a need for them to pervade the language. Enums or symbols would be more useful than bools. > Here are some arguments derived from teaching Python. When > showing people comparison operators etc. in the interactive shell, > I think this is a bit ugly: > > >>> a = 13 > >>> b = 12 > >>> a > b > 1 Nah, if there's one thing everyone knows about computers, it's that they use 1's and 0's to represent truth values. > There's also the issue (which I've seen puzzling even experienced > Pythonistas who had been away from the language for a while) that if > you see: > > >>> cmp(a, b) > 1 > >>> cmp(a, a) > 0 > >>> > > you might be tempted to believe that cmp() also returned a truth > value. If ints are not (normally) used for Booleans results, this > would stand out much more clearly as something completely > different. If cmp returns a boolean, it can no longer distinguish the 3 cases a < b, a == b, or a > b. That is seriously broken. From maxm at mxm.dk Wed Mar 13 04:27:21 2002 From: maxm at mxm.dk (Max M) Date: Wed, 13 Mar 2002 09:27:21 +0000 Subject: sorting nested dictionary References: Message-ID: <3C8F1B79.8000607@mxm.dk> dsavitsk wrote: > i would like to sort this portion by 'weighted'. is there a quick (as in > programming time, not sorting time) better way to do this other than dumping > the values to a list, sorting, and realigning the data? that seems so > unpythonic to me somehow. How do you mean "sort" a dictionary? A dictionary will allways return the items in a random order. What you mean is probably that you want a list of keys that are sorted according to the value of weighted? Then you just create a list of tuples with the values you want to sort on first, and the key in the end of the tuple. This list you sort with the built in 'sort()' untested: dict = {'ids': {'2778xxxxx': {'weighted': 4.6, 'raw': 5.0}, '3059xxxxx': {'weighted': 6.1, 'raw': 6.0}, '3188xxxxx': {'weighted': 3.2, 'raw': 4.0}, '3216xxxxx': {'weighted': 10.1, 'raw': 7.0}, '3257xxxxx': {'weighted': 9.7, 'raw': 9.0}, '3266xxxxx': {'weighted': 4.8, 'raw': 3.0},}} sortedList = [] for key, val in dict['ids'].items(): sortedList.append((val['weighted'],key)) sortedList.sort() sortedKeys = [item[1] for item in sortedList] regards Max M From philh at comuno.freeserve.co.uk Sat Mar 30 17:55:04 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 22:55:04 +0000 Subject: string copying References: <3CA4F5CB.E8961330@engcorp.com> Message-ID: On Fri, 29 Mar 2002 18:16:27 -0500, Peter Hansen wrote: >Jeff Shannon wrote: >> >> In article , >> robin at jessikat.fsnet.co.uk says... >> > Is there some special reason why python inhibits string copying. I >> > suppose there's some attempt being made to make these constants. To make >> > differing versions of 'abc' one has to resort to silliness like 'ab'+'c' >> >> 1) Strings are immutable. This implies that there is zero >> practical difference between two references to two separate >> string objects of identical value, and two references to the same >> string object. > >The only one I've been able to think of is the surprisingly >common situation of trying to consume vast quantities of memory >quickly by something like: > >a = [0] * 1000000 >for i in xrange(1000000): > a[i] = 'bigstringsuckinguplotsofmemory' Simpler is range(1000000) -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From gerson.kurz at t-online.de Fri Mar 15 12:35:43 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 15 Mar 2002 17:35:43 GMT Subject: Using HTMLHelp files with win32all-146 for Python22 Message-ID: <3c922e49.11703328@news.t-online.de> The only thing I really miss from the ActiveState build of Python was the fine helpfiles they had. Looking up things in that HTML stuff sucks! And it gets worse when you install VPython, which replaces index.html with its own docs. Anyway, the official Python website has the docs in HTMLHelp format: http://www.python.org/ftp/python/doc/2.2/html-help-2.2.chm So now only to change Pythonwin to use them. First I hacked pythonwin/framework/help.py, but the recommended way is probably this: In the registry, in HKEY_LOCAL_MACHINE\Software\Python\PythonCore\2.2\Help\Main Python Documentation edit the variable to point to the .chm file rather than the index.html. That works! Now I only hope this isn't spelled out in large fonts somewhere in the doc & therefor obvious ;) From infinitystwin.SPAM at IS.BAD.yahoo.com Thu Mar 28 18:08:15 2002 From: infinitystwin.SPAM at IS.BAD.yahoo.com (Greg Krohn) Date: Thu, 28 Mar 2002 17:08:15 -0600 Subject: ConfigParser -> Section name through Option value References: <3CA375B1.9070802@flexis.de> Message-ID: "domi" wrote in message news:3CA375B1.9070802 at flexis.de... > Hi, > > can somebody help me with this ConfigParser (ini-file) problem: > Is it possible to get a Section name through an Option value > (ConfigParser), e.g.: > > [foo] > name = python > ... > > how can I get the section name 'foo' through the option value 'python'? > Any idea??? > > thanks dominik The problem is that 'python' may be the value for any number of options in any number of sections. If you have: [foo] name = python snake = python [bar] name = perl snake = python name = java Which one do you want? I would loop through each section, then through each option. Something like this: results = [] for section in cp.sections(): for option in cp.options(section): if cp.get(section, option) == 'python': results.append((section, option)) Now you have a list of section\option pairs. From suca at manning.com Tue Mar 19 13:55:52 2002 From: suca at manning.com (Susan Capparelle) Date: Tue, 19 Mar 2002 13:55:52 -0500 Subject: Python Proposal Review Message-ID: Hi, We're a high quality computer book publisher seeking reviewers for a book proposal we currently have in hand tentatively titled, "Effective Python." We're seeking 3-6 people to review this proposal and make comments that will help us make a decision on whether or not to publish. The proposal and outline are approximately 969 words in length. If you are interested in this opportunity, or can recommend someone who might be qualified and willing, please feel free to contact us. Thanks in advance! Sincerely, Susan Capparelle Assistant Publisher Manning Publications Co. ======================================= Susan W. Capparelle Assistant Publisher Manning Publications Co. 209 Bruce Park Avenue, Greenwich, CT 06830 suca at manning.com tel. 203.629.2211 www.manning.com fax. 203.629.2084 ======================================= From edream at tds.net Sun Mar 3 22:23:50 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 04 Mar 2002 03:23:50 GMT Subject: The Text Widget References: <5Hzg8.72869$vP.290047@rwcrnsc51.ops.asp.att.net> Message-ID: <3C82E8C4.24531DE7@tds.net> > I would like to know how to make it so that whenever I insert some text into > the text widget from inside my program, it is inserted on a new line? I am assuming you mean Tk text widgets interfaced with Tkinter. I believe you can do just about anything with Tkinter, and it may take a bit of hacking due to missing events and other strangenesses in Tk. I'll answer generally here, not being sure of your situation. First, note that if you bind to a key-press () event, when the event handler is called the Text widget hasn't been changed yet(!) Other frameworks provide a "text will change" event and a "text did change" event, but AFAIK Tk does not. You could use the "insert" mark or selection to determine where the keypress would go, but that gets messy in a hurry. To get around this, you can use the after_idle tkinter routine to schedule an action that will be taken _after_ the text is changed. You can then munge the text as needed. BTW, Tk does a good job of suppressing flashes, so this approach works well. There are many ways besides "general" key presses ( bindings) that can cause text to change. You may want to provide wrappers for your idle-time code that allow command handlers to indicate that the text has been changed or is about to be changed. For examples of how to do lots of things with Tk/tkinter Text widgets, take a look at Leo's event handlers in leoTree.py: OnBodyKey, onBodyChanged, onBodyWillChange and idle_body_key. Leo does lots of things on every keystroke, including syntax coloring, undo, auto indent, updating dirty marks etc. Auto-indent is probably most similar to what you want. Note that the bindings themselves are set in leoFrame.py and in leoTree.py. Hope this helps. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From bforney at cs.wisc.edu Wed Mar 13 17:44:36 2002 From: bforney at cs.wisc.edu (Brian Forney) Date: Wed, 13 Mar 2002 16:44:36 -0600 Subject: Statically linking standard Python modules into an application Message-ID: Hello, I have embedded a Python interpreter into an application I wrote. The application sometimes uses the standard Python modules, such as sys, depending on the script it executes and loads them dynamically. This solution works well most of the time. It does not work well in distributed execution environment I often use. The problem occurs when calling dlopen() to load Python modules. dlopen() and other functions that use mmap() are unsupported, yet they sometimes work, in this environment. I would like to remove calls to dlopen() by the Python library. Is there a way to statically link in all of the standard modules *and* the Python library *and* keep the Python library from calling dlopen() for standard modules? Brian Forney From philh at comuno.freeserve.co.uk Sat Mar 23 13:29:58 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 23 Mar 2002 18:29:58 +0000 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: >On Fri, Mar 22, 2002 at 02:59:15PM -0500, Barry A. Warsaw wrote: >> >> To maintain www.python.org, we use a web page templating system called >> `ht2html', which transforms .ht template files into .html files. Is the source for this available? -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From metaliu at yahoo.com Mon Mar 25 13:58:53 2002 From: metaliu at yahoo.com (Bill) Date: Mon, 25 Mar 2002 10:58:53 -0800 Subject: reading in ints from binary files Message-ID: Quick Newb question: How do I read in integers from binary files? readlines() reads returns the data in as a string. I can manipulate the string to get the desired result. However, is there an easier way of doing this? I currently do something like: f=open('file', 'rb') s = f.readline() l = list(s[0:-1]) l.reverse() a = array.array('h', ''.join(l)) There's gotta be an easier way. Thanks in advance, Bill From niemeyer at conectiva.com Wed Mar 20 07:10:22 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Wed, 20 Mar 2002 09:10:22 -0300 Subject: classes for fun and newbies In-Reply-To: <0c0601c1d002$26eef0f0$5102020a@graphnet.com> References: <0c0601c1d002$26eef0f0$5102020a@graphnet.com> Message-ID: <20020320091021.A19383@ibook.distro.conectiva> Bruce, > class call_record: > def __init__(self, record=''): > self.record_id=record[0:5] > self.date=record[6:11] [...] > print call_record.record_id(log[1]) Isn't it call_record(log[1]).record_id? If you're going to access many fields, you should probably save this instance in a temp variable (e.g. rec = call_record(log[1])) to avoid parsing it every time. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From mwh at python.net Tue Mar 5 05:24:25 2002 From: mwh at python.net (Michael Hudson) Date: Tue, 5 Mar 2002 10:24:25 GMT Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: Alberto Griggio writes: > #include > #include > #include > #include > > int main(void) > { > double d; > errno = 0; > d = pow(1e-200, 2); > if(!errno) printf("OK: %f\n", d); > else printf("Error: %d, %s\n", errno, strerror(errno)); > return errno; > } > > prints: Error: 34, Numerical result out of range Fun fun fun: [mwh at starship foo]$ gcc alberto.c /tmp/cce0jzts.o: In function `main': /tmp/cce0jzts.o(.text+0x27): undefined reference to `pow' collect2: ld returned 1 exit status [mwh at starship foo]$ gcc alberto.c -lm [mwh at starship foo]$ ./a.out Error: 34, Numerical result out of range [mwh at starship foo]$ gcc alberto.c -lm -lieee [mwh at starship foo]$ ./a.out OK: 0.000000 [mwh at starship foo]$ gcc -O9 alberto.c -lm [mwh at starship foo]$ ./a.out OK: 0.000000 [mwh at starship foo]$ gcc -O9 alberto.c [mwh at starship foo]$ ./a.out OK: 0.000000 When you use "-O9" I think gcc uses the fpu more directly. Words are failing me. Cheers, M. -- 6. Symmetry is a complexity-reducing concept (co-routines include subroutines); seek it everywhere. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From sab at freeuk.com Tue Mar 26 15:59:48 2002 From: sab at freeuk.com (G. Willoughby) Date: Tue, 26 Mar 2002 20:59:48 -0000 Subject: PIL and saved images coming out all garbled? Message-ID: Hi, i have a problem with saved images coming out all garbled when i use PIL. this is the code i am using: [snip] self.currentImage=Image.open("mapper/thumbnail.jpg") self.currentPhotoImage=ImageTk.PhotoImage(self.currentImage) self.mapImage=self.thumbnail.create_image(0, 0, image=self.currentPhotoImage, anchor=NW) [/snip] [snip] def saveImage(self): try: if self.currentImage: savePath=tkFileDialog.asksaveasfile(title="Save", filetypes=[("Jpeg File", ".jpg")], defaultextension=".jpg", initialdir="C:\windows\desktop") if savePath: Image.open("mapper/thumbnail.jpg").save(savePath, "JPEG", quality=100) except AttributeError: pass [/snip] and every time i use the save function the image is all multicoloured and garbled. is this because i have already opened it with the first section of code? is there a nicer/proper way? Thanks, G. Willoughby From philh at comuno.freeserve.co.uk Sat Mar 9 08:00:13 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 9 Mar 2002 13:00:13 +0000 Subject: instantiating a class References: <3c899c2d@news.cc.umr.edu> Message-ID: On Fri, 8 Mar 2002 23:23:08 -0600, Carl wrote: >I'm an intermediate-level python programmer and use classes all the time, >but a weird problem is frustrating me. > >In my main program: > > >import lj_connect > >blah blah code > >talkserver = lj_connect.lj_connect(userinfo) > > >the start of lj_connect.py is this: > >class lj_connect: > def __init__(self,basic_data): > self.uinfo = basic_data > > >I'm getting an AttributeError saying module lj_connect has no attribute >lj_connect. Originally the lj_connect code was in the same file as the main >program until I moved it for readability's sake. Can anyone see a problem? >Thank so much! What i would start with is renaming one of your lj_connect's. Then you'd know which one it is complaining about. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From inerte at hotmail.com Thu Mar 7 10:20:13 2002 From: inerte at hotmail.com (Julio Nobrega) Date: 7 Mar 2002 07:20:13 -0800 Subject: Web scripting with Python (My 2nd post!) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: <40c3f5da.0203070720.6ca52e4@posting.google.com> Hi all! Many thanks for the answers. Here are mine :-) > Do you want to *write* a Weblog-like > system, or just *use* one? Kuchling, both. I *need* one, and I will *write* one :-) It's not really a necessity, it's for personal, although with commercial interests, although for the second time, open source, use. I browsed Slashdot and Kuro5hin too much to understand where the flaws are. OKAY, OKAY! Put your weapon down, slowly.. Let me explain: /. and K5 are both Open Source source projects, and there are literally dozens of PHP weblogs. But, they are grounded a mentallity that I don't like (the 'webmasters'/'editors' are the center of the universe). IMHO they are not much user friendly, or community oriented enough for *my needs* (not to start a flame, please! ;-) I will not cannibalize none of their ideas, I mean, just a certain amount. Specifically the 'geek' focused news part. So Andy, that's why I want to reinvent the wheel. First, I want to learn Python. Second, I don't think there's a system with the infrastructure I need/will develop. Balanced, I will start from scratch. Peter, how about PL, PL-SQL or Procedural? :-) (I admit. I cheated. Hail Google!) Jon, Max, Skip, 99miles and Dave. Thanks for the links and tips. I will look at them all. Julio Nobrega. From grante at visi.com Wed Mar 13 17:21:16 2002 From: grante at visi.com (Grant Edwards) Date: Wed, 13 Mar 2002 22:21:16 GMT Subject: Python 2.2 license question Message-ID: I would like to distribute a "binary" Win32 app that includes python22.dll. The license for 2.2 states: 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 2.2 alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001 Python Software Foundation; All Rights Reserved" are retained in Python 2.2 alone or in any derivative version prepared by Licensee. The file python22.dll contains the copyright notice stibulated above, but it doesn't contain the license agreement. Therefore, I need to include a seperate text file (presumably a copy of LICENSE.TXT) in the distribution, correct? -- Grant Edwards grante Yow! YOU'D cry too if it at happened to YOU!! visi.com From ocipiere at club-internet.fr Wed Mar 13 15:44:06 2002 From: ocipiere at club-internet.fr (Olivier Cipière) Date: Wed, 13 Mar 2002 20:44:06 +0000 (UTC) Subject: Import of strop module in C program with Python2.2 on AIX4.3.3 issues a segmentation fault Message-ID: <772bce2a8686e067a36741da6f2d2fb4.77610@mygate.mailgate.org> Hi all, Here is a problem I encounter with Python 2.2 on AIX 4.3.3 : The import of strop module or strop dependants modules in a C program issues a segmentation fault, even though it seems to work alright when performing import from the python prompt. Does anybody have already encountered this problem or have a solution ?? Best regards, Olivier Cipi?re. Below is the simple test program we use : PYTHONPATH=/tools/python2.2.debug/lib/python2.2:/tools/python2.2.debug/lib/python2.2/lib-tk:/tools/xmlproc0.70:/tools/doctemplate2.2.1:/tools/python2.2.debug/lib/python2.2/plat-aix4:/tools/python2.2.debug/lib/python2.2/lib-dynload:/tools/python2.2.debug/lib/python2.2/site-packages test program : ------------------- #include #include int main(int i__argc,char* i__argv[]) { Py_Initialize(); cout << endl << "CALL of PyImport_ImportModule with argument " << getenv("NAME_MODULE") << endl; PyObject * l__obj = PyImport_ImportModule(getenv("NAME_MODULE")); if (l__obj == NULL) cout << "importation of module " << getenv("NAME_MODULE") << " failed !" << endl; return 1; } We ran this test program for different values of $NAME_MODULE. $NAME_MODULE | result? ------------------------------------------------------------- base64 | KO (Segmentation fault) at the call of PyImport_ImportModule os | OK strop | KO (Segmentation fault) at the call of PyImport_ImportModule string | KO (Segmentation fault) at the call of PyImport_ImportModule What do we see with dbx (Python 2.2 is compiled in debug mode)? ------------------------------------- The last instructions in the stack are : stropmodule.split_whitespace(s = "strop", len = 806723600, maxsplit = 806727672), line 80 in "stropmodule.c" initstrop(), line 1221 in "stropmodule.c" _PyImport_LoadDynamicModule(0x2ff1d2b0, 0x2ff1cdc0, 0xf0004d40), line 53 in "importdl.c" with 0x2ff1d2b0 = "strop" 0x2ff1cdc0 = "/tools/python2.2.debug/lib/python2.2/lib-dynload/strop.so" -- Posted via Mailgate.ORG Server - http://www.Mailgate.ORG From martin at v.loewis.de Sun Mar 10 05:18:12 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 10 Mar 2002 11:18:12 +0100 Subject: httplib question In-Reply-To: <00c101c1c7be$058e73a0$9865fea9@bigdaddy> References: <00c101c1c7be$058e73a0$9865fea9@bigdaddy> Message-ID: "David McInnis" writes: > I am on a Win2k machine (I have access to a linux box too). Where can I > learn how to activate the SSL Support at compile time? I did not see > this option when I installed (I used the windows installer). That explains it: the SSL support is not available on Windows. Regards, Martin From ronny at cs.kun.nl Tue Mar 5 04:19:58 2002 From: ronny at cs.kun.nl (Ronny Wichers Schreur) Date: Tue, 05 Mar 2002 10:19:58 +0100 Subject: Python isn't necessarily slow References: <3C833D19.3A0EBD5A@kfunigraz.ac.at> Message-ID: <3C848DBE.CEF2A2F7@cs.kun.nl> Siegfried Gonzi wrote (in comp.lang.python): > After my nightmare using Clean [..] [Clean] is a useless big > pile of shit! [..] Clean's array-type-system is an impudent > scandal for its own As one of the Clean developers, I'm sorry to read that you're frustrated with our language. I believe that you should use the right tools for the right job. This depends on the job, but also on your own preference. Judging from your comments you seem more at ease with a language that's not statically typed and that doesn't enforce referential transparency. Maybe Python with NumPy is the right choice for your job and you could even use functional programming techniques in Python. One serious objection to your Clean program. The implementation of CharPosInString and ConvertStringtoString_List are both quadratic in the number of columns in each row. CharPosInString because of the call to filter in each iteration and ConvertStringtoString_List because of the calls to length and (!!) (list subscription). Both functions should run in linear time, for example CharPosInString:: !Char !String -> [Int] CharPosInString char string = [i \\ c <-: string & i <- [0..] | c == char] ConvertStringtoString_List:: !String ![Int] -> [String] ConvertStringtoString_List string list = [string % (start+1, stop-1) \\ start <- list & stop <- tl list] (also remove the 0 (initial accumulator) in the calls). This modification should improve the running time with a factor ten or so. Happy hacking. Ronny Wichers Schreur From tismer at tismer.com Tue Mar 5 06:29:36 2002 From: tismer at tismer.com (Christian Tismer) Date: Tue, 05 Mar 2002 12:29:36 +0100 Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> <7xzo1om5wt.fsf@ruckus.brouhaha.com> Message-ID: <3C84AC20.7070103@tismer.com> Just van Rossum wrote: > In article , > Christian Tismer wrote: > > >>Paul Rubin wrote: >> >> >>>Do you think it's feasible to modify Python to use non-blocking i/o >>>everywhere, and then simulate blocking in Stackless? I.e. when a >>>microthread does an i/o operation, Python would start the operation >>>asynchronously, and the Stackless microthread scheduler would block >>>the microthread til the i/o operation actually completes (detected >>>using select or SIGIO). >>> >> >>This is roughly how I understood Frederic's idea. I was wrong: I did understand Frederic's, but was too quick with Paul's. :-) > This is not at all how I understood Frederic's idea... I thought his > idea was about using os threads for C calls (such as I/O), so you could > simply use blocking sockets as they will be run in an OS thread. With > non-blocking sockets you can indeed get a long way avoiding OS threads > completely, while still presenting a blocking interface, which is what > Paul means. It's not a complete solution, though, eg on windows file > system files don't work with select and you haven't solved the problem > of microthreads blocking when calling a C extension. And _that's_ the > area where Frederic's idea would shine, not so much I/O. I agree mostly. In the last sentence, I don't understand how working with windows files can be something different than an I/O problem?. Both approaches make sense to me. On systems with no threads at all, we have only one choice, Paul's, unless we code something thread-alike for the specific platform. When real threads are available, the other is more powerful. BTW., your Mac OsX Power PC Stackless is in CVS. cheers - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Kaunstr. 26 : *Starship* http://starship.python.net/ 14163 Berlin : PGP key -> http://wwwkeys.pgp.net/ PGP Fingerprint E182 71C7 1A9D 66E9 9D15 D3CC D4D7 93E2 1FAE F6DF where do you want to jump today? http://www.stackless.com/ From peter at engcorp.com Mon Mar 25 19:15:44 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 19:15:44 -0500 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> Message-ID: <3C9FBDB0.7E0BCA16@engcorp.com> [Various people wrote] > >>> Is the source for this available? > >> > >>It's in the CVS. > > > >Is it very new? I've got a cvs copy a few weeks old, and it's not there. > > Try http://ht2html.sf.net I may be more confused than average, but if I was I guess there might be others in the same boat. When I went to that site I got a simple page with a context menu down the left, link's to Barry's home page in several places, and a few example .ht files. No sign of source. At first... Now that someone has pointed us there repeatedly, but without much explanation, I figured it had to be me, not the site. Now I notice the "ht2html at SourceForge" link in the upper right (hidden in plain sight -- the old purloined letter trick!), which leads you to the real repository. And from there you have to click on the little "CVS" link, and if you want to browse via the web you then have to click on "Browse CVS repository". *Then* you can see the danged .py files everyone is probably looking for. Maybe there's a more direct route, but I didn't see it. Maybe it's just the ones who already knew how to do this, who knew how to do this.... ;-) -Peter From jadestar at idiom.com Thu Mar 14 21:09:27 2002 From: jadestar at idiom.com (James T. Dennis) Date: 15 Mar 2002 02:09:27 GMT Subject: Setting UNIX environment with a Python script References: <3C8D143A.17963385@all.com> Message-ID: Cameron Hutchison wrote: > On Tue, 12 Mar 2002 13:25:57 +1100, Grant Edwards wrote: >> In article , Cameron >> Hutchison wrote: >>> What you need to do instead is have your python program print on stdout >>> the name of the ora_env file to source. Then you invoke your python >>> script from your shell login script like this (bourne style shell >>> assumed): >>> eval "source ora_env.`get_ora_name`" >> Another common method is to have your Python program write the shell >> commands to stdout, then execute them with something like >> eval `myPythonProgram` > While that would work fine, I dont think it's a terribly good idea. I > think it would be cleaner to keep the shell syntax in a shell script and > avoid having the python program assume the scripting environment it is > returning to. Having "myPythonProgram" implemented in ANY language (including in ANY shell) makes exactly the same assumptions: to wit: FOO=BAR assigns shell variables and either export (Bourne & family) or setenv (csh/tcsh) exports them into the environment. *ANY* program or script that is intended to be invoked under eval `....` will have to make those assumptions. So the choice of implementation for `foo` is not constrained by the shell under which it is run (once could offer a command line argument to support alternative shells: eval `foo -s csh` for example). Since it's not constrained by this; it should logically be chosen on other criteria, such as SUITABILITY TO THE JOB AT HAND! (Doh!) If the OP feels that the parsing and processing that he or she requires is best done in Python, then Python is just as good at printing "FOO=BAR" and "export FOO" (Bourne, et al) or "set FOO=BAR" and "setenv FOO" (csh) as any other language. From usenet at thinkspot.net Sun Mar 17 03:35:43 2002 From: usenet at thinkspot.net (Sheila King) Date: Sun, 17 Mar 2002 00:35:43 -0800 Subject: Where to download bugfix for email Module? Message-ID: In this message: http://groups.google.com/groups?as_umsgid=mailman.1014298776.15692.python-list%40python.org Oleg Broytman writes that the following error message: File "/usr/local/lib/python2.2/email/Message.py", line 214, in get name = name.lower() AttributeError: 'int' object has no attribute 'lower' which was a bug in the email module, has been fixed and one should download the "latest code from mimelib.sf.net". However, I can't figure out where this latest code is or how to download it. When I go to mimelib.sf.net, I get a somewhat broken page of the email module docs. And I see no links to download files. When I go to the CVS for Python at SourceForge.net, and look at the email module files, I'm not sure which files, if any, I should download. There is something that is only 13 days old, there. But the rest of the stuff is at least 3 months old. So, I'm not convinced this is the correct place to get the patch, either. Could someone be VERY specific and tell me exactly where to go and how to get this patch? I really need it for stuff I'm working on. Thanks, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From nhodgson at bigpond.net.au Tue Mar 12 15:56:34 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 12 Mar 2002 20:56:34 GMT Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> <3C8E44C6.E89FF302@ccvcorp.com> Message-ID: <6Ytj8.10726$mp.48831@news-server.bigpond.net.au> In my experience writing a lexer for Perl (for use in syntax styling editors), 'here documents' and arbitrary quote sequences add much complexity to a lexer. The full generality of stacked here documents is a real pain to deal with: print <<"foo", <<"foo"; # you can stack them I said foo. foo I said bar. foo Neil From python at rcn.com Sun Mar 31 20:20:52 2002 From: python at rcn.com (Raymond Hettinger) Date: Sun, 31 Mar 2002 20:20:52 -0500 Subject: New-style exceptions? References: Message-ID: "Aahz" wrote in message > Magnus Lie Hetland wrote: > > > >Is there a reason why new-style objects can't be used in the raise > >statement? > > Because that's the way it currently works. Inherit from Exception and > Bob's your uncle. Is there a reason why Exception can't be defined to inherit from 'object' so that Uncle Bob does the right thing? Raymond Hettinger, CPA From a.clarke11 at pop.ntlworld.com Wed Mar 27 07:31:16 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Wed, 27 Mar 2002 12:31:16 +0000 Subject: Why does this work? Message-ID: <3CA1BB93.FC00D40D@pop.ntlworld.com> Hi I defined a class, and made an instance. The class sis not have a def__init__() line. In the class, I defined a function f(x) and an list object X.tiles. Why can I later call instancename.f, and instancename.tiles? I thought the class had to have a def__init__() line in it for this to work? I would be glad if somebody could spell this out for me, although it is working perfectly well in the finished program! The relevant code is: class Player: import random Tiles=[] Sound="click" Win="yippee" playlist=[] def chooseTiles(x): import random random.shuffle(Setup.r) x.Tiles=[] while len(x.Tiles)<7: l=0 l=Setup.r.pop(random.uniform(1,len(Setup.r))) x.Tiles.append(l) x.Tiles.sort() playstring=[] Porky=Player() Porky.chooseTiles() Thanks in anticipation Tony From pedronis at bluewin.ch Tue Mar 12 22:44:59 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 13 Mar 2002 04:44:59 +0100 Subject: Has Mark Hammond attained pariah status yet? References: <3C8E7E90.6000608@skippinet.com.au> Message-ID: <3c8ece4a_3@news.bluewin.ch> I'm sorry. My issues were mainly with the article, I'm aware that an amount of misquotation happens. Mark Hammond wrote in message 3C8E7E90.6000608 at skippinet.com.au... > From my POV, any publicity is good publicity. I disagree with this POV, but YMMV. You're playing with fire . regards, Samuele Pedroni. From manish_ssharma at yahoo.com Wed Mar 13 05:31:19 2002 From: manish_ssharma at yahoo.com (Manish Sharma) Date: Wed, 13 Mar 2002 02:31:19 -0800 (PST) Subject: load_site.py error Message-ID: <20020313103119.20866.qmail@web13603.mail.yahoo.com> I want to upload some files in zope using load_site.py While running the command in python i m getting the error Syntex error : invalid token the command statement is >>> python .\load_site.py -u manish:manishkumar -D http:localhost:8080/test/ /tests/ here test is a folder created in zope manager and tests is come with Load_site kit having three .htm files. i tried wxLoadSite.py through python >>> python .\wxLoadSite.py it also giving the same error of invalid token if i will use >>> python ./wxLoadSite.py it will give error Syntex Error : invalid syntax please tell me the solution...... manish --------------------------------- Do You Yahoo!? Try FREE Yahoo! Mail - the world's greatest free email! -------------- next part -------------- An HTML attachment was scrubbed... URL: From oliver.pust at web.de Wed Mar 20 06:57:54 2002 From: oliver.pust at web.de (Oliver Pust) Date: Wed, 20 Mar 2002 12:57:54 +0100 Subject: module for assessing gray levels of gray level bitmap? Message-ID: <3C987942.9060309@web.de> Hi, is there a module for assessing the gray levels of gray level bitmap? I am thinking of a module that allows to open a bmp-file and stores the gray levels of each pixel in form of a matrix e.g. gray_level[x,y]. All the best, Oliver From sandskyfly at hotmail.com Fri Mar 15 06:02:38 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 15 Mar 2002 03:02:38 -0800 Subject: psyco, jython, and python speed tests Message-ID: Hi, I wanted to repeat Amund Tveit's simple speed tests of jython and python (see: http://sourceforge.net/mailarchive/message.php?msg_id=705994), and place them alongside results from Armin Rigo's python optimizing compiler, psyco. Here are my results for your interest: METHOD: ------ I ran pystone once with a 1000,000 iterations setting (pretty much duplicating what Amund did). CONFIG: ------ Dell 8100 laptop, windoze XP, PIII-700, 512 MB ram, jdk1.4: TEST RESULTS: ------------ (in decreasing order of performance) psyco 0.4 (cpython22 running psycoized pystone) Pystone(1.1) time for 1000000 passes = 16.1721 This machine benchmarks at 61834.8 pystones/second jython21 (with -server jvm setting)* Pystone(1.1) time for 1000000 passes = 41.739 This machine benchmarks at 23958.4 pystones/second cpython22 (with -O optimization setting) Pystone(1.1) time for 1000000 passes = 55.4291 This machine benchmarks at 18041.1 pystones/second cpython2.1.2 (with -O optimization setting) Pystone(1.1) time for 1000000 passes = 57.1236 This machine benchmarks at 17505.9 pystones/second cpython22 (default) Pystone(1.1) time for 1000000 passes = 61.3202 This machine benchmarks at 16307.8 pystones/second cpython2.1.2 (default) Pystone(1.1) time for 1000000 passes = 61.7983 This machine benchmarks at 16181.7 pystones/second jython21 (default hotspot jvm) Pystone(1.1) time for 1000000 passes = 108.046 This machine benchmarks at 9255.32 pystones/second * my particular command for running jython21 (with -server setting) follows from Amund's posting (one line, yours may be different): "C:\Engines\j2sdk\jre\bin\java.exe" -server -Xmx200m "-Dpython.home=C:\Engines\jython21" -classpath "C:\Engines\jython21\jython.jar;%CLASSPATH%" org.python.util.jython pystone.py SIDE BY SIDE: ------------ (1000,000 pystone iterations) pystones pystones/sec secs /sec relative to cpy22 psyco0.4 16.1721 61834.8 3.79 jython21S 41.739 23958.4 1.47 cpython22O 55.4291 18041.1 1.11 cpython212O 57.1236 17505.9 1.07 cpython22 61.3202 16307.8 1 cpython212 61.7983 16181.7 0.99 jython21 108.046 9255.32 0.57 MY COMMENTS: -------------- o psyco rocks. o jython's no spring chicken for long running processes (with the right JVM setting of course) but is relatively slow otherwise. o Turning on the optimization _does_ extract small but definite performance enhancements from your python interpreter. o I'm already more than happy with the everyday performance of python22, but I'm also happy that people are looking into the performance 'problem'... even though, at least in my case, almost all the times I've personally found that an app was running slowly, it was due to a mistake in the code, and careful redesign fixed it without having to revert to extension writing. o Sometimes, it's nice to think I have performance problems, so I can go through the exercise of writing python extensions (another learning experience) o Developments like psyco should be encouraged and supported because ultimately accelerating python is a good thing: it takes away one usual criticism of those who have _never tried_ to develop in python. For those who have, the productivity benefits, of course, by far outweigh any so-called 'performance' issues. I don't advise you to read too much into these results as the tests were only run once for each configuration, and, of course, for all the other typical reasons one has against benchmarking. ciao, Sandy From aahz at pythoncraft.com Wed Mar 27 13:44:26 2002 From: aahz at pythoncraft.com (Aahz) Date: 27 Mar 2002 13:44:26 -0500 Subject: urllib threads? References: <92994965.0203270818.500f3665@posting.google.com> Message-ID: In article <92994965.0203270818.500f3665 at posting.google.com>, Andres Jaime wrote: > >does anyone have any insight into this problem (issues with urllib and >multithreading, etc) I suggest that you swipe my threaded retrieve code from my home page, test it to verify for own satisfaction that it works correctly, and then progressively modify it until it does what you want. If you hit a failure point in the middle of this process, that should make pinpointing the problem easier. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From tejarex at yahoo.com Sun Mar 31 20:40:39 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Mon, 01 Apr 2002 01:40:39 GMT Subject: PEP 285: Adding a bool type References: Message-ID: "Tim Peters" wrote in message news:mailman.1017602330.26032.python-list at python.org... > [Aahz] > > But what do you think of changing bool() to truth()? > > Whatever Guido tells me to think . Before then, I think "bool" > usually reads better, as it's less a strain to use as either adjective or > noun. Contrast, e.g., > > isatty returns bool > isatty returns a bool > isatty returns a bool value > > with > > isatty returns truth I call this a tie, though I really might lean towards 'truth' here (but maybe not). > isatty returns a truth I admit 'bool' wins here. > isatty returns a truth value I think 'truth' wins this one. Try this quiz on someone less familiar with 'bool' than we are. > After reading "isatty returns a truth", I'm left wondering which specific > truth it returns, and whether I'd agree with it . > > Strangely enough, even today: > > >>> print os.isatty.__doc__ > isatty(fd) -> Boolean > Return true if the file descriptor 'fd' is an open file descriptor > connected to the slave end of a terminal. > >>> > > isatty(fd) -> truth > > doesn't read poorly, though. Agreed ;<) My proposal has two parts: do not use 'bool'; do use 'truth' (or possibly something else such as 'binary' or even 'tval'). I am curious what you think of the four reasons I gave. I am specifically curious whether you will volunteer to anwer a multiyear stream (already started) of questions about why Python truth values, being called bool, do not act 'properly' as bools 'should' and suggestion that they 'ought' to be restricted (crippled) so that they do. For some (many? most?) people, it's obvious now, 'Boolean' and its derivative 'bool' have a definite and restricted usage that excludes Python truth values current and proposed. Perhaps we should honor that usage and use something either more general or more specific to Python. Otherwise, we had bettter say pretty clearly that Python bool is not Boolean and that one should think of it as a type with dual inheritance from both int and (abstract, not implemented) Boolean. (And expect that people will be mislead anyway.) Terry J. Reedy From jimmy at retzlaff.com Sun Mar 3 07:04:32 2002 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Sun, 3 Mar 2002 04:04:32 -0800 Subject: Twain Scanners and some other questions Message-ID: dix wrote: > I need to know if there is a free library for Python to manage Twain > scanners in order to pilot the scanner and have an image representation > of the paper document. The wonderful Daily Python-URL (http://www.pythonware.com/daily) just pointed to http://twainmodule.sourceforge.net a few days ago. Searching Google for the words Python and Twain (http://www.google.com/search?q=python+twain) yields both of these sites. A similar approach may help answer your other questions. Jimmy From aahz at panix.com Sat Mar 9 08:43:45 2002 From: aahz at panix.com (Aahz Maruch) Date: 9 Mar 2002 05:43:45 -0800 Subject: PEP 2, Procedure for Adding New Modules References: Message-ID: In article , Martijn Faassen wrote: > > New functionality is commonly added to the library in the form of > new modules. This PEP will describe the procedure for the > _addition_ of new modules. PEP 4 deals with procedures for > deprecation of modules; the _removal_ of old and unused modules > from the standard library. Finally there is also the issue of > _changing_ existing modules to make the picture of library > evolution complete. PEP 3 and 5 give some guidelines on this. The > continued maintenance of existing modules is an integral part of > the decision on whether to add a new module to the standard > library. Therefore, this PEP also introduces concepts > (integrators, maintainers) relevant to the maintenance issue. The maintainers also possess primary responsibility for determining whether bugfixes should be backported to previous Python releases as discussed in PEP 6. >Maintainer(s) > > All contributions to the standard library need one or more > maintainers. This can be an individual, but frequently is a group > of people such as for instance the XML-SIG. Groups may subdivide > maintenance tasks among themselves. One ore more maintainers shall x > be the _head maintainer_ (usually this is also the main > developer). Head maintainers are convenient people the integrators > can address if they want to resolve specific issues, such as the > ones detailed later in this document. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From adina_levin at mindspring.com Mon Mar 25 21:26:30 2002 From: adina_levin at mindspring.com (adina_levin at mindspring.com) Date: Mon, 25 Mar 2002 20:26:30 -0600 Subject: Question: recursion and scope References: Message-ID: Thank you very much, Terry. That worked. All I needed was the (return max(self.right.howdeep(depth)),(self.left.howdeep(depth))) (as adapted for my implementation). I still have a counter, which works successfully for any one side of the tree (though your version is nicer). Why does this version work? Why does the counter successfully keep count in the recursion on one side of the tree, but lose count across sides of the tree? What scope principle, recursion concept, or logical step am I missing? - Adina Terry wrote: > > Perhaps you want something like the following (untested, adjust for > your tree implementation): > > def maxdepth(tree): > if leaf(tree): return 1 > elif onlyleftchild(tree): return maxdepth(leftchild) + 1 > elif onlyritechild(tree): return maxdepth(ritechild) + 1 > else return max(maxdepth(leftchild), maxdepth(ritechild)) + 1 > > If you want to simultaneously count nodes, then you must return a > tuple of (count,depth) and add a bit more calculation machinery. > > Terry J. Reedy Adina wrote: > > Hello, Pythonistas. > > > > I am attempting to teach myself some basic computer programming > concepts > > using Python. > > > > I'm currently extending the recursive binary tree program in > Programming > > Python to traverse the tree and count its depth. The program > successfully > > traverses the tree and counts the number of nodes. > > > > So far, though I haven't figured out how to calculate the "maximum > depth" of > > the tree without declaring "maxdepth" as a global variable. > > > > If maxdepth is declared as a local variable within the recursive > method, it > > gets re-set for each subtree. > > > > What am I missing? > > From brian at sweetapp.com Wed Mar 27 17:52:20 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 27 Mar 2002 14:52:20 -0800 Subject: unicode experiments + questions In-Reply-To: Message-ID: <000801c1d5e2$0d85c400$445d4540@Dell2> Irmen de Jong wrote: > So I'm using the unicode escape char syntax, but that is cumbersome > (where do I look up all my special characters?) and hard on the eyes. Python 2.2 does not attempt to interpret bytes in string literals. So you can embed non-ASCII characters in them if you want. You can look up Unicode ordinals at http://www.unicode.org/charts/. Or you can just use this code: >>> ord(''.encode('')) > I also have the following question: > what exactly happens when I type "print u" in Python, where u > is a unicode string? for example; > > >>> e=u'\u20ac' > >>> e > u'\u20ac' > >>> print e > ? (<--- this is an Euro symbol on my screen) Is this what actually happens? Did you change your default encoding to be something other than ASCII, possible by modifying site.py? > What charset does the print convert to? > I'm on Win2000, so when I type > >>> print e.encode('cp1252') > I get the Euro symbol. Does print automatically convert to the windows > charset cp1252? The print does not do any conversion; it just sends bytes to the output stream. > How does Python know this charset, because in my syte.py encoding="iso- > 8859-15". Ahah! You did some customization. I think that it is better style to leave the default encoding as ASCII and call encode/unicode explicitly. > When I type > >>> print e.encode('iso-8859-15') > I don't see the Euro symbol, but some other weird symbol. As you should, it your system does not use ISO-8859-15. > > For your interest, below is the test program I'm using to generate > different encoded documents. > Interestingly enough, UTF-7 is not understood by Opera 6. IE 5 and Mozilla > get it right. I've never seen an HTML document encoded in UTF-7, so this doesn't surprise me. Cheers, Brian From garys at ihug.com.au Sun Mar 31 16:22:36 2002 From: garys at ihug.com.au (Gary Stephenson) Date: Mon, 1 Apr 2002 07:22:36 +1000 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: "phil hunt" wrote in message news:slrnaacavs.2gs.philh at comuno.freeserve.co.uk... > On 30 Mar 2002 11:04:13 -0500, Andrew Koenig wrote: > > > >I wonder if this is the circle-ellipse problem over again? > > What is the circle-ellipse problem? One way of expressing the problem is that whilst you and I readily understand that a rectangle with equal width and height is most definitely a square, or that an ellipse with equal chords is in fact a circle, our OO type systems, in general, do not and cannot. Date and Darwen discuss this issue extensively in their 3rd Manifesto tome [1], and they opine that a "real" OO type system should automatically promote a "square rectangle" to an actual square instance (assuming of course, that a "square" class has been defined as an heir of rectangle with the appropriate constraint). They call this feature "Specialisation by Constraint". Personally, whilst I find their arguments most interesting and persuasive, it would appear to my neophyte eye that actually implementing such a system might prove even more problematic than trying to trying to satisfy all twelve of Codd's rules at once! (which in turn has proven to be marginally more difficult than lifting yourself up by your own bootlaces ). cheers gary [1] - http://www.amazon.com/exec/obidos/ASIN/0201709287/ref=pd_sim_books/002-59731 48-1843226 From edream at tds.net Fri Mar 8 18:50:04 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 08 Mar 2002 23:50:04 GMT Subject: PEP 282: A Logging System -- comments please References: Message-ID: <3C894E28.BB2CCE7B@tds.net> PEP 282 is more complex and less flexible than it could be. Instead, Python's standard logging system could well use dynamic tracing. Consider a tracing function with two arguments, a "tracepoint" string and a message (or function to execute). By default, the trace function uses the name of the method from which trace was called as the tracepoint string, so, def foo(): trace("abc") is the same as: def foo(): trace("foo","abc") This trace prints "foo:abc" only if tracing for "foo" is enabled. trace(f) executes f() if "foo" is enabled. Extending this scheme is easy. The app (or tracing object) maintains a dict of enabled tracepoint names. The user can add or delete entries in the dict at run time. trace() supports wildcards and other special characters, so enable("*") enables all tracing, enable("level2.?") enables "level 2" tracing, trace("-foo","abc") suppresses wildcard matches for "foo", etc. Dynamic tracing is trivial to implement. More importantly, it is simpler to use and more flexible than any static scheme such as the one described in 282. PEP 282 talks about control flow, levels, loggers, handlers, formatters, filters and configuration. A case can be made for dealing with each issue, and experience shows that simple dynamic tracing suffices in complex apps like compilers and file systems. For example, all kinds of configuration (including picking formatters, data sinks, altering the flow of control of the program being run, etc.) can be done just by initializing the dict of tracepoint names. Dynamic tracing provides the essential benefit of any logging system, namely the ability to alter tracing output without altering the program being traced. It does so in the simplest and most general way. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From bokr at oz.net Tue Mar 12 17:36:56 2002 From: bokr at oz.net (Bengt Richter) Date: 12 Mar 2002 22:36:56 GMT Subject: doctest Hassles! References: <10d46bdc.0203120928.7e9c708b@posting.google.com> Message-ID: On 12 Mar 2002 21:56:20 GMT, bokr at oz.net (Bengt Richter) wrote: >On 12 Mar 2002 09:28:11 -0800, doug at pobox.com (Douglas Garstang) wrote: > [...] >>Now, in my code I have: >> >>def tester3(): >> """ >> >>> import os >> >>> ls=os.popen("/bin/ls","r").read() >> >>> print ls >> example.py >> example.pyc >> tester.py >> >> """ >> >>It ignores the blank line at the end, as the docs say it will. On a > ^^--what ignores what blank line? There's no executable code above. Well, at least not directly, sorry ;-/ Regards, Bengt Richter From i.linkweiler at gmx.de Tue Mar 26 19:03:00 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Wed, 27 Mar 2002 01:03:00 +0100 Subject: Python vs. C/C++/Java: quantitative data ? References: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> Message-ID: <3CA10C34.A27D5597@gmx.de> I?m writing a diploma paper on rapid prototyping and python at education. I am interested in your experiences with python, too, including the time you needed to learn python. - Do YOU think, it is more easy to learn python than perl, java or C++ or ..... ? - What do you think about the syntax of Python? Is it easy to use, or do you have any problems with it? - Is here anybody who learned Python as first language? - Where do you see disadvantages of Python? Ingo From joonas at olen.to Thu Mar 28 02:37:14 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Thu, 28 Mar 2002 09:37:14 +0200 Subject: Image in a module question References: Message-ID: <3CA2C82A.B33B25BF@olen.to> Christopher wrote: > > A while back, I remember somebody mentioning a way to store image data > in a Python module. This is something I think I could really use (I > want to incorporate an image into an frozen exe that I am writing for > my coworkers). I would like to keep the installation nice and neat > (--onefile) and I figure the easiest way is to store the image in a > module, import it, then use the string (I am assuming this is what you > would get from the module, I can't remember what the post sais) e.g., > > import MyImageModule > import Image, ImageTk, StringIO > > myImage = MyImageModule.MyImage # Where MyImage is the string > representing the image > > im = Image.open(StringIO.StringIO(myImage)) > # I can now use im to construct my Tkinter label/button/etc. > > I did some searches: PIL, image in module, importing images, etc. and > didn't see the post (it was a lot of pages, i may have just missed > it). If somebody remembers the post, could you point me to it (just > the date would be a huge help). Thanks a bunch, Fredrik Lundh explains exactly what you need to do in an ancient newsgroup article at http://groups.google.com/groups?selm=9705101637.AA16871%40arnold.image.ivab.se From sjmachin at lexicon.net Tue Mar 26 18:56:07 2002 From: sjmachin at lexicon.net (John Machin) Date: 26 Mar 2002 15:56:07 -0800 Subject: C API for modules References: <3CA09F43.80206@erols.com> Message-ID: "Edward C. Jones" wrote in message news:<3CA09F43.80206 at erols.com>... > Is there some simple way to call functions in modules from C? In > particular, for module struct, how do I call pack, unpack, and calcsize? > OK, I'll be the bunny and ask the obvious(?) meta-question: Give that the struct module is designed for Python callers to pack/unpack C structs (laboriously), why bother? Why not just manipulate the structs in C?? From evebill8 at hotmail.com Thu Mar 21 14:33:50 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Thu, 21 Mar 2002 19:33:50 GMT Subject: Telnet Message-ID: Hi folks, I am trying to write a telnet client program. Here is the code: ID = "123445" PASSWORD = "333" try: tn = telnetlib.Telnet() tn.read_until("Please enter your id? ") tn.write(ID+"\n") tn.read_until("Enter your password? ") tn.write(PASSWORD+"\n") print tn.read_all() tn.close() except: tn.close() print 'connection failed' tn.close() It stops after the ID was written. If I use the actual telnet client, it returns "Enter your password? " after my ID is submitted. why does not tn.read_until() find the "Enter your password? " string ? Is there any other way to handle the password prompt? Thanks in advance! Billy Ng From python at rcn.com Mon Mar 4 00:48:06 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 4 Mar 2002 00:48:06 -0500 Subject: functional programming with map() References: Message-ID: "mcherm" wrote in message news:mailman.1014747703.26001.python-list at python.org... > >> List comprehensions are declarative (no loops) and they avoid side effects > >> (no loop variables or temporaries) > > > > No side effects? Try this: > > > > L = [x for x in range(10)] > > print x > > Yeah, but that's a bug. It COULD be a feature despite its creepy-crawly, six-legged, hive-dwelling, crumb-eating nature. Hard to tell. Raymond Hettinger @ @ \_/ From rnd at onego.ru Fri Mar 8 13:13:48 2002 From: rnd at onego.ru (Roman Suzi) Date: Fri, 8 Mar 2002 21:13:48 +0300 (MSK) Subject: RFC PEP candidate: q''quoted ? In-Reply-To: Message-ID: On 4 Mar 2002, Bengt Richter wrote: >On Sun, 3 Mar 2002 14:56:45 +0300 (MSK), Roman Suzi wrote: > >>On 3 Mar 2002, Bengt Richter wrote: >> >>>Problem: How to put quotes around an arbitrary program text? >> >>Have it in a separate file. >> >That's fine in a lot of cases, but does require reliable presence >of both files. It's not so convenient if you are trying to write >e.g. a program generator and want to write out snippets containing >mixed triple quoted doc strings and data etc. Or if you are >writing copied example snips as part of dynamic HTML from CGI. >===the stuff I want=== > > >Sure, I can copy it and make a separate file, and write some code to >read the file into my snippet string, but would you actually prefer to >do it that way? Ok, I could write a class to systematize it. Maybe I >will, when I want use file-stored snippets, but I'd like both options >;-) And I guess I'd like to have Q' as well as q' ;-) Well, maybe my first impressions were wrong. After all, the feature is convenient. But probably you will need to coordinate it well with encoding things. What if "dochere"'s encoding need to be different from main program one? Are binary data allowed? Otherwise the feature will become grammatical disaster... >>Making Python as gibberish as Perl is. And all that only to >>have Windows path be written without double-\ >Not 'only'. I said 'also' ;-) Perhaps my choice of '|' delimiter triggered >your 'gibberish as Perl' detector? ;-) Maybe. I wonder why Perl novices do not know about "dochere" capabilities of Perl. Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Friday, March 08, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "People are always available for work in the past tense." _/ From eppstein at ics.uci.edu Wed Mar 6 16:37:01 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 13:37:01 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , "Roman Yakovenko" wrote: > What is about step ? > > for( int I = 0; I < 10; I+=2) > do smth The proposal doesn't address arithmetic progressions, geometric progressions, or any other type of sequence: just intervals of consecutive integers. But if you expanded your example a little: for (int l = 0; l < 10; l += 2) do smth(l) you would see that it is easy to handle it with the proposed new syntax: for 0 <= h < 5: do smth(2*h) From aahz at pythoncraft.com Sun Mar 31 09:41:28 2002 From: aahz at pythoncraft.com (Aahz) Date: 31 Mar 2002 09:41:28 -0500 Subject: Subclass sadness (was Re: [Python-Dev] PEP 285: Adding a bool type) References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> Message-ID: In article , Richard Jones wrote: >On Sun, 31 Mar 2002 15:46, Andrew Koenig wrote: >> >> The other way around -- inheriting rectangle from square -- would >> seem to make more sense because a rectangle has all the information >> that a square does, and then some. But that doesn't really work either, >> because then you can no longer assume that every kind of square is >> really a square. After all, it might be a rectangle. > >Hrm, just following this thought here, possibly for no good reason at >all (hey, it's Sunday, and daylight savings just ended so I've got a >whole _hour_ extra to waste today :)... hell, I can't even remember >what the point of the circle/ellipse comment was ;) It was pointing out that inheriting truth/bool from int carries the same sort of messiness inherent in circle/ellipse. >Surely sqaure and rectangle (and parallelogram) subclass a more >fundamental four-sided-shape (er, I can't believe it, but I've >forgotten the name for them ;)? They impose their own constraints on >the four-sided-shape, given it has side lengths and angles between the >sides. Quadrilateral and parallelogram. But that's still the same sort of problem when one subclasses, only adding more attributes. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From San at hotmail.com Sun Mar 17 23:51:36 2002 From: San at hotmail.com (San) Date: Sun, 17 Mar 2002 21:51:36 -0700 Subject: Compile.py Message-ID: <3c9570f8_1@corp-goliath.newsgroups.com> Hello, Very new to Python. "Programming on Win32" mentions David Asher's Compile.py. I've found a Compile.py in the sources \Tools\compiler folder. This script seems to be expecting arguments, and in fact I drop into the "no files to compile" case, presumably from getopt. This contrasts "Win32"'s example, where no arguments are used ( thought a setup.in and source files in the current directory are assumed). Am I using the right script, or have I totally missed something? Thanks, M.E.I. ______________________________________________________________________________ Posted Via Binaries.net = SPEED+RETENTION+COMPLETION = http://www.binaries.net From python at rcn.com Mon Mar 25 02:37:59 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 25 Mar 2002 02:37:59 -0500 Subject: list comprehension question References: <5.1.0.14.2.20020324115311.0457dbb8@202.95.131.154> Message-ID: "Tripp Scott" wrote in message news:mailman.1017031538.14132.python-list at python.org... > At 25/03/2002 07:37, brueckd at tbye.com wrote: > thanks for the tip. actually, the essence of what i wanted to > ask was: "can that SOMETHING be a list of more than one elements > which will be _flatly_ added to the result list." as another > example, can i generate this list > > [1,1 2,2,2, 3,3,3,3, 4,4] I don't see the pattern. I presume you mean: [1,1, 2,2,2, 3,3,3,3, 4,4,4,4,4 ] > > with a list comprehension that contains one 'for' clause? I think you are asking for a general purpose solution to the problem of using list comprehensions in an 'extend' rather than 'append' mode. The general purpose technique is to build it unflattened and then wrap it with 'reduce' to flatten it. Applying that general technique to your specific example is easy: >>> import operator >>> reduce(operator.add, [[i]*(i+1) for i in range(1,5)]) [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4] Hope this helps you train your pet Python, Raymond Hettinger From barry at zope.com Fri Mar 22 14:59:15 2002 From: barry at zope.com (Barry A. Warsaw) Date: Fri, 22 Mar 2002 14:59:15 -0500 Subject: ht2html project at SourceForge Message-ID: <15515.36115.281626.923961@anthem.wooz.org> To maintain www.python.org, we use a web page templating system called `ht2html', which transforms .ht template files into .html files. While the generated html pages are fairly stylized, there is some degree of flexibility in customizing the style for other sites. E.g. www.list.org, www.jython.org, tmda.sf.net, barry.wooz.org. There's been enough interest in the software for me to finally create a SourceForge project for it. Please visit http://ht2html.sf.net for more information. -Barry From agenkin at thpoon.com Thu Mar 21 03:18:18 2002 From: agenkin at thpoon.com (Arcady Genkin) Date: Thu, 21 Mar 2002 08:18:18 GMT Subject: multithreading and Tkinter Message-ID: Greetings: I have a separate thread, responsible for graphical stuff, which displays a bunch of objects as "Tkinter.Lablel"s. Then, I have a buhch of separate threads, which collect information about the objects over the network, at specified intervals. How do I signal the GUI thread that new information for a particular object has arrived? Currently I'm using after() method of the Tkinter object to update info for *all* objects every second, but that is hardly a good design, since there may be 500 of them, and the new info can be arriving once every 15 minutes. Any ideas and/or pointers to the documentation (preferably online) highly appreciated. Many thanks, -- Arcady Genkin Don't read everything you believe. From gh_pythonlist at gmx.de Sun Mar 31 20:40:23 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 03:40:23 +0200 Subject: Python/Linux In-Reply-To: References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: <20020401014023.GB333@lilith.hqd-internal> * Robert Oschler [2002-03-31 19:53 -0500]: > Heard much about Zope, not much about Don Quixote. Zope isn't only a web application framework, it's also a content-management system. But I'm really not quite sure what it really is ;-) IMO if you want to develop a web application, using a plain CGIs or a framework like Webware is easier, because they're less complex than Zope. > If I go with Zope will I miss something special as far as Quixote's > concerned? > I didn't know Zope also had a WYSIWIG editor for HTML pages. It doesn't. > Also, do I have to get Python 2.2 to use Zope 2.5? I'm surprised SUSE's > Yast2 missed that update. You can avoid potential package management trouble by downloading a Zope binary distribution and setting it up yourself. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.3 ?C Wind: 0.7 m/s From cs1spw at bath.ac.uk Tue Mar 5 07:43:10 2002 From: cs1spw at bath.ac.uk (Simon Willison) Date: Tue, 5 Mar 2002 12:43:10 GMT Subject: Problem with popen() and a regular expression Message-ID: <3C84BD5C.3050901@bath.ac.uk> I've written a simple Python script to scan a bunch of URLs for "live" sites and grab the title of those pages. It works by using popen() to call lynx and analyse the HTTP response: ----------------------------------------------------------------- command = "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~"+user+"/" f = os.popen(command) l = f.readline() # Read first line of output, the HTTP status line try: # Look for '200' HTTP status code indicating page exists i = l.index('200') except ValueError: i = 0 if i: print "Web page exists!" # Now try and get the title of the page for line in f.readlines(): line = string.strip(line) # look for * using regular expression result = re.search('\s*([^<]*)\s*', line) if result: # Found the title title = result.group(1) found[user] = title print "Page Title: " + title break if not found.has_key(user): found[user] = "[unknown]" ----------------------------------------------------------------- You can see the output of the script here: http://www.bath.ac.uk/~cs1spw/cs1sites.html As you can see, the code works fine for most pages but fails to grab the tag on some of them (resulting in an [unknown] entry in the list). I've checked the HTML for these pages and a <title> tag exists in a form that should be picked up by my regular expression, but for some reason it just doesn't work. Any ideas? From scott2237 at yahoo.com Tue Mar 12 16:52:01 2002 From: scott2237 at yahoo.com (googlePoster) Date: 12 Mar 2002 13:52:01 -0800 Subject: trouble testing for existance of variable Message-ID: <4bbaa6d6.0203121352.4358f14@posting.google.com> python gurus: if I want to know if a variable exists before testing it, what do I do? I have tried if locals().has_key("colors_name") and if globals().has_key("colors_name") and curr_color = "none" curr_color = vim.eval("colors_name") and curr_color = os.getenv("colors_name", "none") and I just can't seem to get there from here I am using python as my gvim scripting language here, python v2.2, both on NT 4.0 and win98se gvim is version 6.0 I want to do things based on the existance of colors_name, but if it's undefined I can't test it From deathtospam43423 at altavista.com Tue Mar 19 20:45:01 2002 From: deathtospam43423 at altavista.com (Flavian Hardcastle) Date: 20 Mar 2002 01:45:01 GMT Subject: Q: Sound production with python? Message-ID: Being a beginner fiddle player, as well as a beginner python programmer, I want to write a little prog that trains the sense of pitch. How envisage it working is thus... It plays a simple 4 note melody, then repeats the melody with one of the notes (selected randomly) slightly off pitch ... say by 20% or 10% or 5%. The user then has to detect which note was off. What modules and commands should I use to generate this sounds? What's the best way to go about it? -- cdewin at dingoblue.net.au From eppstein at ics.uci.edu Fri Mar 8 11:54:15 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 08 Mar 2002 08:54:15 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , philh at comuno.freeserve.co.uk (phil hunt) wrote: > Thev reasdon i don't like it is that the syntax already has a > meaning: to compare the magnitude of values. Now you are proposing > another, totally different, meaning. How is that unlike the difference in meaning between "in" in expressions and "in" in for-loops? From cliechti at gmx.net Sun Mar 31 12:18:49 2002 From: cliechti at gmx.net (Chris Liechti) Date: 31 Mar 2002 18:18:49 +0100 Subject: Possible to save router logs? References: Message-ID: Luap777 at hotmail.com (Paul) wrote in news:bbde2416.0203310724.4150665d at posting.google.com: > I have a D-Link 704 cable/DSL router. Unfortunately, it has very > limited logging capabilities(in that it doesn't save logs, it just > rights over them when the space fills.) What I would like to do is > right a program to save the logs to my hard drive every 12 hours or > so. I normally have to access the web page with the url being the > local IP of the router, then type in a password to get access to the > logs. Has anyone attempted something like this? I know this is kinda > general, but any feedback would be appreciated. It might give me an > idea of where to begin. Thank you. with the urllib module you can easily get a webpage i.e the log page of your router. you may first have to log in. for that you just have to format the HTTP GET correctly. when you find out what you browser sends to login you can mimic that with the urllib. chris -- Chris From op73418 at mail.telepac.pt Wed Mar 13 17:25:48 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 13 Mar 2002 22:25:48 +0000 Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: On Wed, 13 Mar 2002 22:23:02 +0000, Gon?alo Rodrigues wrote: >On Wed, 13 Mar 2002 13:01:13 -0800, James_Althoff at i2.com wrote: > >> >>[ruud de rooij[ >>| perhaps lists should support .keys() and .items() for those operations >>| (analogous to dictionaries). >> >>[Clark C . Evans] >>| Very nice idea. This is PEP worthy. It is nice beacuse it >>| does not introduce anything new; a list can easily be viewed >>| as a mapping having a positive integer domain. This is simple, >>| consistent, and quite elegant. >> >>I would like to see: >> .keys() >> .items() >> .iterkeys() >> .iteritems() >> >>jim >> > >The same idea should be extended to any sequence, actually. > >Gon?alo Rodrigues. In case I am misunderstood, sequence = object supporting a list-like protocol (__getitem__, etc.), not just an iterable. From martin at v.loewis.de Mon Mar 11 00:29:10 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 11 Mar 2002 06:29:10 +0100 Subject: How to disable assert statements inside a module? References: Message-ID: Tim Peters writes: > Note that assignment to __debug__ was deprecated in 2.1: > > SyntaxWarning: can not assign to __debug__ > > and removed in 2.2: > > SyntaxError: can not assign to __debug__ Of course, def foo(x): assert x globals()['__debug__'] = 0 foo(0) continues to work. Regards, Martin From whale at mycameo.com Mon Mar 4 05:12:12 2002 From: whale at mycameo.com (whale) Date: Mon, 4 Mar 2002 18:12:12 +0800 Subject: Problem with opening PCX image Message-ID: When I opened PCX images with PIL, most images work fine. However, there is one image I opened it with the same procedure, the exception occured. I can view this image with different image viewer. I am not sure how does this happen? Is this the bug existing in PIL module? I put a problematic image online at http://www.mycameo.com/download/fromQA.PCX. Please take a look at it. Thanks a lot. PythonWin 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - see 'Help/About PythonWin' for further copyright information. >> import Image >> im = Image.open("fromQA.PCX") >> im.load() Traceback (most recent call last): File "", line 1, in ? File "D:\Python21\Image\PIL\ImageFile.py", line 166, in load raise IOError, "decoder error %d when reading image file" % e IOError: decoder error -1 when reading image file From tim at vegeta.ath.cx Tue Mar 12 12:49:28 2002 From: tim at vegeta.ath.cx (Tim Hammerquist) Date: Tue, 12 Mar 2002 17:49:28 GMT Subject: Is Python an object based programming langauge? References: Message-ID: Roy Smith graced us by uttering: > Tim Hammerquist wrote: >> According to Smalltalk enthusiasts, definitely not. > > AFAICT, if you ask a smalltalker, he'll tell you python is not OO because > it's not more like smalltalk. That's coincidental, actually. That's simply because Smalltalk _has_ the qualities he/she uses to classify object oriented langauges. > On the other hand, if you ask a C++ hacker, he'll tell you python is > not OO because it's not more like C++. Similarly for Java, etc. I personally eschew Java and C++ because in my experience, they're more trouble than they're worth. > Everybody seems to have their own definition, usually based on > whatever they learned first. Good observations. I agree. > I've got one guy I work with you insists python isn't OO for exactly one > reason: because it doesn't implement private variables. What does he think of Ruby? Tim Hammerquist -- Man invented language to satisfy his deep need to complain. -- Lily Tomlin From jjl at pobox.com Sun Mar 24 12:26:10 2002 From: jjl at pobox.com (John J. Lee) Date: Sun, 24 Mar 2002 17:26:10 +0000 Subject: ranking and searching [was: Re: "Zope-certified Python Engineers"] In-Reply-To: References: Message-ID: On Fri, 22 Mar 2002, Laura Creighton wrote: > >On Thu, 21 Mar 2002, John J. Lee wrote: [...] > Now consider the case where site number 15,899 is your best bet. Unless > you can come up with the sort of search terms that makes this site come > up higher -- you are never going to see it. This is a neat problem. But of course, you can get other sites to the top of the list by using longer / different search terms. And there is no search system which will not suffer from bad ranking, though metadata does help of course. [...] > once you have made it to the top, you basically stay there, so an [...] I agree this is a problem, but given the fact that self-consistent ranking works much better than non self-consistent ranking, for everyday usage, this is inevitable, isn't it? > The deeper problem is one of the web itself. A few months ago, I [...story of inaccurate web site...] > > I can't report this; I can't get it fixed; and right now some other > poor soul may have done exactly what I did. This is worrysome We You can not link to it, though. I don't claim this is the perfect system, of course, but the self-consistent algorithm used by google makes it work better than you'd expect. I agree that further improvements probably need better input rather than (only) better algorithms. It is a shame, as amk commented, that backlinking schemes aren't being used much (never used it myself, so I can hardly complain). > now have too much information at our disposal, vastly too much, when > throughout history we were more likely to have too little. The problem > now isn't finding stuff -- it is knowing how trustable the stuff is. > > EBay has one sort of approach. So does Advogato (see http://advogato.org ). > It is a real problem and one that interests me a lot. Of course, this is the same kind of information that Google already uses, though in a self-consistent and decentralised way (which is necessary for web page ranking -- unlike advogato's system). Not exactly the same, agreed, since linking to a page doesn't necessarily mean you think it's authoritative. > >[OT: A question I've asked many times and got no answer to is 'why has > >nobody done self-consistent ranking for academic papers'? I fear the [...] > Oh yes! Many people have been trying to do this. See > http://www.isinet.com/isi/news/2001/productnews/8117876/index.html > for one attempt. Hmm, I don't see anything about it on that page... Perhaps my use of 'self-consistent' is not clear: I mean this in the same kind of sense as in 'self-consistent field' calculations (which IIRC is where they say they got their inspiration) -- eg. http://www.google.com/technology/ : | In essence, Google interprets a link from page A to page B as a vote, | by page A, for page B. But, Google looks at more than the sheer volume | of votes, or links a page receives; it also analyzes the page that | casts the vote. Votes cast by pages that are themselves "important" | weigh more heavily and help to make other pages "important." Which I've always assumed is the reason why Google does so much better than older search engines. John From sdm7g at virginia.edu Wed Mar 13 13:52:27 2002 From: sdm7g at virginia.edu (Steven Majewski) Date: Wed, 13 Mar 2002 13:52:27 -0500 (EST) Subject: python and analyze image format? In-Reply-To: <87henkickf.fsf@lumen.indyrad.iupui.edu> Message-ID: On 13 Mar 2002, Michael A. Miller wrote: > Anybody know of a python reader/write for analyze image data and > header files? Would you provide a pointer if you do? Are you referring to the Mayo Foundation's "Analyze" ? -- Steve From python at chajadan.net Thu Mar 7 22:25:17 2002 From: python at chajadan.net (chajadan) Date: Thu, 07 Mar 2002 19:25:17 -0800 Subject: Tkinter question: master? Message-ID: <5.1.0.14.0.20020307191741.028c7940@63.118.78.184> Boy this has been bothering! me.... I understand what a master ~is~, what I don't understand is that in so many examples, I see something along the lines of: class Application(Frame): def __init__(self, master): Frame.__init__(self, master) >>> Now what confuses me is, where is master defined? It always seems to just pop-up. Let me think out loud a sec-- in "def __init__(self, master):", self refers to this class, i.e. Application (though how those are inherently linked [by name or arguement position--assuming position] I have no clue. master will be set equal to whatever the next arguement is, which seems to be Frame... Ok, so if that's all correct so far, in "Frame.__init__(self, master)" the master seems to be referring to itself...... ok wait... the "app=Application(root)" part probably becomes important. I guess, this calls the init method, with root being passed on as master, the class instance as self, and the (Frame) in the class definition must just be for inheritance purposes and have ~NOTHING~ to do with arguements, in the method-sense... geesh! That's been bugging the heck out of me. So do I stand self-corrected? --chajadan From BPettersen at NAREX.com Fri Mar 15 14:23:03 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 15 Mar 2002 12:23:03 -0700 Subject: Pretty Integers Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192158DA2@admin56.narex.com> > From: Lindstrom Greg - glinds [mailto:Greg.Lindstrom at acxiom.com] > > I would like to add commas to the integers I am writing (for > example: 12345678 --> 12,345,678). I have a fairly ugly > method that relies heavily upon mods, but am convinced there > must be a "pretty" way to do it. How would you go about this task? > > Thanks, everyone! How about: >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'English_United States.1252' >>> locale.format('%d', 12345678, 3) '12,345,678' >>> -- bjorn From lac at strakt.com Fri Mar 8 08:33:54 2002 From: lac at strakt.com (Laura Creighton) Date: Fri, 08 Mar 2002 14:33:54 +0100 Subject: PEP 284, Integer for-loops (code bash?) In-Reply-To: Message from David Eppstein of "Thu, 07 Mar 2002 16:39:06 PST." References: Message-ID: <200203081333.g28DXstB021716@ratthing-b246.strakt.com> David Eppstein writes: > Your ints module is nice, and I think if it were in the standard library > I'd be a lot less motivated to push PEP 284. But, the objection to it > will be that it only creates closed intervals, where other Python > objects create half-open ones and it would be nice to have a syntax that > would allow any combination of open and closed interval endpoints. I am not so certain of this. I think that only some people think that it would be nice to have a syntax that would allow any combination of open and closed interval endpoints. I don't. I think that it would have been nice if when Guido was designing the language he used Haskall's syntax for loops. But he didn't. And I think that the reason that no changes along these lines have happened despite years of effort on the part of people who want changes is that this is too hard a thing to retrofit a language with. There are no changes that I can see that are not inferior to living with things the way they are. They flunk my personal elegance test. Right now I don't believe that it is possible to come around with one that is elegant enough that I would support, because I think that we would have found it already if it existed. (Now watch Guido pass the PEP tomorrow :-) ) Laura Creighton By the way, for your students, what keeps you from doing this: import sys _indices = xrange(sys.maxint) #a reusable index sequence, use with zip only, NOT with map ... for index, value in zip(_indices, someList): whatever_you_want() I am assuming that your problem is that you want to teach algorithms to your students and you don't want their brains getting derailed with 'what is a range function' and 'what is an open-interval' and the like. zip is rather easy to understand. Only the name is odd, but then map is already taken. But perhaps I have misunderstood your problem. Laura Creighton From jim at jim.jim Wed Mar 27 15:51:51 2002 From: jim at jim.jim (jimh) Date: Wed, 27 Mar 2002 12:51:51 -0800 Subject: problems with circular references Message-ID: I am working on python code that consist of quite a few files (about 50; each file contains one class). All errors returned by functions are numeric and are defined in the individual files. There is a MessageCatalog.py class which will map these numbers into strings. This MessageCatalog.py has to import all of the 50 other files to have access to their error numbers. So far, so good - no problems yet. Here is the problem: Most of these 50 classes need to use the MessageCatalog themselves. This means, of course, that classA imports MessageCatalog which imports classA. This doesn't work very well. Does anyone have ideas on how to deal with this situation? Thanks, Jim From logstx at bellatlantic.net Thu Mar 21 18:06:14 2002 From: logstx at bellatlantic.net (logistix) Date: Thu, 21 Mar 2002 23:06:14 GMT Subject: Develop-test-debug cycle References: <3C9A6321.9953DC71@ccvcorp.com> Message-ID: DOH! Missed that del statement. > One possible fix/workaround, though also possibly a huge pain in the posterior, > is to simply change all references to wibble to use Wibblemodule.wibble. > > Another thing that might work: > > reload(Wibblemodule) > from Wibblemodule import wibble > > By specifically re-importing wibble, this should (I think) re-bind the name to > the new version. You could also do this the same way you overload stdin, stdout: from Wibblemodule import wibble import Wibblemodule ... reload(Wibblemodule) wibble = Wibblemodule.wibble From stephen at xemacs.org Mon Mar 25 23:36:22 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 26 Mar 2002 13:36:22 +0900 Subject: starting a python program from within xemacs References: <1017098019.357959@DS9.ai-lab.fh-furtwangen.de> Message-ID: <87vgbk54jd.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Marco" == Marco Herrn writes: Marco> sorry if this is the wrong newsgroup to ask, but I tried in Marco> comp.emacs.xemacs and nobody could help me, probably Marco> because too few people there code in python :-) Oh, I think it's unlikely that that is the problem. For starters you waited less than 16 hours for an answer. But most likely because you omitted important information: Marco> Because I use curses, a C-c C-c doesn't work because the Marco> xemacs output window isn't capable of using curses. You didn't mention C-c C-c, so obviously people were led to answer a different question. (defun marco/py-execute-in-xterm () (interactive) (shell-command (concat "xterm -e 'python " (buffer-file-name) "' &"))) (define-key py-mode-map [(control c) c] #'marco/py-execute-in-xterm) probably sorta kinda does what you want. If you want to override the normal C-c C-c, change the second element of the vector to (control c). -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From cfox at crystalcherry.com Wed Mar 6 04:23:37 2002 From: cfox at crystalcherry.com (Colin Fox) Date: Wed, 06 Mar 2002 09:23:37 GMT Subject: mx package Message-ID: Greetings. I realize this is a little OT, but I don't know where else to ask. I'm trying to work with Zope and Postgres, and one of the packages I'm trying to install (psycopg) requirs mxDateTime, which in turn requires mx. I can't find any mention of this 'mx' package anywhere. Any suggestions? Thanks in advance. -- Colin Fox CF Consulting Inc. cfox at crystalcherry.com GPG Fingerprint: D8F0 84E7 E7CC 5C6C 9982 F1A7 A3EB 6EA3 BC97 572F From eppstein at ics.uci.edu Fri Mar 15 19:10:32 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 15 Mar 2002 16:10:32 -0800 Subject: Optimising list comparison References: Message-ID: How about simplifying the logic a bit: def compare(): for i in range(len(list1)): if list1[i] + list2[i] == 1: return 0 return 1 -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From fabi.kreutz at gmx.de Fri Mar 1 07:42:51 2002 From: fabi.kreutz at gmx.de (fabi.kreutz at gmx.de) Date: 1 Mar 2002 12:42:51 GMT Subject: SAX-Parser entity Message-ID: Hi, I spend the last 3 hours browsing FAQs and Mailinglist - without success - but have nevertheless the feeling, that this is a very easy question: I try to use the minidom XML-Parser to parse my little file in order to generate HTML Code. Being german, I really like to use Umlauts but minidom does not. Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.0/site-packages/_xmlplus/dom/minidom.py", line 908, in parse return _doparse(pulldom.parse, args, kwargs) File "/usr/lib/python2.0/site-packages/_xmlplus/dom/minidom.py", line 900, in _doparse toktype, rootNode = events.getEvent() File "/usr/lib/python2.0/site-packages/_xmlplus/dom/pulldom.py", line 251, in getEvent self.parser.feed(buf) File "/usr/lib/python2.0/site-packages/_xmlplus/sax/expatreader.py", line 92, in feed self._err_handler.fatalError(exc) File "/usr/lib/python2.0/site-packages/_xmlplus/sax/handler.py", line 38, in fatalError raise exception xml.sax._exceptions.SAXParseException: :29:19: not well-formed where Character 19 in Row 29 is the occurence of an ?. After browsing the FAQs I changed the default encoding in site.py to iso-8859-1, which had some nice effect, but not on minidom. Some more browsing let me tell pulldom to use StringIO instead of cStringIO, still no success. Since I want to use the text in HTML it would be enough, if I could use the ü instead, but parse gives me in this case ... File "/usr/lib/python2.0/site-packages/_xmlplus/sax/handler.py", line 38, in fatalError raise exception xml.sax._exceptions.SAXParseException: :29:19: undefined entity where 29:19 is the &. I tried to protected it with an \ or / but still no success. Can anybody help me with this? -- The irony of the Information Age is that it has given new respectability to uninformed opinion. - John Lawton From sjmachin at lexicon.net Thu Mar 28 04:41:01 2002 From: sjmachin at lexicon.net (John Machin) Date: 28 Mar 2002 01:41:01 -0800 Subject: Sorting distionary by value References: <3CA295CC.9682E2DB@engcorp.com> Message-ID: Peter Hansen wrote in message news:<3CA295CC.9682E2DB at engcorp.com>... > > Something like freq[word] = freq.get(word, 0) + 1 > > would probably be faster, and it's a little simpler I think, Try this: # way up front of the function, outside all loops freq = {}; freq_get = freq.get # much later ... freq[word] = freq_get(word, 0) + 1 From info at pythonware.com Fri Mar 15 08:57:43 2002 From: info at pythonware.com (PythonWare) Date: Fri, 15 Mar 2002 14:57:43 +0100 Subject: ANN: Python Imaging Library 1.1.3 (march 15, 2002) Message-ID: <036501c1cc29$8fb0f930$0900a8c0@spiff> the secret labs proudly presents PIL 1.1.3: The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities. Version 1.1.3 adds distutils build scripts, improved resampling, screen grabbing support (windows only), and more. Get your copy of the source kit here: http://www.pythonware.com/products/pil/ enjoy, the pil team "Secret Labs -- makers of fine pythonware since 1997." From tdelaney at avaya.com Wed Mar 6 21:20:57 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 7 Mar 2002 13:20:57 +1100 Subject: PEP 284, Integer for-loops Message-ID: > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > In article , > "Delaney, Timothy" wrote: > > You would add a summary of this discussion to PEP 284's > description of > PEP 274? I didn't want to get too detailed, just provide appropriate > citations so readers could look up the relevant related proposals. No - not quite thinking straight there. It of course belongs on PEP 274 only. Tim Delaney. From rich at worldsinfinite.com Fri Mar 15 11:04:04 2002 From: rich at worldsinfinite.com (Rich Harkins) Date: Fri, 15 Mar 2002 11:04:04 -0500 Subject: does Python support some kind of "casting" In-Reply-To: <3C91F472.FB2B67C7@engcorp.com> References: <3C91F472.FB2B67C7@engcorp.com> Message-ID: <200203151604.g2FG44g02681@localhost.localdomain> On Friday 15 March 2002 08:17 am, Peter Hansen wrote: > Tino Lange wrote: > > > Yes, that will make a copy. But copying a list is a pretty efficient > > > operation, so no, it isn't really horribly inefficient. Have you tried > > > it and identified this as a bottleneck? How long are your lists anyway? > > > > 3600 Elements each. > > > > No I didn't check if it's a bottleneck. But I immediately didn't feel > > good when writing "return list(newlist)" (the list contains a list of > > strings itself - so it's much stuff to copy) > > Get over it. 3600 elements is nothing, especially once you realize that > the strings themselves are not duplicated, just the references. > > Anyway, the "immediately didn't feel good" thing is probably a feeling > you'd best learn to ignore more. :-) Only optimize when you have actually > identified a bottleneck by profiling. And a "bottleneck" is not something > that runs "slow", but something that runs "too slow" which means you > also need to have a specific requirement in mind before spending your > valuable time optimizing. Once I learned this it has made my programming > life much easier. > > -Peter Isn't there some additional overhead (above copying the underlying C array for the list) in having to bump each refcount of every object contained? This would appear on the surface to be not trivial when the number of referenced objects becomes large, especially considering that many of the object's ref counts may be swapped out or otherwise. But your point about it is true, it is reasonably fast and I certainly can't think of a general solution that would be better. OTOH, I do wonder if some form of list-based buffer() would be useful in these cases, so that you can take a slice of a list, bump the list's refcount without bumping the referenced objects (they're going to have one for the underlying list anyway), and proceed to process as necessary. Granted, the usefulness in small list cases and cases where you want to modify the buffered thing would be quite limited, such a utility might be useful in large-scale list processing. Is anyone out there doing large scale list stuff in Python that would find this useful? Has anyone else tried using buffer() to do similar slicing with strings? I've had mixed results - sometimes it works like a charm, others some standard library won't accept the buffered() strings... Just random thoughts, Rich From neal at metaslash.com Thu Mar 21 15:28:41 2002 From: neal at metaslash.com (Neal Norwitz) Date: Thu, 21 Mar 2002 15:28:41 -0500 Subject: IntSpan? References: <3c97c886@news.nwlink.com> <3C99F049.5A78B149@metaslash.com> <3c9a1ae9$1@news.nwlink.com> Message-ID: <3C9A4279.D63C14BB@metaslash.com> Jeff Bienstadt wrote: > > "Neal Norwitz" wrote in message > news:3C99F049.5A78B149 at metaslash.com... > > Jeff Bienstadt wrote: > > > > > > Does there exist for Python something akin to the Set::IntSpan module > for > > > Perl? > > > > > > I'm looking for something that inteligently handles and manipulates > spans > > > of integers, such as: > > > 2-356,456,458-500 [my response deleted] > Yes, I knew about range, but that's not quite what I'm looking for. > > Using range to create the full list of integers seems prohibitively > expensive --- spans in the range 1-400000 are not at all out of line. > > I'm envisioning a class that stores (for example) a list of tuples and/or > integers > to express each portion of the span, such as > [(2,356), 456, (458,500)] > > Then, the class might be asked to insert the value 457 into the > span, which would then result in a "merging" of the items in the > internal list, such as: > [(2,356), (456, 500)] > > Other operations (removing a value or a sub-span, merging another > span, etc.) would be useful as well. > > I can see from your reply how range could be useful in the > implementation, for creating temporary lists of values to work > with but again, since the spans could be quite long, this > seems expensive. > > I'm sure that I can implement something like this myself, but > I was hoping that such a thing already existed, because a) I would > prefer to not have to re-invent the wheel, and b) existing code > would almost certainly be better that anything I could write given > my current (week-old!) knowledge of Python. > > (Also, the fact that the Perl module I mentioned uses Set is not > really important, it just came up while I was searching --- further > searching also turned up an Array::IntSpan Perl module. I'm not > a Perl guy at all, and attempting to translate code from a language > that I don't know at all into one that I am just learning strikes me > as painful :-> ) > > If I can't find anything that already does what I'm looking for, I'll go > ahead and tackle it myself. Oh, so you wanted something useful??? :-) Here's a start: class IntSet: def __init__(self, *args): self.ints = {} self.ranges = [] for v in args: try: self.add(*v) except TypeError: self.add(v) def add(self, min, max=None): if max is None: self.ints[min] = 1 else: self.ranges.append((min, max)) def __contains__(self, value): if self.ints.has_key(value): return 1 for min, max in self.ranges: if min <= value <= max: return 1 return 0 has = __contains__ def __add__(self, other): newset = IntSet() newset.ints = self.ints newset.ranges = self.ranges if type(other) is type(0): newset.ints[other] = None return newset if type(other) is not type(self): raise TypeError, "'%s' is not an int or %s" % \ (other, self.__class__.__name__) newset.ints.update(other.ints) newset.ranges = newset.ranges + other.ranges return newset >>> from intset import * >>> s = IntSet((2, 356), 456, (458, 500)) >>> print s.ranges [(2, 356), (458, 500)] >>> n = s + 5 >>> print n.ints {5: None, 456: 1} >>> print n.ranges [(2, 356), (458, 500)] >>> s + 5.3 Traceback (most recent call last): File "", line 1, in ? File "intset.py", line 37, in __add__ raise TypeError, "'%s' is not an int or %s" % \ TypeError: '5.3' is not an int or IntSet >>> j = s + n >>> 457 in j 0 >>> 456 in j 1 >>> 5 in j 1 >>> 2 in j 1 >>> 1 in j 0 >>> s.has(456) 1 >>> s.has(457) 0 >>> s.add(2, 356) >>> s.add(456) >>> s.add(458, 500) I'll let you learn the how to do intersection, etc. :-) But union is done. Neal From netlangau at yahoo.com.au Sun Mar 10 06:21:53 2002 From: netlangau at yahoo.com.au (Patrick) Date: Sun, 10 Mar 2002 22:21:53 +1100 Subject: python and haskell for fun References: Message-ID: "Sandy Norton" wrote in message news:b03e80d.0203100136.74910e87 at posting.google.com... > > I've just picked up Simon Peyton Jones' book on haskell: "The craft of > functional programming", and I've just discovered that there's a nice > aesthetic to haskell that somehow reminds me of python: beautiful > syntax, significant whitespace, a wonderful obsession with simplicity, > clarity and readability... > > Now, just for fun, I'm thinking how it would be splendid to use these > two languages together, and make them beget a pretty monster so to > speak. When you distil the qualities you like in each language, are there any parts that don't overlap? If so, perhaps there's a "pretty monster" waiting to be begotten. There are a few different ways to look at this, but I suspect that when you distil and combine the qualities that appeal to you, you'll have a nice set of overlapping qualities. This subset of PASKELL will be clean, beautiful and functional. To make it functional in a practical as well as mathematical sense, you'll need to incorporate a few more carefully chosen features that give you enormous practical benefits without spoiling the elegant simplicity you inherited. By the time you're finished, you'll have a brand new .... Python ;-) At least that's how it seems to me... (You might also want to look at Lisp). From anthony_barker at hotmail.com Thu Mar 7 17:52:22 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 7 Mar 2002 14:52:22 -0800 Subject: Python on W2K server and dos batch files? References: <3c866f0c$1_2@axion.net> <899f842.0203062032.75b219a7@posting.google.com> <3C87AFCB.1731B0B5@noaa.gov> Message-ID: <899f842.0203071452.2ac42ddb@posting.google.com> > Personally, I like wxPython better: I think it produces a more native > looking app, is faster, and I just like how it is put together better. > Most of this is just personal preference. The one truly compelling > reason to use TK is the wonderful canvas widget, but you don't seem to > have a need for that. At first look, TK seems to be quicker and easier and require less code to build a GUI, but my experience (and that of others) is that while you can through something together faster with TK, once you tweek it to be > just how you want, and have a full blown application, you have written > more code than you would with wxPython. The application is an admin tool, "A throw away application". Thats why I recommended TKinter. If you are going to use the application on multiple machines you don't need to worry about installing wxPython on each one or writing an install program. I needed a commercially supported distro which runs on Solaris and Windows. ActiveState comes only with TKinter. For info: http://www.pythonware.com/library/tkinter/introduction/ From gerrit.muller at philips.com Wed Mar 6 07:15:53 2002 From: gerrit.muller at philips.com (Gerrit Muller) Date: Wed, 06 Mar 2002 13:15:53 +0100 Subject: Reorganizing python.org (was: Why isn't pychecker...) References: <3C80ED0B.42292C99@tds.net> <3C83E283.6F030BA1@metaslash.com> <3C841006.634D0059@tds.net> <3C84299A.20EC85A2@tds.net> Message-ID: <3C860879.BEC1002B@philips.com> "Edward K. Ream" wrote: > > Steve Lamb wrote: > > > > Another example, the otherwise superb intro to Tkinter, > > > http://www.pythonware.com/library/tkinter/introduction/index.htm > > > would be vastly more useful if it fit on a single page. > > > > Define "page". If you say 800x600 you'd lose. > > Good question. How would you define a page in terms of web design? > > Eliminating most if not all scrolling on reference pages seems > particularly important. Some reference pages seem way too long. And > your point is well taken. I have a large monitor, but I use relatively > big fonts, so I'm only using 1024x768... > > Edward <...snip...> at this moment in time 1024*768 is a reasonable choice; the poor 14" CRT users will need some scrolling, but all more lucky 15" LCD and 17" CRT and above will have a scroll free overview. Gerrit -------------------------------------------------------------------- Gerrit Muller Philips Research Laboratories Eindhoven Building: WDC 2 - 007 Prof. Holstlaan 4 Phone: +31 40 27 45242 5656 AA Eindhoven Fax: +31 40 27 45033 The Netherlands mailto:gerrit.muller at philips.com http://www.extra.research.philips.com/natlab/sysarch/index.html From richard at NOstarfighterSPAM.freeuk.com Tue Mar 19 14:13:34 2002 From: richard at NOstarfighterSPAM.freeuk.com (Richard Townsend) Date: Tue, 19 Mar 2002 19:13:34 -0000 Subject: Extending Python/Tkinter References: <5acdbd0c.0203190838.20c3733e@posting.google.com> Message-ID: <1016564981.29368.0@eurus.uk.clara.net> > I have a C++ class that draws maps that I've been assigned to extend > into python. The class uses X primitive calls (XDrawPoint, etc.) to > do much of the work and I'm at a loss on how to integrate this as an > extension to Python. Initially I thought I could get a drawable, > display and graphics context from the Tk C API. Then I saw that > Tkinter is using the Tcl interpreter and not calling the Tk routines > directly. Now I'm lost. I'm a newbie to Python/Tk/Tcl and hitting > info overload from looking through so many books and web pages (sorry > is this is a bad question). I'm missing something crucial or this > approach is half-baked or both. > Tkinter doesn't have an equivalent of XDrawPoint, but you could use PIL. I wrote a simple application to display elevation data for the UK. It was rather slow, but it did the job. You need the following imports import Image import ImageDraw import ImageTk Here is my method that creates the image and copies it to a Tkinter Canvas widget - perhaps you could adapt the concepts: def createImage(self): """Create an image containing the data from the file """ m_file = open('uk_map.dat', 'rb') self.img = Image.new("RGB", (self.map_width, self.map_height)) self.photo = ImageTk.PhotoImage(self.img) self.canvas.create_image(0, 0, anchor=NW, image=self.photo, tags='img') self.canvas.resizescrollregion() draw = ImageDraw.Draw(self.img) # Fill image with the sea colour draw.rectangle((0, 0, self.map_width, self.map_height), fill=self.colours[0]) for y in range(0, self.map_height): for x in range(0, self.map_width): b1, b2 = m_file.read(2) elev = ord(b1) + 256 * ord(b2) if elev > 0: draw.point((x, y), self.colours[elev]) if y % 50 == 0: self.photo = ImageTk.PhotoImage(self.img) self.canvas.itemconfigure('img', image=self.photo) self.canvas.update() m_file.close() del draw self.photo = ImageTk.PhotoImage(self.img) self.canvas.itemconfigure('img', image=self.photo) self.canvas.update() Hope that is of some use, RT From slimey at choc.late.org Sun Mar 24 18:15:23 2002 From: slimey at choc.late.org (Sly Mee) Date: Sun, 24 Mar 2002 17:15:23 -0600 Subject: I am TGOS your new ruler References: <07fcd5f6.3ba05335@tgos.org> <2sjl7a.ap6.ln@hairy.machine.org> <3C9E5402.7070406@attbi.com> Message-ID: On Sun, 24 Mar 2002 16:32:35 -0600, Rann Aridorn said: > Sly Mee wrote: > >> On Sun, 24 Mar 2002 12:46:44 -0600, TGOS said: >> >> >>>That's right you stupid, inbred, shit eating, pathetic, motherfucking, >>>brain dead, useless cocksuckers! I'm taking over all of Usenet! There >>>isn't a fucking thing you can do about it either! You're all a bunch of >>>worthless scumbags, and now you will all answer to me! If you don't >>>like this fact TOO FUCKING BAD! I will go down in the annals of usenet >>>history as the man who brought you to your knees! Now get down on your >>>knees and pay proper tribute to my glorious self! >>> >>>I AM THE GUARDIAN OF SAILOR MOON! LORD AND HIGH MASTER OF USENET! >>> >>> >> .....And High Moron of All You Survey! >> >> >> > Sorry about this. A hipcrimer is trying to cause trouble for > Alt.Hentai.Sailor-Moon by impersonating one of our regulars. If you care > to register your displeasure, please do so in the hipcrimer's own > stomping grounds, alt.mag.hustler > > -Rann Sorry, but he's doing it all over. Best to ignore him I suppose. -- Any time things appear to be going better, you have overlooked something. --- 100 Proof News - http://www.100ProofNews.com --- 1,500+ Binary NewsGroups, and over 90,000 other groups --- Access to over 100 Gigs/Day - $8.95/Month --- UNLIMITED DOWNLOAD From Ed.Smirnov at mail.ee Tue Mar 26 11:01:24 2002 From: Ed.Smirnov at mail.ee (Eduard Smirnov) Date: Tue, 26 Mar 2002 18:01:24 +0200 Subject: Python vs. C/C++/Java: quantitative data ? Message-ID: <3ca09a43$0$3216$bb624dac@diablo.uninet.ee> I?m writing a diploma paper on the difference between scripting (e.g. in Python or Tcl) and system programming (e.g. in C, C++ or Java), and one of the claims I want to make is that you can often develop applications 10x or more faster in a scripting language. I apologue that more applications can be written or re-written in scripting language faster and with more complex functionality then in system programming language. If you have any experience in writing applications in system programming language (e.g. in C, C++) and re-writing it in scripting language (e.g. Python) or vice versa, please compare your work in both implementations, describe your work/application?s functionality, approximate number of lines and time of development of each implementation, skill?s level needed. Any more comments about are welcome. Additional thanks for copy your answer to my e-mail. Eduard.Smirnov at mail.ee Tallinn Technical Univercity Estonia From op73418 at mail.telepac.pt Wed Mar 27 15:49:56 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 27 Mar 2002 20:49:56 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Message-ID: On Wed, 27 Mar 2002 10:42:59 -0800, Geoff Gerrietts wrote: >Quoting Gon?alo Rodrigues (op73418 at mail.telepac.pt): >> On Tue, 26 Mar 2002 20:04:50 -0800, Geoff Gerrietts >> wrote: >> >> >Quoting Courageous (jkraska at san.rr.com): >> >> >> >> >I'd say the skills required to write clear, readable >> >> >software and clear, readable novels are not entirely >> >> >disjoint! >> >> >> >> Oh certainly not, you just haven't backed up to a big >> >> enough perspective of the cognitive domain. :) >> > >> >I think poetry and code are actually very similar. Some day I may >> >write a paper on that thesis, but I'm still living the experience >> >today.... >> >> Poetry and coding are similar in that they are both creative activities >> needing inteligence, imagination, etc. But there is also a world of >> difference between the two. A simple way to see this is how they relate >> to their heritage, their common dead. > >I think the startling similarity that I see is that code is in many >ways an extremely strict form of poetry. If you look to things like >the Perl poetry contests, and even the innumerable obfuscated code >contests, these are artistic in a way that forms a sort of continuum. > >Writing code is a lot like writing a poem, with a vocabulary that is >extremely restricted and formal requirements that are invariably >rigid. The sense of meaning one derives from a program is generally >more pragmatic than what one gets from a poem. But both are >appreciated as much for what they say as for how they say it. > >One notable difference between programming and poetry is that a >programming cliche is acceptable, a rote that people are encouraged to >re-use, whereas dropping someone else's clever turn of phrase into >your poem is likely to backfire. > >I'm still a long way from a thesis, but I think the similarities are >pretty astounding. > >And I don't think I can comment extensively on the "common dead", >given that poets tend to take about 25 or 50 years to rise to >prominence, and the widespread practice of programming in 3rd gen >languages is still somewhat younger than that. I can comment on the >"common living", though -- Silicon Valley and the Bay Area are both >full of people who went to school for English and fell into writing >HTML, Perl, PHP. I can't comment extensively on the quality of the >code these writers-cum-programmers generate, but I'll bet their >comments are at least a bit more intelligible -- and I'll bet their >code is more readable. > >I've been programming for a long time -- most of my life at this >point, and professionally for a bit more than 6 years. But my >education was in poetry; I was trained as a poet, and somewhat >successful at it, winning a few awards and being published in some out >of the way places. > >I returned to programming when I realized that I was pretty good at >writing, but I couldn't bring myself to do it in my spare time -- I >was instead spending that spare time learning new programming >languages, or learning Linux system administration. I didn't enjoy >reading poetry all that much, but I could sit down and read a book on >OO design or advanced programming techniques without hesitation. > >So I respect the differences; there are many, and I've chosen my road >because of them. But the principal values of poetry: no wasted words, >clear expression, clever expression, best use of language -- these >values translate directly into writing code. > My comment was made not so much to deride the analogies which you have pointed out, and with which I agree, but to stress the differences which are many and of great import. And as an example of the differences I gave you the relation that the living active practicioners (programmers or poets) have with the heritage that is bestowed on them. Programming, although only a few decades hold, already has its morcel of history and its heroes - the demigod hackers - which are respected and revered. But the situation is totally different in poetry, especially if you are a poet. The type of respect and reverence given to Shakespeare is of a totally different kind to that given to Guido van Rossum. Shakespeare has occupied its place in the space of poetry and he will not suffer to be dislodge. Shakespeare puts a contingency on all those that follow him because there is no such thing as "poetry reuse", originality of Voice, of Expression, of Vision, being THE most important goal for poets. Poetry, or more generally the arts, are not progressive. My favourite living prose writer is Thomas Pynchon. Is he a "progress" (on the aestethic sense, the only one that matters) on Sterne or Dickens? Of course not. But code, even very god one, is constantly being improved upon. An anedoctal evidence of this is that code has bugs! So, to sum things up, I do not disagree with the similarities you have pointed out - essentially, the sense of beauty in a piece of code, deriving not just from what you are trying to achieve but in the way you achieve it - but I wanted to point out the differences and frame them better. >Maybe that thesis isn't so many years off, after all.... > >--G. Best regards, Gon?alo Rodrigues From bergeston at yahoo.fr Wed Mar 27 13:38:08 2002 From: bergeston at yahoo.fr (Bertrand Geston) Date: Wed, 27 Mar 2002 19:38:08 +0100 Subject: visual python References: <20020327104352.12035.00000368@mb-mk.aol.com> Message-ID: I am so sorry ... ... to be french when I see (too often) such indelicate compatriots. B. "Paul Wright" <-$P-W$- at verence.demon.co.uk> wrote in message news:a7sq8i$76a$1 at verence.demon.co.uk... > > In article <20020327104352.12035.00000368 at mb-mk.aol.com>, > Marxdormoy wrote: > >downlaod visual python ? website? > > Search engine? Google? > > -- > Paul Wright | http://pobox.com/~pw201 | From abou at cam.org Fri Mar 29 19:00:19 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Fri, 29 Mar 2002 19:00:19 -0500 Subject: First post! Message-ID: <3CA50013.3582BC63@cam.org> Ok, this is my first post on this list. I've been doing simple Python scripts for a few months but now I have a 'bigger' (IMO) project. It's as follow: I play a MUD called Core 2651 (http://coremurd.org) and in this MUD, there is a stock market. The various prices are all on the website and are updated every once in a while. So basically, I want a script that checks the page for the prices and print the output in a text file. I've never done anything that touches the web or internet so I'm really puzzled. I'm not asking for someone to write it for me (don't spoil the fun :) but maybe there already are some scripts like that somewhere... Scripts that parse (is that right?) through a page and get different infos. I have right here a Perl one that does basically that (but I'm not a fan of Perl, that's why I'm here) and it seems pretty easy (well, not for me). So, if anyone has tips, links or examples, just let me know. Thanks in advance, Zutroi Zatatakowski From philh at comuno.freeserve.co.uk Tue Mar 26 06:28:28 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Tue, 26 Mar 2002 11:28:28 +0000 Subject: ht2html project at SourceForge References: <15515.36115.281626.923961@anthem.wooz.org> <3C9FBDB0.7E0BCA16@engcorp.com> Message-ID: On 26 Mar 2002 11:19:03 +0100, Martin v. Loewis wrote: >Peter Hansen writes: > >> Maybe it's just the ones who already knew how to do this, who >> knew how to do this.... ;-) > >I guess Barry sort-of expected everybody to know that pointing to >foo.sf.net should trigger the "SF structure" synapse, so you'd >immediately know that the CVS can be reached through >sf.net/projects/foo, which has the CVS link in the standard location. It certainly wasn't obvious to me. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From jhg at galdon.com Fri Mar 8 14:25:12 2002 From: jhg at galdon.com (Juan Huertas) Date: Fri, 8 Mar 2002 20:25:12 +0100 Subject: About deletion of variables in version 2.1 Message-ID: Hi all. I'm working with large list or dict an have problems with the deletion and time of response, this problems does not exist in version 2.0: Reading a large file and loading to a list: f=open('c:/xx','rb') ls=[] while not eof: ln=f.readline() ls.append(ln) This takes 5 seconds (reasonable) The new instruction: ls=[] # or del ls Takes about 10 seconds and use 100% of Memory!!!! And a continuation repeating the proccess: while not eof: ln=f.readline() ls.append(ln) This takes about 30 seconds !!! Why? (please aid) The comprobation is in Windows 2000 and pythonwin If i try with a new variable, p.e. lx=[] and not refer to ls, the process take 5 seconds. From vinay_sajip at yahoo.co.uk Wed Mar 20 21:59:03 2002 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 21 Mar 2002 02:59:03 -0000 Subject: ANN: Logging Module v0.4 released References: <2e37dc1.0203201754.50a15e80@posting.google.com> <200203210211.CAA14633@crown.off.ekorp.com> Message-ID: <00e001c1d084$63095120$652b6992@alpha> > Having looked at the excellent work being done here, I wonder what's > happening at the other end of the pipeline. That is, what's listening for the > events that the logger is generating? Has anyone got any plans to write a > logging sink for the other end? There is a rudimentary logging sink provided (as an example and test harness) with the distribution - logrecv.py. It can be run to listen for logging events on TCP, UDP or both. > The sink would perform the following duties: > - accept events from the logging module via all the logging module's > handlers > - present a display of the events to a user, either graphically or > textually (the most basic of these would resemble the UNIX tail -f) > - redistribution of events to other targets > - filter incoming events, possibly aggregating, possibly dropping > - have state which would be affected by the filters and may cause new > events to be generated (ie. escalation) Presently, logrecv.py just logs according to whatever the logging policy is on the machine where it is running. This allows, for example, logging to Unix syslogs from an NT-based application, or logging to NT event logs from a Unix-based application. Most of the functionality you've described above (e.g. GUI) would be fairly application specific. Certainly, the logging system delivers (I hope) what is expected of it - accepting events of interest and passing them flexibly to handlers. Presentation, sophisticated filtering, aggregation etc. are all in the application domain, and I'd certainly be interested to hear more about specific applications. Regards Vinay Sajip Red Dove Consultants Ltd. http://www.red-dove.com/ _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From peter at engcorp.com Sat Mar 9 09:25:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Mar 2002 09:25:36 -0500 Subject: Q: How can I lock a file in Windows? References: Message-ID: <3C8A1B60.D4B6ABCA@engcorp.com> Flavian Hardcastle wrote: > > Graham Ashton wrote in > news:XBli8.5326$OP.143152 at stones: > > > On Sat, 09 Mar 2002 10:06:08 +0000, A.Newby wrote: > > > >> Is there another way I can lock the file in Windows? > > > > Yes. Try this: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 > > > > Thanx! That should work, except I don't seem to have the following > extension modules ... win32con, win32file, and pywintypes. Any idea where I > can get them? Whenever I'm in this situation, I go to google and ask for a search on something like "win32file python download" and I usually get an answer... -Peter From wealthychef at mac.com Thu Mar 14 23:26:34 2002 From: wealthychef at mac.com (wealthychef) Date: 14 Mar 2002 20:26:34 -0800 Subject: how to check how many bytes are available to read() ? Message-ID: <2b57f654.0203142026.68ec3fc7@posting.google.com> I have a file object f. I want to know if there are any bytes to read from it. I have tried using select.select([], [f], []), but I have found that select will return [],[f],[] even if there is nothing to read in f, so that when I call f.readline(), it blocks. Is there a function or some way i can peer into f and see if it has any bytes for me? f is actually someprocess.fromchild, by the way. From jason at jorendorff.com Sat Mar 9 13:59:31 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sat, 9 Mar 2002 12:59:31 -0600 Subject: should i learn it first ? In-Reply-To: Message-ID: Qiang.JL wrote: > I am a student who have learned perl,java and other like data structure > stuff. Now i want to take some further step to learn one or two > languages to improve my language view. There are two languages are on > the list: python and C++ Learn C first. > do i need to learn C/C++ to be a good programmer? You can be a good Java programmer without knowing C. You can be a good Python programmer without knowing C. But every good *all-around* programmer I've met knows C. ## Jason Orendorff http://www.jorendorff.com/ From frr at wanadoo.es Sat Mar 9 05:43:53 2002 From: frr at wanadoo.es (Fernando Rodríguez) Date: Sat, 09 Mar 2002 11:43:53 +0100 Subject: Tokenize a string or split on steroids Message-ID: <4lpj8u4nbsoqjf2h4upadti62jh4sf4i59@4ax.com> I need to tokenize a string using several separator characters, not just one as split(). For example, I want a function that returns ['one', 'two'] when given the string '{one}{two}' . How can I do this? O:-) TIA | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Fernando Rodr?guez frr at EasyJob.NET | http://www.EasyJob.NET/ | Expert resume and cover letter creation system. | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From loewis at informatik.hu-berlin.de Wed Mar 20 05:17:06 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 20 Mar 2002 11:17:06 +0100 Subject: how to ask different DNS for gethostbyname? References: <8de6d3da.0203200204.31b083d9@posting.google.com> Message-ID: koji at twinsun.com (Koji Nobumoto) writes: > Is there any way to use a DNS which is not looked up > when I just use the socket.gethostbyname(), without > changing /etc/resolv.conf or any system configuration? No. You need, at a minimum, access to the systems resolver library, which is not exposed in standard Python. Better yet, you should use a Python DNS package - that will allow you to use all tuning you want. Regards, Martin From fig at localhost.localdomain Mon Mar 4 05:01:40 2002 From: fig at localhost.localdomain (Stephen R. Figgins) Date: Mon, 04 Mar 2002 10:01:40 -0000 Subject: Converting mailbox formats References: Message-ID: In article , Ron Johnson wrote: > Are there pythonic methods for converting the MH message header > format to the mbox message header format? Does it need to be in Python? Check out the packf command which comes with MH, it will pack your folders into mbox style. -Stephen From max at alcyone.com Sat Mar 30 23:47:47 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 30 Mar 2002 20:47:47 -0800 Subject: long integers References: Message-ID: <3CA694F3.83BF0E17@alcyone.com> Michael Hall wrote: > I'm using Python 1.5.2 and am having trouble with long integers when I > pull data out of a MySQL database using MySQLdb. When I retrieve a > numeric value from a field with an `int' data type, the value has an > `L' > stuck on the end. There are two standard methods of converting to a string: str and repr. repr is for converting to a representational string (nominally how it would have been parsed, or surrounded in < and > otherwise), and str is for pretty formatting. The print statement implicitly converts its arguments via str, not repr. > In one script, I worked around this by stripping the L off with: > > var = numeric_id # ("2L") > var = var[:-1] > print var > >> 2 In 1.5.2 you're stuck with this solution; unfortunately, both str and repr including the L suffix. This was considered a defect and was fixed in 2.0; in 2.0 and greater, str does not include the L suffix but repr stil does. > var = result[0] # ("2L") > var = 'var[:-1]' > print var > >> var[:-1] Presumably you meant backquotes here, not forward quotes: `...` is requivalent to repr(...). Forward quotes ('...') are for quoting strings, so 'var[:-1]' is literally the string "var[:-1]" (not an evaluation of the expression), but `var[:-1]` is equivalent to repr(var[:-1]). Note that some (many?) consider the backquotes unsightly; you're probably better off using repr. > Can this be fixed in > MySQL by changing or modifying the data type, or should I upgrade to a > later version of Python? It's fixed in Python 2.0 and up; upgrading and using str will solve the problem. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From brueckd at tbye.com Wed Mar 20 13:21:11 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 20 Mar 2002 10:21:11 -0800 (PST) Subject: Attachments to the list/group - OK? (Was Re: Popular style document?) In-Reply-To: <20020320171852.GI18847@andy.tynant.ftech.net> Message-ID: On Wed, 20 Mar 2002, Andy Gimblett wrote: > I've just noticed that most people seem to embed their code directly > into their messages. Is attaching .py files (or any other > non-binaries) frowned upon around here? I won't speak for others, but the likelihood of me opening an attachment to look at code is close to zero... just too annoying. IMO, if it's too big to gracefully include in the message then attaching it isn't that good anyway because (1) if you're asking for help nobody is going to read through that much code and (2) if you're releasing something then it'd be better posted to the Web (e.g. the Vaults). -Dave From grante at visi.com Sat Mar 9 00:29:01 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 09 Mar 2002 05:29:01 GMT Subject: wxPython seg faults under RH7.2 Message-ID: I can not get wxPython to work on a RH7.2 system. I have gtk 1.2.10 and wxGTK 2.3.2.1 installed. Gtk came with RH7.2 and wxGTK was installed from binary RPMs downloaded from wxwindows.org. I built and installed wxPython 2.3.2.1 from sources using Python 2.1.1. The build/install seemed to work fine, but even the most trivial wxPython apps just seg fault. I next attempted to use SWIG in the wxPython build: I downloaded SWIG 1.1-883, but the patches that come with wxPython 2.3.2.1 fail to apply. Can somebody point me to some documentation that explains how to get wxPython to work under RH7.2? -- Grant Edwards grante Yow! I think my CAREER at is RUINED!! visi.com From h_schneider at marketmix.com Mon Mar 11 12:04:04 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Mon, 11 Mar 2002 18:04:04 +0100 Subject: DBgrid in python References: Message-ID: DBgrid in pythonOoops ... www.wxwindows.org , certainly ... "Harald Schneider" schrieb im Newsbeitrag news:a6ihmt$2re$03$1 at news.t-online.com... www.wxpython.org www.wxpython.org You have to install both to get a GUI ... Bye, Harald "Alves, Carlos Alberto - Coelce" schrieb im Newsbeitrag news:mailman.1014054238.12896.python-list at python.org... Is there any component in python as DBGrid component in Delphi?! If so, where can I get it?! Thanks, Carlos Alberto COELCE/DPRON-Departamento de Projetos e Obras Norte Fone: 677- 2228 e-mail: calves at coelce.com.br \|||/ (o o) --ooo0-(_)-0ooo-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From watkins_no_spam at trendvue.nospam.com Wed Mar 6 23:59:23 2002 From: watkins_no_spam at trendvue.nospam.com (Michael Watkins) Date: Thu, 07 Mar 2002 04:59:23 GMT Subject: Web scripting with Python (1st post here, also :-) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: I can empathize with your quest. I'm fairly new to Python although already entranced. Coming from several years of PHP, ASP, Jscript yet as little Perl as possible, I found the Python language and base libraries very refreshing and complete. Deciding on an architecture for web work is as you've found, much more complicated due to all the choices. Why not just dive in and build a simple app for yourself as a start, it will teach you much. If you want a simple html templating system, one I use (used it in PHP as well) is HTMLTMPL ( http://htmltmpl.sourceforge.net ) which is available for Python and PHP, and uses templates compatible with the Perl module HTML::TMPL. That and simple CGI will get you going. To do anything bigger, more complex, on a public web site you either need to own the box or have a flexible web hoster to run many of the other systems (mod_python, Zope, etc) that you have been referenced to. Get your feet wet and have some fun! "Julio Nobrega" wrote in message news:40c3f5da.0203061114.18f7fea6 at posting.google.com... > Hi! > > So, I am looking for examples that might help me. Yes, I saw Zope. > Waaaaay too much. Also read Web Programming Topic Guide on python.org, > way less practical than I like. Picky, ain't I? :-) > From joonas at olen.to Tue Mar 5 10:28:03 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Tue, 05 Mar 2002 15:28:03 GMT Subject: Problem with popen() and a regular expression References: <3C84BD5C.3050901@bath.ac.uk> Message-ID: <3C84E363.6020106@olen.to> Simon Willison wrote: > I've written a simple Python script to scan a bunch of URLs for "live" > sites and grab the title of those pages. It works by using popen() to > call lynx and analyse the HTTP response: > > ----------------------------------------------------------------- > > command = "/opt/bin/lynx -mime_header http://www.bath.ac.uk/~"+user+"/" Use: command=["/opt/bin/lynx","-mime_header","http://www.bath.ac.uk/~"+user+"/"] for better security. From jgardn at alumni.washington.edu Wed Mar 13 20:02:10 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Thu, 14 Mar 2002 10:02:10 +0900 Subject: How do you protect the source code of python applications? References: <3C8C6EC5.8080308@student.kun.nl> Message-ID: husam penned with his keyboard: > Is there a way to protect the source code of applications written with > python? > License it with the GPL. That will ensure that anyone who uses it has to make their software free as well. No one has successfully taken source code from a GPL project and put it in their own closed-source prorietary project. If you transfer the copyright on your software to the FSF, they will defend the license in court for you for free as well (like they are doing for MySQL right now). Jonathan PS - Yes, this is half in jest. But you ask a question... =) From kp87 at lycos.com Fri Mar 8 04:50:13 2002 From: kp87 at lycos.com (kevin parks) Date: 8 Mar 2002 01:50:13 -0800 Subject: Voss 1/f noise algo help Message-ID: <5e8bd451.0203080150.44a259ce@posting.google.com> Hi I have a couple of attempts below at the beginnings of a 1/f^2 Noise generator. It is in a sort of heavily commented psuedo Python (somewhat translated from PASCAL) You can see that there are some areas where i am in way over my head. I may have introduced a mistake or two as well. Anyone familiar with Voss's algorithym want to help smooth out the rough edges here? It sure would be nice to be able to generate pink noise values in Python (brownian noise would be good too, I am trying to work something up on that too). Back to the books, # An attempt to get R. F. Voss's algorithm ported to python import random def one_over_f (n=128): '''generates a sequence with a 1/f spectrum n determines the number of random generators and length of sequence ''' seq_length = 2**n # Compute length of output sequence random_max = 1.0/n # Set scale factor for random generators previous_seq_index = (seq_length - 1) # Initialize the previous index value seq_index = 0 # Generate the 1/f seq while seq_index < seq_length: output_value = 0 # Generate output loop i = 0 # Bit check loop # Compare bit 1 of seq_index with that of previous_seq_index # If they are not the same, generate new random number. while i < n: if bit_compare(i, seq_index) != bit_compare(i, previous_seq_index): values[i] = random(O, random_max) output_value = output_values + values[i] i = i + 1 # End bit check loop previous_seq_index = seq_index seq_index = seq_index + 1 return output-value # ---- # def oneoverf(npts=128): # nbits = 1 # np = 1 # nr = npts # float # nr = nr/2.0 # while nr > 1: # nbits = nbits + 1 # np=2*np # nr=nr/2 # for(kg=0; kg 1: nbits = nbits + 1 np=2*np nr=nr/2 kg = 0 while kg Message-ID: "John" wrote in news:01rp8.34168$tg4.401910 at vixen.cso.uiuc.edu: > I was glad to find that Python allows the following: > > def addone(a): return a+1 > list_of_functions=[addone] > list_of_functions[0](1) --> returns 2 > > However, what if the functions require more than one arguments? say > def addall(a,b,c): return a+b+c? > Though list_of_functions[0](1,2,3) works, I'd like to make (1,2,3) as > variables.. How do I pass the variables to such functions? like that: >>> a=1;b=2;c=3 >>> list_of_functions[0](a,b,c) or >>> l = (1,2,3) >>> apply(list_of_functions[0],l) chris -- Chris From lenny.self at attbi.com Fri Mar 8 00:57:50 2002 From: lenny.self at attbi.com (Lenny Self) Date: Fri, 08 Mar 2002 05:57:50 GMT Subject: List of Dictionaries References: <14dc40e2.0203071559.5e3d4550@posting.google.com> <3C88186F.6BEFA3D2@alcyone.com> Message-ID: Here's a chunk of the real code. f = open("c:/test.dbx", "rb") msgs = ReadOEFile(f) # Using 3rd party code to get email out of an Outlook mailbox masterList = [] for mesg in msgs: email = Read_OE_Message(f, mesg.position) # returns a string containg an individual email data = MailData(email).getOrderInfo() # Looks though email and sucks out important information and returns it as a dictionary # if I print the data variable here It shows data from each of the messages (all unique) masterList.append(data) # If I print the masterList dictionary here it has the right number of elements in the list but they are all the same. Each of the origional dictionaries containd the following key:value pairs being appended to the masterList looks something like this. {'sku': 'BIO-09', 'city': 'Rancho Palos Verdes', 'shipMethod': 'media mail', 'shipTo': '3456 Address Dr.', 'listingID': '38fh49dhfm4', 'zip': '90275', 'shippedby': 'email at address.com', 'url': 'url.goes.here.com', 'country': 'USA', 'address2': '', 'timeOfSale': '02-07-2002 09:27:35', 'buyerEmail': 'another.email at address.com', 'purchaseDate': '02-07-2002 09:27:35', 'item': 'The Rise of Theodore Roosevelt by Morris, Edmund', 'state': 'CA', 'transaction': '700106169851', 'buyerName': 'Someone S. Name', 'address1': '1234 Address Lane, 'condition': 'Good'} An interesting piece of info is that when I append a subset of this data, say just to key value pairs it works Like just: {'sku':'BIO-09','item':'The Rise of Theodore Roosivelt by Morris, Edmund'} Same code just smaller dictionary. Could I be surpassing some sort of limit. I woudn't think this dictionry is that big. Thanks again for your help. -- Lenny "Erik Max Francis" wrote in message news:3C88186F.6BEFA3D2 at alcyone.com... > Lenny Self wrote: > > > When I add the first dictionary element to the list all is well. When > > I add the second element to the list both the first and second element > > reference the second dictionary that was added. The behavior > > continues whenever I add an element. So, if I add, say 50 > > dictionaries, all of the listes elements reference the last dictionary > > I added. > > > > I don't have the code with me right now, but I can assure you it is > > easy as this: > > The problem you're having crucially depends on you doing something wrong > in the details of your implementation. You're going to have to show us > the _exact_ code that is causing this problem or it will be impossible > to help you. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ Laws are silent in time of war. > \__/ Cicero > Esperanto reference / http://www.alcyone.com/max/lang/esperanto/ > An Esperanto reference for English speakers. From greg at cosc.canterbury.ac.nz Sun Mar 3 20:08:44 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 04 Mar 2002 14:08:44 +1300 Subject: Status of PEP's? References: <1cef615e.0203021254.6bf3658@posting.google.com> Message-ID: <3C82C91C.A60B3242@cosc.canterbury.ac.nz> "Hernan M. Foffani" wrote: > > But I fail to see how to apply this solution naturally on sets that have > several different main 'walking' directions like arrays or like the sample > in the PEP. If the 'table' object has symmetry between two (or more) axes, > then > indici(table) > is ambiguous. An optional second argument indicating which dimension you want the indices for. for i in indices(myarray, 0): for j in indices(myarray, 1): ... or for more abstract notions of dimension: for i in indices(mytable, "rows"): for j in indices(mytable, "cols"): ... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From altis at semi-retired.com Mon Mar 4 17:16:07 2002 From: altis at semi-retired.com (Kevin Altis) Date: Mon, 4 Mar 2002 14:16:07 -0800 Subject: Win32 2.2 & 2.1.2 References: Message-ID: > 2. Install 2.2, then change the file associations to use 2.1.2. And the file associations are under the Tools->Folder Options menu of the Explorer. I think the actual dialog probably differs depending on which version of Windows you're using (I mostly use Win2K), but somewhere in the dialog should be a File Types tab and then a button to edit the associations for a given extension; this is done with the dialog brought up by the Advanced button in Win2K. You shouldn't have to actually dig into the registry with regedit. ka From smonica at compuserve.com Sat Mar 23 21:44:53 2002 From: smonica at compuserve.com (Sexy Monica) Date: Sun, 24 Mar 2002 03:44:53 +0100 (MET) Subject: Customer, Instant Pleasures, Volume 2002 Message-ID: An HTML attachment was scrubbed... URL: From phd at phd.pp.ru Thu Mar 7 04:06:23 2002 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 7 Mar 2002 12:06:23 +0300 Subject: Python daemon instead of CGI programs In-Reply-To: <88bc63c6.0203061444.30ad9c44@posting.google.com>; from writeson@earthlink.net on Wed, Mar 06, 2002 at 02:44:03PM -0800 References: <88bc63c6.0203061444.30ad9c44@posting.google.com> Message-ID: <20020307120623.H17563@phd.pp.ru> On Wed, Mar 06, 2002 at 02:44:03PM -0800, Doug Farrell wrote: > I'm of the opinion this is akin to killing a fly with a sledgehammer > and am thinkin of some other mechanism. One thought that occurred to > me was to create a Python daemon that has a thead pool, a pipe pool > and all the CGI functionality built into classes that could be run by > a thread. PersistenCGI or FastCGI. Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From grante at visi.com Thu Mar 7 21:15:06 2002 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Mar 2002 02:15:06 GMT Subject: how to give an object as argument for a method References: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> Message-ID: In article , Marco Herrn wrote: >> If a function expects a parameter, then it should show up in >> the function definition. Methods are just functions whose >> first parameter is expected to be an object reference. > > Hmm, ok. All you say seems right to me. But what is a bit strange is, > that I explicitly have to implement 'self', but don't give it as argument. Ah, but you do. You just put it before the name of the function: objectName.methodName() | | | \_ This is the function name \ \_ This is the "self" parameter The object who's name is "objectName" also defines the namespace(s) which are to be searched for "methodName". > If a have a method with the defininion 'f(self)' I call this method only > with 'f()'. Nope. You can't call f like that. You have to do either objName.f() or f(objName) > So the declaration doesn't look the same like the call. It can, if you want. > So you think it will stay this way, that one has to implement > it for himself. That's ok. I can live with that. But I don't > see any disadvantage, when changing the language so that a > 'self' statement is always available. -- Grant Edwards grante Yow! If I felt any more at SOPHISTICATED I would DIE visi.com of EMBARRASSMENT! From kragen at pobox.com Thu Mar 14 16:48:13 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 14 Mar 2002 16:48:13 -0500 Subject: new to python - please help References: Message-ID: <837koen7mq.fsf@panacea.canonical.org> "Jason Orendorff" writes: > Rule #1: Post real code. > > I can't make heads or tails of your post because all > that code is so broken. :-/ It's got syntax errors. I feel like I just walked into comp.lang.perl.misc circa 1998. From dk at flexis.de Thu Mar 28 14:57:37 2002 From: dk at flexis.de (domi) Date: Thu, 28 Mar 2002 20:57:37 +0100 Subject: ConfigParser -> Section name through Option value Message-ID: <3CA375B1.9070802@flexis.de> Hi, can somebody help me with this ConfigParser (ini-file) problem: Is it possible to get a Section name through an Option value (ConfigParser), e.g.: [foo] name = python ... how can I get the section name 'foo' through the option value 'python'? Any idea??? thanks dominik From garry at sage.att.com Tue Mar 5 10:45:08 2002 From: garry at sage.att.com (Garry Hodgson) Date: Tue, 5 Mar 2002 15:45:08 GMT Subject: Hosting References: <283adf56.0202201551.7026d548@posting.google.com> <3C838FDA.5016804F@sage.att.com> Message-ID: <3C84E804.4484327F@sage.att.com> Garry Hodgson wrote: > > Kevin Dahlhausen wrote: > > > > Does anyone know of an inexpensive web host that allows compilation > > and use of Python extensions from your own directory? > > i've been happy with http://www.your-site.com/ > > 50 MB Disk Space, 25 POP3 E-Mail Accounts, > 6 Gigs Transfer, Daily Tape back-ups, > E-Mail Control Panel, Frontpage 2000 Extensions, > Private Logs, RealAudio & RealVideo > Detailed Statistics, 99.9% Guaranteed Uptime, > 24/7 FTP Access, your own cgi-bin directory. > > i can login using telnet or ssh and futz around with > directory structures, compile code, etc. i left my > previous host because their support was poor. these > folks have been very responsive, the few times i've had > questions. i forgot to mention, all this is $5/month. -- Garry Hodgson Let my inspiration flow Senior Hacker in token rhyme suggesting rhythm Software Innovation Services that will not forsake me AT&T Labs 'til my tale is told and done. garry at sage.att.com From paulsid at shaw.ca Sat Mar 30 18:40:10 2002 From: paulsid at shaw.ca (Paul Sidorsky) Date: Sat, 30 Mar 2002 16:40:10 -0700 Subject: PEP 285: Adding a bool type: yes, but not as int subtype References: <3CA62CD8.6ABD44D0@accessforall.nl> Message-ID: <3CA64CDA.2AE2B235@shaw.ca> Ype Kingma wrote: > A bool is a bool and an int is an int. > The only relation between them is that they have to be implemented using > bits of a computer. > Python is sufficiently high level not to care about the bits. Wow, wait long enough and somebody will say exactly what you're thinking. I pretty much agree 100% with everything Ype wrote. I am totally in favour of a boolean type. Writing "value = 1" instead of "value = True" has seemed wrong ever since I started with Python. I feel it important to add a definitive "yea" on this since there has been quite a bit of resistance to this PEP so far. However, while I think it'd be great to have a bool type, I think it would be even better to see it done "right" from the start. >From what I have read on python-dev it looks as if the desire to mix ints and bools stems mainly from wanting to preserve backward compatibility. However, it seems to me that allowing ints and bools to be interchanged somewhat is going to create a lot of situations where the two of them get mixed in the same module. Old code will use ints, while newer changes and additions will use True/False as programmers get used to using them in new projects. Maintaining these kind of modules is going to be hell until somebody finally decides to correct everything to the new style. If this is going to be done anyhow, why not at least force people it to be done right the first time? People may gripe at first at having to upgrade code, but in the end they'll be better off than if they hadn't. Hmmm, this seem like a good time to share my own horror story about what can happen when you mix ints and bools. This was in C (not C99 though) so there was no bool type - just like Python is now. I had a program that was storing a bunch of values, and in one part I needed to know if just one particular value was there or not, so of course I had assigned that value 0 and exploited the fact that I could use "!value" to test for it quickly. I needed this result a few times so I assigned it to a variable. Some time later I was adding features and found that in one case I needed to know exactly what the value was, so I modified that part of the program to use the same variable to store the actual value instead of a truth value. This meant that what was 0 (false) would now be a positive integer, and vice-versa. This must have slipped my mind because I got the assignment the wrong way around. This should have broken the program immediately, except that when I was converting the the rest of this part of the program I had missed a negation of the old value. The result was essentially that of applying "value = !(!value)". The program still worked WRT the old truth checks, but was completely unable to determine the actual value where I wanted it to because the value could only be 0 or 1. Needless to say, it took a very long time to track this problem down. This would never have happened if bools and ints were separate types. The extra negation would have meant I was trying to assign a bool to an int and caused an error immediately. Furthermore, I almost certainly would never have _tried_ such a twisted approach to begin with. I did it the way I did because in C I _could_ do it that way. Mixing ints and bools doesn't offer enough protection in my mind. A boolean type that can be partially interchanged with an int might have prevented my nightmare above from happening, but not necessarily. As I said, though, a separate boolean type would have prevented this kind of error from even compiling. Having that kind of protection built into the language is very appealing, at least to me. I admit that in this case above the problem was ultimately the result of my own stupidity. However, if programmers weren't stupid the odd time we wouldn't even need languages like Python because we'd all be able to program in perfect C. Heck, we might not even need C because we could program in perfect assembly. Given that we're not pefect, the job of a high-level language should be to provide more protection for programmers not from lower-level languages, but from themselves. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid at shaw.ca http://members.shaw.ca/paulsid/ From niemeyer at conectiva.com Wed Mar 20 04:45:04 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Wed, 20 Mar 2002 06:45:04 -0300 Subject: ANN: python-bz2 1.0 Message-ID: <20020320064504.A2142@ibook.distro.conectiva> This is the README file of python-bz2. Description ----------- The python bz2 module provides a comprehensive interface for the bz2 compression library. It implements a complete file interface, one shot (de)compression functions, and types for sequential (de)compression. Features -------- python-bz2 provides the following features: o Support for Python newstyle classes, allowing subclassing; o BZ2File implements complete file interface, including readline(), readlines(), xreadlines(), writelines(), seek(), etc; o BZ2File implements emulated seek() support; o BZ2File developed inheriting builtin file type (isinstance(BZ2File(), file) == 1); o Sequential (de)compression supported by BZ2Compressor and BZ2Decompressor types; o One shot (de)compression supported by compress() and decompress() functions; o Complete inline documentation; o Thread safety uses individual locking mechanism; o Comprehensive unit tests. License ------- This module is licensed under the terms of LGPL, read LICENSE for further information. Some portions of code included in the module were based on code included in Python. These parts are clearly stated in the code, and are copyrighted by Python Software Foundation, and licensed under PSF's own license. Read LICENSE-PSF for further information. New Versions ------------ Information on how to retrieve new versions of python-bz2 can be found on http://python-bz2.sf.net Credits ------- The python-bz2 module was developed by Gustavo Niemeyer. Some portions of code included in the module were based on code included in Python. These parts are clearly stated in the code, and are copyrighted by Python Software Foundation, and licensed under PSF's own license. Read LICENSE-PSF for further information. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From jeff at ccvcorp.com Tue Mar 12 13:11:19 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 12 Mar 2002 10:11:19 -0800 Subject: RFC PEP candidate: q''quoted ? References: <3C8523F8.38715E45@ccvcorp.com> Message-ID: <3C8E44C6.E89FF302@ccvcorp.com> Bengt Richter wrote: > The problem to solve is not constructing an arbitrary-valued string > by writing an escaped sequence adhering to current python string syntax. > That can be done, as you show. > > The problem is to do it by using an existing source of text, without > changing the text, and without using an external file to delimit it. My take on all of this is: 1) Only when dealing with Python source code or raw binary data is it likely that triple quotes will be found. Raw binary data is better expressed entirely in quoted hex or octal form, anyhow, to make it clear that it *is* binary, so this change is really only beneficial when quoting Python code. 2) Only when cutting and pasting large sections of Python code (small sections are unlikely to have multiline quotes) to be used as string literals in other Python code, does this quoting problem arise. One can read from a file, import another module, read from a database, etc, etc, without having much worry here; cutting and pasting seems the only case where quotation issues come into play. 3) The need to use arbitrary Python code as a string literal is... well... rather abstruse. It is not something that comes up often, and (ISTM) is confined to relatively specialized tasks. (I can't think of anything other than that code generator you mentioned, and even there, I wouldn't think that *arbitrary* code would be desirable...) 4) Python code that uses both ''' and """ within reasonably-sized stretches of code is pretty rare. 5) Because of (4), most cases of cutting and pasting Python code into string literals can be handled simply by choosing the style of triple quotes that the source doesn't use. To be honest, your example of quoting a segment of code that includes a quoted segment of code seems rather artificial and contrived; I find it hard to imagine a case where this would be desirable, and (ISTM) odds are that any such case would likely be served as well (or better) by some other technique (such as the aforementioned data files, etc.) 6) In most cases where it *is* desirable to quote large sections of Python code, you'd want to be reviewing and modifying and tidying the code *anyhow*. During such tidying, it would not be difficult to normalize the quoted text to use all the same type of triple quotes, or (if they're nested) change one type to be represented as escaped hex. (Note again, as per (4), nested triple quotes seem to be rare.) 7) As a result of all of this, there seem to be vanishingly few cases in which quoting reasonably sized sections of text to use as string literals, can't be accomplished through the use of standard triple quotes. Only when triple quotes are nested within the source text, or when it's impractical to see *what* you're quoting (and why are you quoting it if you don't know what it is?), would the standard triple quotes be insufficient. 8) If we *had* this arbitrary-delimited quote, then many people would feel that they should be used everywhere, even though triple quotes would often do the job just as well (and far more clearly). For example, note how many people want to use eval() and exec to accomplish things that can be done far more simply, cleanly, and safely by using a standard module. I'm sure that the same would happen with arbitrary delimiters. Not only that, but I can well imagine people choosing "clever" delimiters that, while being unique enough to be parseable, don't stand out visibly enough to make it easily apparent where the particular quoted string ends. (As per your previous example, it took me over a minute to figure out where those quotes ended; with triple quotes, it takes me about a second. That's almost two orders of magnitude difference -- to me, that's significant confusion.) In short, I see the need for arbitrarily-delimited string literals to be a very rare, and very specialized thing, and providing special core syntax to deal with this rare special case is both unnecessary and likely to create lots of opportunity for confusion. And (ISTM) there is only one of your conditions which makes current Python syntax unsuitable for the usage you're envisioning -- the desire to not have to actually examine what you're cutting and pasting. (Note that, if you're doing this a lot, it shouldn't be too hard to have a smart editor examine pasted text and create a suitable string literal that can be normally triple-quoted.) Python is intended to be simple and clean; this proposal is (IMHO) neither. Jeff Shannon Technician/Programmer Credit International From gerhard at bigfoot.de Tue Mar 5 10:24:59 2002 From: gerhard at bigfoot.de (Gerhard =?ISO-8859-15?Q?H=E4ring?=) Date: Tue, 05 Mar 2002 16:24:59 +0100 Subject: Get reference to "owner" References: <20020305072655.GA1525@lilith.hqd-internal> <625h8.3294$tg2.206482@e3500-atl1.usenetserver.com> Message-ID: <3C84E34B.1010009@bigfoot.de> Robert Oschler wrote: > Gerhard, > > Excellent!!! Never expected to find a language that could do this and it > something I've wanted very badly for a long time. Yes that's exactly what I > meant. B knows about the A that owns it without having to artificially pass > a reference of A to B during construction. So, if we're really the first ones to invent and implement this pattern, how do we name the baby? The Borg name seems to be already taken ;-) Gerhard From ajs at ix.netcom.com Mon Mar 18 09:57:51 2002 From: ajs at ix.netcom.com (Arthur Siegel) Date: Mon, 18 Mar 2002 09:57:51 -0500 Subject: bug reporting Message-ID: <002301c1ce8d$6a2980e0$0334fea9@carol> >Yes, that is sort of what I am hoping for, when I post stuff here. I've >gotten a lot of "submit it as a bug report" responses, more recently. >Anyhow, the one in the thread you continued this from...I have now >submitted it as a bug report. However, as I continue to work on this >problem (sort of trying to see if I can fix it or at least see if I can >understand what's causing it), I'm not so sure it will end up to be a bug >report after all. It may end up to be a problem in my own code. :/ I ended up posting my issue up to the tutor list, where Danny Yoo picked it up and did the kind of analysis I wouldn't know how to undertake. I know you are active there - so assumedly you saw it. Danny has helped me before, and I was actually figuring I might get his attention to the problem by posting on tutor. He concluded: "In any case, this is definitely a bug in the documentation. Arthur, bring it up on comp.lang.python and Sourceforge again. Someone should really look at your example, since it does seem serious... if not a little obscure. *grin*" I have posted the issue up to sourceforge (but didn't get a nice "submission received" kind of message at the end of the process - hope it made it) Must admit some perverse satisfaction in uncovering something that perhaps has some significance. Bit of a Pythonic coming of age. And thanks, Danny. Art From klaatu at evertek.net Fri Mar 8 16:56:13 2002 From: klaatu at evertek.net (Mike Dean) Date: Fri, 8 Mar 2002 15:56:13 -0600 Subject: Is current integer for-loop syntax a wart? In-Reply-To: ; from jcromwell@ciena.com on Fri, Mar 08, 2002 at 10:26:00AM -0800 References: Message-ID: <20020308155613.B1212@evertek.net> Probably somewhere between Wart? and Not a wart. Python's for loop is very different from that present in C, or any of its derivitave languages. If we don't try to make it the same, it doesn't cause problems (for me, at least). Most of my Python programming has been short, many times one-time scripts for things like data laundering, but never have I had to use range(). I don't see how it's a problem, and seeing the arguments caused by any solution hitherto proposed, I don't think it's worth making a change to the language in this regard. And every time 'special cases' has come up (which seems to be quite common in this particular debate), it's made me think of my recent, brief, and unpleseant journey into the land of Perl. Let's not take Python that direction... -Mike * Cromwell, Jeremy [2002-08-03 10:26]: > PEP 276 (Simple Iterator for ints) and PEP 284 (Integer for-loops), among > others, are written from the perspective that the current integer for-loop > syntax > > for i in range(10): > > is a wart. Is this true? That is, where does the Python community stand on > this issue? > > If you will, please start your response by placing your description of the > syntax in one of these categories. > > -Major wart > This is painful to type and I would support almost any type of improvement. > > -Wart > I don't like the current syntax and would like to see an improvement, but I > could care less. > > -Wart? > What's wrong with it? I guess it could be improved but I never thought > about it. > > -Not a wart > This is the most pythonic way to write an integer for loop. I would oppose > almost any change. > > Not to bias the results, but I'd be just as interested to hear from the > "Wart?" group as any other. > > References > PEP 276, Simple Iterator for ints > http://www.python.org/peps/pep-0276.html > PEP 284, Integer for-loops > http://www.python.org/peps/pep-0284.html > > -Jeremy Cromwell > > -- > http://mail.python.org/mailman/listinfo/python-list From tdi01fhu at syd.kth.se Tue Mar 26 14:37:16 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Tue, 26 Mar 2002 20:37:16 +0100 Subject: Primes.... Message-ID: I am looking for a way(either by finding a module online, or by getting some helpfull hints on how to write this myself) to generate **large** prime numbers. All help is appreciated(Id rather write the code myself since I tend to like understanding the code that I use, but if the math is too heavy I'll have to use other code...) /Fredrik From serge at rohan.sdsu.edu Sun Mar 17 13:22:51 2002 From: serge at rohan.sdsu.edu (Serge Rey) Date: Sun, 17 Mar 2002 10:22:51 -0800 Subject: why python for the academe? In-Reply-To: References: Message-ID: <20020317182251.GM19278@typhoon.sdsu.edu> On Sun, Mar 17, 2002 at 02:57:06AM +0000, Paul Magwene wrote: > On Sat, 16 Mar 2002 21:00:57 -0500, huck wrote: > > > hello all, > > > > i've been lurking for a while and am amused at how many people in the > > list here use python for scientific computing. why not matlab (or octave > > or scilab or whatever)? > > > > > > Speaking only for myself of course - flexibility, extensibility, > readability, and "shareability" -snip- of good points. i would add to the shareability aspect by considering that my students can download python for free. while the same holds for octave and scilab, octave has been a bit more difficult for students to get installed on windows. scilab is a bit easier to install, but there again you do not have as flexible/extensible/readabile a language as you do with python (+numpy). plus, python is just more fun :) -- Serge Rey http://typhoon.sdsu.edu/rey.html Nature is the realization of the simplest conceivable mathematical ideas. - Albert Einstein -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 240 bytes Desc: not available URL: From eric.brunel at pragmadev.com Wed Mar 27 05:20:27 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 27 Mar 2002 10:20:27 +0000 Subject: Tkinter -> spawn external cmd -> return stdout and stderr to back Tkinter References: <3CA0A490.4C88C20C@club-internet.fr> Message-ID: Fabien Henon wrote: [snip] > I use 'spawnv' to fire up POV to start it as a new process. Which > command should I use to get interactive stdout and stderr back to my > Tkinter > application.(do you have any running examples of popen ? the doc is not > clear) I'd use popen3, popen4 or popen (like you apparently tried to do...). The one you choose depends on what you want to do with the command's stdin, stdout and stderr. The simplest is popen4, which returns two opened pipes: one opened for writing on the external command's stdin (which you apparently won't need), the other opened on the external command's stdout and stderr. These pipes are then manipulated like any file opened with the same mode. Try: cmdIn, cmdOut = os.popen4("ls") print cmdOut.readlines() If you need to separate the command's stdout from its stderr, use popen3, which returns 3 opened pipes: one on the command's stdin (opened for writing), one on the command's stdout and one on its stderr (both opened for reading). Try: cmdIn, cmdOut, cmdErr = os.popen3("grep foo *") print cmdOut.readlines() print cmdErr.readlines() Be careful with this one! Since you often can't predict in what order the command will print to its stdout and stderr, you may encounter deadlocks with popen3. Use it only if you're sure that there will be something on both stdout and stderr. You may also mix two of your solutions by using popen with a redirection: cmdOut = os.popen("command 2> /tmp/cmderr.txt", 'r') print cmdOut.readlines() Since you don't use the command's stdin, the plain popen may be enough for your needs. With this solution, you get the command's output directly in cmdOut, and to get the command's stderr, you just have to read the file /tmp/cmderr.txt. As far as I can see, this may be the best solution for you're trying to do... > I also would like to be able to stop the raytrace when it is started. To do this, you need to use the *classes* Popen3 or Popen4 in the popen2 module. These classes are used by the popen2/3/4 functions on Unix, and have an attribute giving the process id of the running process. So if you want to stop it, you just have to kill it using os.kill. See the module popen2 in the library reference. My advice would be to have it working with the functions before trying to use the classes... > I heard about subproc. I can't get to find it in ftp.python.org Don't know anything about that... HTH. Bonne chance! Tu risques d'en avoir besoin... - eric - From mxl at fluent.com Thu Mar 14 17:26:06 2002 From: mxl at fluent.com (Mohammed Lazreg) Date: Thu, 14 Mar 2002 17:26:06 -0500 Subject: [q]Mouse event References: Message-ID: <3C91237D.12B221DD@fluent.com> Just bind your events to create an entry in a file containing the event information.... You might want to take a look at : http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm Actually there is a nice idea behind this: you can bind all the events of the application to register their callback in a file. Next time you run your application you can source this file to watch your application doing exactly what you were doing in the previous run..... This might lead to automatic gui regression testing between two different releases of the same application...... Mohamed John wrote: > Hi, > > Is there any way to record Mouse events (click, double click, and etc.) on > the applications running, using Python? > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > This message has been 'sanitized'. This means that potentially > dangerous content has been rewritten or removed. The following > log describes which actions were taken. > > [ score: 10 ] > 00000 Split long word(s) in header. > > Anomy 0.0.0 : sanitizer.pl > $Id: sanitizer.pl,v 1.35 2001/02/01 00:10:46 bre Exp $ From James_Althoff at i2.com Wed Mar 6 18:05:14 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Wed, 6 Mar 2002 15:05:14 -0800 Subject: PEP 276 -- What else could iter(5) mean? Message-ID: [Bernhard Herzog] > That's not quite right, I think :) > > [f(x) > for x in range((4 in range(3)) in range((2 in range(3)))) > if x in range((x+1 in range(x*2)))] > > would me more like it (but it's late so there may still be a mistake :) ) Thanks (I think ). [James Althoff] > Can you suggest a less contrived example that might be a problem? [Bernhard Herzog] > x, = 1 > > would assign 0 to x instead of raising an error. Agreed. Note that this example has been in the PEP from the beginning. Jim From mkelleghan at ElectricImage.com Thu Mar 14 20:27:36 2002 From: mkelleghan at ElectricImage.com (Mike) Date: 14 Mar 2002 17:27:36 -0800 Subject: How much trouble will I get into ... Message-ID: <1a8cc73d.0203141727.b19f149@posting.google.com> ... if I remove GUSI from Mac Python? I've got a monster app we're trying to embed Python into and having GUSI's version of file I/O along with the MacOS version is just not happening. Any words of wisdom appreciated. thanx Mike :-) From peter at engcorp.com Sun Mar 31 11:07:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 11:07:04 -0500 Subject: Most important extensions? References: Message-ID: <3CA73428.C5770D47@engcorp.com> Aahz wrote: > > In article , > Nick Arnett wrote: > > > >Would sgmllib, htmllib and urllib count as two or three? I mention the > >first two partly because they could benefit from some teaching; I had to > >stare at examples for a while before I grasped what was going on. All three > >replaced quite a lot of my old Perl. Does Tkinter/Pmw count as an > >extension? > > Pmw does, but that's the only one. Sorry for not making clear that I > was specifically referring to 3rd-party extensions. I've found calldll very useful. And standalone ZODB. And wxPython. From skip at pobox.com Thu Mar 7 20:21:15 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 7 Mar 2002 19:21:15 -0600 Subject: Seek fame(*) & fortune(**) as a Python developer In-Reply-To: References: Message-ID: <15496.4619.570284.157464@12-248-41-177.client.attbi.com> >> Whether or not you want to be able to check files into the CVS >> repository, if you want to contribute, you should probably subscribe >> to the python-dev mailing list. You can subscribe here: >> >> http://mail.python.org/mailman/listinfo/python-dev Darrell> Have you changed to acceptance criteria? Yes, I believe python-dev has opened up. Try subscribing again and see what happens. ;-) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From imbosol at vt.edu Sun Mar 31 22:25:00 2002 From: imbosol at vt.edu (Carl Banks) Date: Sun, 31 Mar 2002 22:25:00 -0500 Subject: string copying References: <3CA4F5CB.E8961330@engcorp.com> <3CA6ABB6.71786096@engcorp.com> Message-ID: Peter Hansen wrote: > phil hunt wrote: >> >> On Fri, 29 Mar 2002 18:16:27 -0500, Peter Hansen wrote: >> >The only one I've been able to think of is the surprisingly >> >common situation of trying to consume vast quantities of memory >> >quickly by something like: >> > >> >a = [0] * 1000000 >> >for i in xrange(1000000): >> > a[i] = 'bigstringsuckinguplotsofmemory' >> >> Simpler is range(1000000) > > Yeah, I know. I think you and Aahz missed my (admittedly puny) > point, which was to hypothesize _at least one case_ where it > was conceivably desirable by someone to try to copy a string. Perhaps he wanted to use the strings as some sort of serial number and message in one, i.e., something a not-trying-to-be-clever programmer would implement as a tuple or class. For example: # checking to see if two messages refer to the same event, # in which case print the message only once if a is b: print a else: print a print b -- CARL BANKS http://www.aerojockey.com "Nullum mihi placet tamquam provocatio magna. Hoc ex eis non est." From greg at cosc.canterbury.ac.nz Mon Mar 25 21:25:04 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 26 Mar 2002 14:25:04 +1200 Subject: 2.2 open References: Message-ID: <3C9FDC00.A2D4AABB@cosc.canterbury.ac.nz> Christian Tanzer wrote: > > Curious what you'll say about > you-really-should-have-been-comparing-it-with-in-the-first-place > when `__import__` evolves into a type itself <3/4 wink>. Then I'll say "find a better algorithm". :-) I don't know what the "right" way to do this is. Maybe there isn't one -- it all seems rather hacky to me. Perhaps there should be an ____import____ (that's 4 underscores on each end :-) variable that holds the "real" value of __import__, analogous to sys.stdin/ sys.__stdin__ etc. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From shriek at gmx.co.uk Fri Mar 1 04:02:08 2002 From: shriek at gmx.co.uk (Stephen) Date: 1 Mar 2002 01:02:08 -0800 Subject: Want to monitor process.. References: <87550ef1.0202272315.15779bbd@posting.google.com> <97ae44ee.0202280901.3153bdfc@posting.google.com> <3C7EC9C6.D11FB17@engcorp.com> Message-ID: <97ae44ee.0203010102.14ebf2bb@posting.google.com> > > Unfortunately, my own applications seem to crash as opposed to > > shutdown normally, so it's probably not going to help me. From the > > library reference ~ > > "Note: the functions registered via this module are not called when > > the program is killed by a signal, when a Python fatal internal error > > is detected, or when os._exit() is called. " > > Yikes! "Crash"? Do you really mean they crash the Python interpreter, > or do you mean they exit with an exception? Sorry, I guess I mean "exit with an exception" though to be honest, I still don't know because I haven't been able to run the programs interactively during a 'crash'. The problem seems to be that sometimes a thread can take up to 60 seconds to be dealt with (not by design but because one of the backend systems takes so long to respond) and in the meantime requests keep coming in ~ during peak load (5 requests/sec), this can result in a high number of threads kept open. > If the former, you've got seriously problems, I agree. > > If the latter, just wrap the highest level code with a try/finally > or try/except and put code in to ensure the child processes are > properly terminated. Simple, clean, safe. Will do. I didn't want to put try/except/finally at the highest level of code yet since we're actually in Beta and I want to know when my server encounters a problem. Problem has been that not running it in interactive mode, I've missed the reasons for the failures. That's why I also asked about logging recently. > My Python programs *never* crash (as in kill the interpreter) > but maybe that's just me... I doubt it. I doubt it too. More likely my error handling isn't sufficient. Stephen. From phlip_cpp at yahoo.com Wed Mar 27 01:04:17 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 27 Mar 2002 06:04:17 GMT Subject: Tkinter: Why won't it work? References: Message-ID: A.Newby wrote: > > > Hi. > > Below is an example exercise from "An Introduction to Tkinter" by Fredrik > Lundh. It simply creates a box with a quit button in it. Problem is, > everytime I click Quit, the program freezes. Does Freddy specify he got these working on Linux? > self.button = Button(frame, text="QUIT", fg="red", > command=frame.quit) I suspect you can change that to command=frame.destroy and it will go away. The problem may have been 'quit' turned off 'mainloop', but the window still existed. -- Phlip http://www.greencheese.org/HatTrick From john at yahoo.com Sun Mar 24 13:12:34 2002 From: john at yahoo.com (John Warney) Date: Sun, 24 Mar 2002 18:12:34 GMT Subject: is there gonna be a Core Python Programming 2e ? References: Message-ID: >I know that Wes is gearing up to work on the second edition; I'll pass cool >this on to him (he doesn't read c.l.py regularly these days). However, ye, i have seen him reply to a few posts but not many >I'll have to note that this is more up to the publisher than the author. ye, i have seen all the CORE series with the same binding and i hate it, same with O'Reilly books. If its a paperback i like the binding that is on Linux Firewalls books. If its hardback i like the binding thats on the Sybex books. This is me personally, since it is easier on the book in the long run and it keeps the pages cleaner. Rob From torppa at polykoira.megabaud.fi Tue Mar 12 12:25:32 2002 From: torppa at polykoira.megabaud.fi (Jarkko Torppa) Date: Tue, 12 Mar 2002 17:25:32 +0000 (UTC) Subject: How do you conver output of "popen('ls')" to a list? References: <3C737245.BC5D7164@macrozon.net> Message-ID: In article , Wojtek Walczak wrote: >** Since micro$oft is stupid it doesn't mean >** that you should be stupid too - do NOT toppost. >Dnia Wed, 20 Feb 2002 10:54:13 +0100, husam napisa?(a): >>thanks for reply. > >--------- >#!/usr/local/bin/python2.2 > >import os > >blah = os.popen('ls').read() >i,n,tabl,blen=0,0,[],len(blah) > >while i < blen: > tmp = i > i = blah.index('\n', i) > tabl.append(blah[tmp:i]) > n+=1 > i+=1 > >for a in tabl: > print a >--------- What's wrong with: >> [ x[:-1] for x in os.popen('ls').readlines() ] or better yet (no fork tax) >> os.listdir('.') -- Jarkko Torppa, Elisa Internet From robin at jessikat.fsnet.co.uk Sat Mar 23 05:34:17 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 23 Mar 2002 10:34:17 +0000 Subject: New SIG on logic/CLP programming in Python References: <59667b81.0203221433.261c8210@posting.google.com> Message-ID: <1hg8f0ApoFn8EwlT@jessikat.fsnet.co.uk> In article , Peter Norvig writes >I have some simple, inefficient CSP code in Python at >http://www.norvig.com/python/csp.html > >Includes fintie domain backtracking search (with optional forward >checking, domain ordering, and variable ordering); hill-climbing >min-conflicts search; examples from map coloring, n-queens, and the >zebra puzzle. > >-Peter > > ..... so I guess I need to know what search and utils are or can CSP discover that? -dazed and confused-ly yrs- Robin Becker From anthony at ekit-inc.com Wed Mar 13 20:26:58 2002 From: anthony at ekit-inc.com (Anthony Baxter) Date: Thu, 14 Mar 2002 12:26:58 +1100 Subject: Zope In-Reply-To: Message from Bernard Yue of "Thu, 14 Mar 2002 00:20:39 GMT." <3C8FED4D.A8C0470@3captus.com> Message-ID: <200203140126.g2E1Qw122298@burswood.off.ekorp.com> > Are there anybody using Zope 2.4.3 with Python 2.2 in production > environment? Problems? PythonScripts will fail and cause Zope to shutdown with that combination. Python2.2 is also not the recommended version for Zope 2.4 or 2.5. Use Python2.1.2, and Zope2.4.4b1, or Zope 2.5.x Anthony -- Anthony Baxter It's never to late to have a happy childhood. From s.schwarzer at ndh.net Sun Mar 17 17:01:27 2002 From: s.schwarzer at ndh.net (Stefan Schwarzer) Date: Sun, 17 Mar 2002 23:01:27 +0100 Subject: Sharing code between instance and class methods Message-ID: <3C951237.A28EB624@ndh.net> Hello, I would like to be able to set the same variable for an instance or for its class. Someting like: class X: def set_in_instance(self, value): self.data = value def set_in_class(cls, value): cls.data = value set_in_class = classmethod(set_in_class) However, if the code to set the value involves several calls of other methods, the code duplication would become awkward: class X: def set_in_instance(self, value): self.meth1(value) self.meth2(value) x = self.meth3(value) self.data = self.meth4(x) def set_in_class(cls, value): cls.meth1(value) cls.meth2(value) x = cls.meth3(value) cls.data = cls.meth4(x) set_in_class = classmethod(set_in_class) One possibility I can imagine is to put the common code into a static method: class X: def set_static(obj, value): obj.meth1(value) obj.meth2(value) x = obj.meth3(value) obj.data = obj.meth4(x) set_static = staticmethod(set_static) def set_in_instance(self, value): self.set_static(self, value) def set_in_class(cls, value): cls.set_static(cls, value) set_in_class = classmethod(set_in_class) Is there a more direct way to accomplish the same? (In a concrete case, the class method should only be in a derived class, and I have a dislike to modify the base class to support the per-class operation in the derived class.) Thanks in advance for your help. Stefan From jimd at vega.starshine.org Thu Mar 21 06:31:14 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 21 Mar 2002 11:31:14 GMT Subject: Newbie: word count and Win32 References: Message-ID: In article , Joe Christl wrote: >On 19 Mar 2002 20:26:34 GMT, bokr at oz.net (Bengt Richter) wrote: >>From a quick look that[1] script, it looks like it expects to read >>from stdin only. I.e., it says >> # iterate over each line on stdin >> for line in sys.stdin.readlines() : >> ... ... >>To make the script work like what you expected, it needs to look >>at the command line arguments (sys.argv) for a file name and open that, >>and use the resulting file object in place of stdin. >He gave a a diff output for it to accept a filename. I am going to try that >first and report back, for i in sys.argv[1:]: try: file = open(i,'r') for line in file: ... except IOError: pass ... that's about the simplest way to iterate over each in in each file. Within the last couple of days I posted a script that implements the GNU "wc" (word count) program in Python with full support for the GNU command line options. That script shows an example of how to selectively use stdin (if no non-switch/option arguments are present) or to iterate over a list of files. My script is slightly UNIX-centric --- but it might work on Windows or Mac (if os.path.isdir() is sufficiently similar and getopts works). I think os.path.isdir() is the only OS specific function I used. Of course the UNIX/GNU wc command only counts the total number of "words" (whitespace separated things), lines, and characters in a file or set of files. It doesn't provide a count of individual words. Tonight I wrote a "wordcount.py" program that counts "words" and "knownwords" (if you have a suitable list under /usr/share/dict/words --- as most UNIX and GNU/Linux systems will) and then dumps a sorted list of all non-unique "words" (sequences of letters, possibly hyphenated or with apostrophes, as in "o'clock"). It keeps counts of the words that it processed, the number that it added to it's dictionary, and the number that it found in "knownwords" dictionary and prints summaries and ratios of those. >>BTW, IMO you get a nicer ouput if you change the last line of the script to >> print '%6d: %s' % (words[word], word) >I don't really care too much about the amount of times a word shows up. I'll >try it his way and yours. :) I missed what you're actually trying to do. >>Regards, >>Bengt Richter >Thanks, >Joe Christl From mlerner at zektor.gpcc.itd.umich.edu Wed Mar 13 17:39:58 2002 From: mlerner at zektor.gpcc.itd.umich.edu (Michael George Lerner) Date: Wed, 13 Mar 2002 22:39:58 GMT Subject: YANRQ (yet another regex question) Message-ID: <2zQj8.409$zT5.12612@news.itd.umich.edu> Howdy, I have a regular expression that looks vaguely like this: r = re.compile(r'''(?Pstart)(?P foo)(?Pend)''') but the middle pattern isn't quite what I want. I know that foo will be a string that is seven characters long and contains 'foo' surrounded by spaces. That is, it could be any of these: 'foo ' ' foo ' ' foo ' ' foo ' ' foo' I'd like to rewrite my regular expression to match any of these, and I'd really rather not write it all out like this: (?P(foo | foo | foo | foo | foo|) Is there some easy way to do this that I've overlooked? thanks, -michael From fdrake at acm.org Fri Mar 29 17:48:51 2002 From: fdrake at acm.org (Fred L. Drake) Date: Fri, 29 Mar 2002 17:48:51 -0500 (EST) Subject: [development doc updates] Message-ID: <20020329224851.02DAD18EAD1@grendel.zope.com> The development version of the documentation has been updated: http://python.sourceforge.net/devel-docs/ Started to update the Extending & Embedding manual with information on the new support for types. There's still a long way to go -- contributions welcome! From Francois-regis.Chalaoux at sanofi-synthelabo.com Mon Mar 4 13:23:13 2002 From: Francois-regis.Chalaoux at sanofi-synthelabo.com (Francois-regis Chalaoux) Date: Mon, 4 Mar 2002 19:23:13 +0100 Subject: question about an installation of a new module Message-ID: <"020304203918Z.WT13248. 28*/PN=Francois-regis.Chalaoux/O=RESEARCH/PRMD=SANOFI/ADMD=ATLAS/C=FR/"@MHS> Hi All, After my 'configure', 'mak' and 'make install' of Python , I modified the 'Setup' from Module directory and then I ran 'make' as explained in the README.txt. However, should I run again 'make install' again after this modification ? FR From GetCapsOffDomain Fri Mar 1 06:08:58 2002 From: GetCapsOffDomain (Javier) Date: Fri, 1 Mar 2002 12:08:58 +0100 Subject: wiin32clipboard "odd" behaviour?? Message-ID: Hi all!! I am experiencing a "strange" thing when trying to use the win32clipboard module that comes with Active State's Active Python distro... The thing is, I want to "load" a list of strings to the "main" clipboard (thing loading a list of alternate URLs to clipoard managers like GetRight :-) The thing is, I OpenCliboard(), I SetClipboardText(text) and I can GetClipboardData(format), but I can't "get" the clipboard data from outside apps (not even after I've CloseClipboard() )... It seems like I've gotten a "new" clipboard all for myself... So, what would I have to do to manage things "as usual"?? Ideas, pointers?? TIA Javier ---- To be, or not to be. *BOOM!* Not to be. From bp at sam.localdomain Fri Mar 1 13:25:36 2002 From: bp at sam.localdomain (Bob Parnes) Date: Fri, 01 Mar 2002 18:25:36 -0000 Subject: Mod-python problem References: Message-ID: On 1 Mar 2002 03:34:10 -0800, Alan Kennedy wrote: >bp at sam.localdomain (Bob Parnes) wrote in message > >> The only trouble is that I had forgotten about my httpd.conf file. The >> relevant lines are: >> >> >> AddHandler python-program .py >> PythonHandler mod_python.publisher >> >> >> This was the reason I used main() instead of handler(); in the url window I >> typed in "test.py/main" and got the table but no response from FieldStorage(). > >> Are publisher and FieldStorage() incompatible, or am I misusing them? Knowing >> what I know now, I can probably get along without publisher, but I am >> accustomed to placing several scripts in one directory. > >Bob, > >Sorry, I didn't realise you were using the Publisher handler, >otherwise I wouldn't have gone and rewritten your code to work with a >completely different paradigm. And I was wondering how you were >getting results with something that just didn't look like it could >work %-) D'oh! Silly me. > >Warning: I don't use the publisher handler, so I haven't tested any of >the stuff below! > >Looking at the publisher handler documentation, section 6.1.3: >Publisher handler: Form data > >http://www.modpython.org/live/mod_python-2.7.6/doc-html/node74.html > >which says: > >"In the process of matching arguments, the Publisher handler creates >an instance of FieldStorage class. A reference to this instance is >stored in an attribute form of the Request object. > >Since a FieldStorage can only be instantiated once per request, one >must not attept to instantiate FieldStorage when using the Publisher >handler and should use Request.form instead." > >So it would appear to me that you shouldn't be trying to instantiate >the util.FieldStorage() class at all. Instead, you should be referring >to the already extant req.form attribute. So your main function should >change from this > >def main(req): > formDict = util.FieldStorage(req) > cl = clTest() > return cl.cltest(req, formDict) > >to this > >def main(req): > cl = clTest() > return cl.cltest(req, req.form) > >As mentioned, I haven't tested any of this! > >Hope this helps, > >Al. It works great. Thank you so much. I am ashamed to say that I have the documentation, but somehow. I overlooked section 6.1.3 Bob -- Bob Parnes rparnes at megalink.net From samschul at pacbell.net Sun Mar 31 18:43:30 2002 From: samschul at pacbell.net (Samuel Schulenburg) Date: 31 Mar 2002 15:43:30 -0800 Subject: Accessing CVS on SourceForge? Message-ID: How do you access a particular python realease on SourceForge? I can obtain the latest realease by following the instruction provided at SourceForge, but I would like to obtain Python2.2 or 1.52. Thanks in advance. Samuel Schulenburg From BPettersen at NAREX.com Fri Mar 1 08:42:59 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 1 Mar 2002 06:42:59 -0700 Subject: Status of PEP's? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019221514A@admin56.narex.com> > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > In article , > James_Althoff at i2.com wrote: > > > For example, one problem I had when playing with an experimental > > implementation of the "middle argument" variant mentioned above is > > that the specific relational operators are tied to the > values of the > > bounds. If you want to iterate from the smaller value (up) to the > > larger value you write: > > > > for 1 <= var < 5: > > > > whereas if you want to iterate from the larger value (down) to the > > smaller value you have to turn things around and write: > > > > for 5 > var >= 1: > > > > which all looks very nice when you are dealing with literal > constants. > > But suppose you have variables for the bounds, "start" and "end"? > > Let's say I have a function > > > > def doSomethingFromTo(start,end): > > > > The function has to test to see which of "start" and "end" is the > > smaller value in order to know whether to execute a > for-loop with "<" > > or a for-loop with ">" (and the code specified in each separate > > for-loop has to be written redundantly). I found this to > be awkward. > > What's wrong with > for min(start,end) < var < max(start,end) Nothing at all, but with this syntax you have different semantics for: for start <= i < end: And if start <= i < end: One being an iterative construct, the other being a 'simple' comparison. I find that at least as confusing as integers producing iterators in iterative constructs. Of course, if anyone actually cared about this syntax, we would have a PEP with a pro/con section, so we wouldn't have to reiterate the same arguments over and over again -- bjorn From rnd at onego.ru Thu Mar 7 05:27:20 2002 From: rnd at onego.ru (Roman Suzi) Date: Thu, 7 Mar 2002 13:27:20 +0300 (MSK) Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <31575A892FF6D1118F5800600846864DCBCD8B@intrepid> Message-ID: On Thu, 7 Mar 2002, Simon Brunning wrote: > > From: Geoff Gerrietts [SMTP:geoff at gerrietts.net] > > For the space of around three years, a child is immersed almost > > constantly, from waking to sleep, and even sometimes while asleep, in > > language. For those first three years, the child is almost completely > > incapable of making him or herself understood. Are you sure? My daughter makes herself understood by all available means. She built her own dictionary which we, parents, learned. What is interesting, she uses (internally) a hash table to convert from our language to her almost instantly... Our observations tell us that children differ in their ways. E.g. some of them unthinkingly repeat lots of words and even sentences, while our child uses only what she understands. Some others do not talk at all and then at once speak clearly in sentences. I guess, adults can also be categorized by their approach in learning languages. And trial-and-error is, IMHO, also needed to learn computer languages. I can't imaging someone writing right from the start after studying docs and specs. I do not remember who told me this, but it seems that students better learn from poorly constructed lectures than perfect ones. Because, they need to be _active_ in constructing their own system rather than _passively_ "eat" readymaid knowledge frames. So, a bad book (with errors, inconsistencies, etc) is not necessary bad for learning purposes (if it covers enough of a subject). > So I don't think that computer languages can be learned in the same way as > natural languages. Children learn language by a combination of instinct and > trial-and-error. We don't *have* a computer language instinct - only Guido > has one of those - and trial-and-error will just mean > trial-and-syntax-error. IMHO, children do not only learn language, they also build their interpreter for themselves as nobody provide them with the source, only flying in the air binaries ;-) Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From akuchlin at ute.mems-exchange.org Wed Mar 6 16:05:59 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 06 Mar 2002 21:05:59 GMT Subject: Web scripting with Python (1st post here, also :-) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> Message-ID: In article <40c3f5da.0203061114.18f7fea6 at posting.google.com>, Julio Nobrega wrote: > Well, enough is enough, isn't? Where do I start? It's for a weblog > (Kuro5hin-like) system. > Anyone have a tip for me? Examples? Squisdot is the way to go? Do you want to *write* a Weblog-like system, or just *use* one? If you just want to use one, then Squishdot is the only alternative in Python that I'm aware of, and it requires Zope. If you want to write your own, then there are lots of different Web programming frameworks for Python. I like Quixote best (http://www.mems-exchange.org/software/quixote/) but then I'm also one of the developers. Paul Boddie has a list of frameworks at http://www.infector.com/Paul/Python/web_modules.html . --amk (www.amk.ca) Thou hast made the Furies cry, Orpheus. They will never forgive you for that. -- Queen Persephone, in SANDMAN: "The Song of Orpheus" From marknenadov at winningteam.com Fri Mar 29 17:41:52 2002 From: marknenadov at winningteam.com (Mark Nenadov) Date: Fri, 29 Mar 2002 17:41:52 -0500 Subject: GUI programming References: <20020329.173950.1469262009.25190@d57-36-119.wido3.on.cogeco.ca> Message-ID: <20020329.174152.1548348142.25190@d57-36-119.wido3.on.cogeco.ca> In article <20020329.173950.1469262009.25190 at d57-36-119.wido3.on.cogeco.ca>, "Mark Nenadov" wrote: > I would personally recommend wxPython. I believe that wxPython is more > modern and feature rich. It also doesn't depend on another scripting > langauge (TCL). Just to clarify things, I ment to say that wxPython doesn't rely on another scripting language like TkInter does (TkInter relies on TCL). Good day, ~Mark Nenadov (www.freelance-developer.com) From grey at despair.dmiyu.org Wed Mar 6 17:00:14 2002 From: grey at despair.dmiyu.org (Steve Lamb) Date: Wed, 06 Mar 2002 22:00:14 -0000 Subject: PEP 284, Integer for-loops References: Message-ID: On Wed, 06 Mar 2002 08:41:31 -0800, David Eppstein wrote: > One of the most common uses of for-loops in Python is to iterate > over an interval of integers. Python provides functions range() > and xrange() to generate lists and iterators for such intervals, > which work best for the most frequent case: half-open intervals > increasing from zero. However, the range() syntax is more awkward > for open or closed intervals, and lacks symmetry when reversing > the order of iteration. In addition, the call to an unfamiliar > function makes it difficult for newcomers to Python to understand > code that uses range() or xrange(). > The perceived lack of a natural, intuitive integer iteration > syntax has led to heated debate on python-list, and spawned at > least four PEPs before this one. Perceived lack. IE, this is a solution looking for a problem. I read it and really have to ask.... why? If people have a problem with it they just need to flip open their Python book and take a few seconds to look it up. Also the proposal takes a nice line-noise approach to it. I want line noise, I'll use Perl or Brainfuck. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your ICQ: 5107343 | main connection to the switchboard of souls. To email: Don't despair! | -- Lenny Nero, Strange Days -------------------------------+--------------------------------------------- From bh at intevation.de Wed Mar 6 16:37:29 2002 From: bh at intevation.de (Bernhard Herzog) Date: 06 Mar 2002 22:37:29 +0100 Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: <6qu1rtfkdi.fsf@abnoba.intevation.de> James_Althoff at i2.com writes: > [huaiyu] > > "spam".append("eggs") > > x, y, z = "d" > > x, y, z = 3 > > [f(x) for x in (4 in 3) in (2 in 3) if x in (x+1 in x*2)] # just for fun. > :-) > > Fun? Ok, if you say so. > > But just to make sure I understand your point, I guess you are saying the > above is bad because today's equivalent is more clear? > > [f(x) for x in range((4 in range(3))) in range((2 in range(3))) if x in > range((x+1 in range(x*2)))] That's not quite right, I think :) [f(x) for x in range((4 in range(3)) in range((2 in range(3)))) if x in range((x+1 in range(x*2)))] would me more like it (but it's late so there may still be a mistake :) ) Anyway, I think that booleans will be iterable too could be problematic. OTOH, that they're ints could be considered problematic too but hasn't actually been a problem AFAICT. > Can you suggest a less contrived example that might be a problem? x, = 1 would assign 0 to x instead of raising an error. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://mapit.de/ From just at xs4all.nl Sun Mar 24 12:48:19 2002 From: just at xs4all.nl (Just van Rossum) Date: Sun, 24 Mar 2002 18:48:19 +0100 Subject: 2.2 open References: <1UtsCLAcngn8EwWc@jessikat.fsnet.co.uk> Message-ID: In article <1UtsCLAcngn8EwWc at jessikat.fsnet.co.uk>, Robin Becker wrote: > >> So open is now a file? That seems a bit odd to me. > > > >Correction: open is the type of file. > > > >> It seems that some built ins now have the type of the object they > >> create. Pretty weird logic. > > > >Correction: some built ins are the type of the object they create. > > > >Notice that in 2.2 types and classes are unified. > > > yes I heard about that, but the semantics seem strange to me. > open is not a file it is a function that produces an open file. It still isn't a file (as Pearu tried to tell you), it's a factory for files. In 2.2 types are more like classes, in that calling a type object with the right arguments creates an object of that type. > It's now > not even amongst the built ins. > > what does X==type(X()) imply? It's more or less the same as X == X().__class__ (Also note that open is now an alias for the new "file" builtin, which considering how things now work is the more logical name. The builtin functions int, float and str (among others) are olso type objects these days.) Just From tim.one at comcast.net Thu Mar 7 15:46:46 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 07 Mar 2002 15:46:46 -0500 Subject: Bug in the standard module random ? In-Reply-To: <3C8791B1.6BBC1981@Spam.Please> Message-ID: [Weet Vanniks] > The gammavariate function of the standard module is documented as > taking two parameters ... You can follow the drama here: From jmarshal at mathworks.com Fri Mar 8 08:48:16 2002 From: jmarshal at mathworks.com (Joshua Marshall) Date: 8 Mar 2002 13:48:16 GMT Subject: threads killing other threads References: <1013105970.135322@cswreg.cos.agilent.com> <3C62E0D5.99C586DF@ccvcorp.com> Message-ID: If outright killing is disallowed, I'd still like to see the ability for one thread to cause an exception to be thrown in another. Currently you can do this to the main thread (on UNIX) by using process signals. dman wrote: > Here's an analogy : > If someone is sitting on the toilet, then you come and kill him, how > is he supposed to flush? > Processes can be killed by other processes since their resources are > separate and the kernel can "flush" for the now-dead process. With > threads, there is one process and all resources are shared. No one is > left around to "flush". From usenet at thinkspot.net Wed Mar 13 23:39:54 2002 From: usenet at thinkspot.net (Sheila King) Date: Wed, 13 Mar 2002 20:39:54 -0800 Subject: Performance problem with filtering References: Message-ID: On Thu, 14 Mar 2002 15:06:09 +1100, "Delaney, Timothy" wrote in comp.lang.python in article : > Bah ... > > results = filter(lambda k: not c.has_key(k), b) > > That will slow it down a bit (using the lambda) but will give the right > result ;) How does something with list comprehensions compare? Like: b = [entry for entry in b if entry not in a] Is this as slow as the original method suggested? Or is it closer to dictionary performance? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From python at rcn.com Mon Mar 11 13:42:58 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 11 Mar 2002 13:42:58 -0500 Subject: [ANN] PEP 279 version 1.6 Message-ID: PEP 279 -- Enhanced Generators has been updated: http://python.sourceforge.net/peps/pep-0279.html Comments are invited on the revised PEP. The changes were driven by comments from GvR, from the authors of PEP 255, and from members of the Py-Dev maillist. The principal changes from the previous version are: 1. Rationale section focused on generator usage instead of lazy evaluation. 2. The proposal for four builtins has been reduced to one. Xzip, xfilter, and xmap are retracted. Expanded the discussion of the remaining proposed builtin, indexed(). 3. All sections expanded to include comments received from GvR and the PEP 255 authors (the experts on the existing generator implementation). 4. Proposal for generator exception passing moved up one section. 5. Proposal for generator parameter passing listed as deferred -- everyone thinks this may be a viable idea but it doesn't have a chance in the near-term. 6. The restartability discussion has been deleted -- Guido thought it was evil. Raymond Hettinger Addenda Here are comments from Magnus Lie Hetland which were received after the PEP was updated: > I like indexed() a lot; +1. I'm quite happy to have it make PEP 281 > obsolete. Adding a separate module for iterator utilities seems like a > good idea. > > Generator comprehensions seem mildly useful, but I vote +0. Defining a > separate, named generator would probably be my preference. On the > other hand, I do see the advantage of "scaling up" from list > comprehensions. > > Even though I cannot speak for the ease of implementation, I vote +1 > for the exception passing mechanism. > > I like the generator parameter passing mechanism. Although I see no > need to defer it, deferral seems to be the most likely scenario, and > in the meantime I guess the functionality can be emulated either by > implementing the generator as a method, or by passing a parameter with > the exception passing mechanism. > > I guess there is no real need to comment on restartability, but I > can't see that I have any need for it. From tjl3 at cornell.edu Fri Mar 29 12:06:55 2002 From: tjl3 at cornell.edu (Tim Lynch) Date: Fri, 29 Mar 2002 12:06:55 -0500 Subject: problem getting xmlrpclib example to work Message-ID: <3CA49F2F.DE642F22@cornell.edu> Could someone get me pointed in the right direction? I've been banging my head for over a day now trying to get an example xml-rpc cgi-based server to work. Specifically, I'm trying to get the example from O'Reilly's "XML-RPC Web Services" book, pg 137, ex. 6-3, to work. I've copied the code from www.ora.com for ex 6-3 to my cgi-bin directory, it's included at the end of this message. I've tried the code on several different Linux installations, running Python 2.1.1 and 2.2 all with the same results. Here's the test script to exercise the cgi script: ---- #!/usr/bin/python import xmlrpclib server = xmlrpclib.Server('http://localhost/cgi-bin/xmlrpc.py') print server.Describe('xxx') ---- And here's the traceback I get: Traceback (most recent call last): File "./tst.py", line 6, in ? print server.Describe('xxx') File "/usr/local/lib/python2.1/xmlrpclib.py", line 547, in __call__ return self.__send(self.__name, args) File "/usr/local/lib/python2.1/xmlrpclib.py", line 630, in __request request File "/usr/local/lib/python2.1/xmlrpclib.py", line 582, in request headers xmlrpclib.ProtocolError: Here is the cgi code: ---- #!/usr/bin/python # xmlrpc_cgi.py import xmlrpclib import os, sys, string #### HTTP message templates success_msg = """ HTTP/1.1 200 OK Content-type: text/xml Content-length: %d %s """ failure_msg = """ HTTP/1.1 500 Internal Server Error - x.py """ #### functions that implement XML-RPC API def do_SetColor(shape_type, shape_id, color_tuple): return "hello from do_SetColor" def do_Describe(*one_or_more_args): return "hello from do_Describe" def call(meth_name, arg_tuple): """ XML-RPC method dispatcher """ myAPI = ("SetColor", "Bounce", "Describe") if meth_name in myAPI: func_obj = eval("do_" + meth_name) return apply(func_obj, arg_tuple) else: raise xmlrpclib.Fault(123, "Unknown method name") ##### main program if __name__ == "__main__": try: # get arguments data = sys.stdin.read( ) fh = open("/tmp/xmlrpc.cgi.log", 'w') fh.write(data) fh.close() params, method = xmlrpclib.loads(data) # generate response try: response = call(method, params) if type(response) != type(( )): response = (response,) except xmlrpclib.Fault, faultobj: # generated response was a Fault response = xmlrpclib.dumps(faultobj) except: # report exception back to server response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)) ) else: # no exception occurred: # send method's return value back to server response = xmlrpclib.dumps( response, methodresponse=1 ) except: # internal error, report as HTTP server error print failure_msg else: # no internal error: send back a "success" response print success_msg % (len(XML_response), XML_response) ---- What's really annoying is that I've got equivalent Perl code working on the same machines I've tested this code. Tim Lynch Mann Library Cornell University Ithaca, NY 14853 From aahz at panix.com Thu Mar 7 21:24:54 2002 From: aahz at panix.com (Aahz Maruch) Date: 7 Mar 2002 18:24:54 -0800 Subject: threads killing other threads References: <1013105970.135322@cswreg.cos.agilent.com> Message-ID: In article , Les Smithson wrote: > "Aahz" == Aahz Maruch writes: >> In article , >> Les Smithson wrote: >>> >>> I'm sure there's a good reason for Python not implementing >>> this. Anyone know what it is? >> >> Yes. It doesn't work. >> >> Oh, sure, there's a long technical explanation of how arbitrarily >> killing threads leaves processes in various kinds of weird states, >> but it all boils down to, "It doesn't work." That goes double for >> any kind of cross-platform facility. Note that Java has pretty much >> abandoned any pretence that it can provide this capability. > >But doesn't pthread_testcancel allow cooperative threads to be >canceled? This is the portable equivalent to the thread signaling >scheme described earlier. It also gives the canceled thread a chance to >clean itself up before exiting. > >Not ideal, but better than nothing. After looking this up, I see two basic problems with this: * Doesn't work with extensions unless the extension writer cooperates. * Don't see any direct equivalent in Win32. Solaris native threads don't support this; I don't know off-hand whether Python uses pthreads on Solaris. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From shareselect at hotmail.com Sat Mar 16 12:20:57 2002 From: shareselect at hotmail.com (Al) Date: 16 Mar 2002 09:20:57 -0800 Subject: Help Setting PATH w/Python and Win98 Message-ID: Hi I am new to programming and am currently doing a Python Tutorial at http://softwaredev.earthweb.com/sdopen/article/0,,12382_626311,00.html On that page it says I must set the path in Windows to the directory where the Python.exe is located so that I can execute Python script. I can get around DOS a bit to do this but not sure how to do it exactly. Could someone tell me what I must do? Also it says I must make the directory containing my first script file my CURRENT DIRECTORY from the COMMAND PROMPT IN DOS. How do I do this too? Thanks Al From gmcm at hypernet.com Sat Mar 23 10:05:18 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 23 Mar 2002 15:05:18 GMT Subject: circular imports (don't yell!) References: Message-ID: jimh wrote: > We have a scenario where we have (and need) circular imports, that is, > A imports B imports C imports A. Now I know there are ways around > this, but we have external dependencies that make it very difficult to > use an alternative, so don't be yelling at me about the design ;) > > I have whittled the problem down to 3 files: > > a.py > ------ > from b import * > from c import * > consta = 3 > if __name__ == "__main__": > print consta > print constb > print constc > > b.py > ------ > print "in b" > from c import * > constb = 4 > constb2 = constc + 10 > > c.py > ------ > print "in c" > from a import * > constc = 5 > > As these are given here, it works. Note that a.py is running as __main__. The import in c.py gets a different copy (check out sys.modules at the end to prove it). So you don't have a circular import. __main__ imports b b imports c c imports a a imports b (already loaded) a imports c (already loaded) __main__ imports c (already loaded) > But if I switch the order of the > two imports in a.py, it doesn't work: > > Traceback (most recent call last): > File "a.py", line 2, in ? > from c import * > File "c.py", line 2, in ? > from a import * > File "a.py", line 3, in ? > from b import * > File "b.py", line 5, in ? > constb2 = constc + 10 > NameError: name 'constc' is not defined > > I think this is what is happening: > - a imports c so c is marked as "loaded" Not exactly. In effect, c is marked as "loading". > - c imports a > - a imports b > - b imports c, but c is already marked as "loaded", however, it > hasn't > REALLY been loaded, thus constc is not yet defined. About right (the import of c in b doesn't do anything, because c is "loading"). But you haven't accounted for the difference between __main__ and a. __main__ imports c c imports a a imports c (loading) a imports b b imports c (loading) and you die here because b wants c.constc. So changing b to print "in b" import c constb = 4 constb2 = c.constc + 10 gets you closer, but still doesn't work. That's because c hasn't finished loading at the time c.constc is evaluated. But that's probably an artifact of your test. In real life, references to c.contc are likely to be inside functions or methods, and the revised code would work. The lesson being that with circular imports, not everyone can use "from ... import ...". Somebody has to do a plain "import ...". (And don't forget __main__). -- Gordon http://www.mcmillan-inc.com/ From rnd at onego.ru Thu Mar 7 05:31:37 2002 From: rnd at onego.ru (Roman Suzi) Date: Thu, 7 Mar 2002 13:31:37 +0300 (MSK) Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: <3C8623B9.3000504@sympatico.ca> Message-ID: On Wed, 6 Mar 2002, Ramkumar Kashyap wrote: > non-intuitive manner and lose out on a big chunk of their audience. > Only a few of us that persevere, end up learning the language and even > fewer go on to achieve "GURU" status. Why is this? > > I have seen several posts on CLP and the newbie tutors list, where > people mention that their first encounter with programming was in BASIC, > COBOL, Pascal, Fortran. They did not really make any progress, gave up > on programming. Now they are attempting once again, hoping things have > become a little easier. I think, the initial language has nothing to do with later gaving up programming. These same thoughts bother me for several years already and I came to the decision that almost nothing does matter: only motivation to continue learning programming. Then certain barrier falls and a person is from that point capable of programming (in any language, as it is universal skill). It's like mastering bicycle or learning to swim. > I would like to know how the pattern was set to teach programming > languages. You do an introductory program like "Hello World", learn how > to compile and run it. Then jump into decision structures, loops, > functions, etc. > > This is extremely non-intuitive to most people. Most 5,6,7 year olds > can speak fluently in their native languages, but how many of them could > tell you about vowels, consonants, nouns, verbs, adjectives. In fact > quite a few of them speak multiple languages, can easily differentiate > sentence structures in those languages, but would be hard-pressed to > give defintions of the above. > > So how come in programming, we ALWAYS jump into the constructs of a > language, rather than just doing, gaining proficiency and then > understanding how it is put together? > > I think that unless the approach to teaching Programming languages, is > changed and follows the more universal style of teaching spoke language > or verbal communication, Computer Programming for Everybody will remain > a dream. > > Just my .02 cents Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From jason at jorendorff.com Fri Mar 15 13:15:06 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 15 Mar 2002 12:15:06 -0600 Subject: Windows NT shell + extended characters. Bug or what? In-Reply-To: <10095d00.0203150319.12f9cbf9@posting.google.com> Message-ID: Noel Smith wrote: > >>> print ord('?') > 156 > >>> print ord('?') > 157 > > Which is clearly wrong although strangely enough when I type the same > thing into IDLE on Windows NT, it produces the correct results. Of course, you can use a Latin-1 chart http://czyborra.com/charsets/iso8859.html#ISO-8859-1 but that doesn't really answer your question. When you type the pound sign on your keyboard, the console interprets it as some byte. If the console were Latin-1 friendly, it would generate the byte A3, which is the Latin-1 code for the pound sign. Alas, the PC console uses a different character set called CP437, which is not Latin-1 compatible. In CP437, the pound sign is 156 and the yen sign is 157. So when you type a pound sign, your computer is putting the byte 9C (=156) into memory somewhere, and that is what Python receives when you hit Enter. Anyway, to cut a long story short: (1) Whenever you're using non-ascii characters, you want to use Unicode strings. A bare string like '?' may cause a warning in a future version of Python, in part because of this mess. (2) Alas, Python doesn't currently interpret Unicode literal strings all that intelligently, in the Windows console world anyway: [in Win2K console] >>> ord(u'?') 156 # uhhh, no >>> ord(u'\N{POUND SIGN}') 163 # correct answer I think it's fair to say this is a deficiency in current versions of Python. I believe it will be fixed, so eventually ord(u'?') will consistently return 163. But for now, a Latin-1 chart is your best bet. (Note that the above are technically Unicode codepoints, not Latin-1 character codes. But Latin-1 is the first page of Unicode, so it works.) (3) Tk is Unicode-friendly, so when you type or paste a ? character into it, the correct Unicode character is stored. Hope this helps allay the confusion, at least. :-/ ## Jason Orendorff http://www.jorendorff.com/ From martin at v.loewis.de Sun Mar 3 15:55:16 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 03 Mar 2002 21:55:16 +0100 Subject: Problems with print str, References: Message-ID: Stefan Heimann writes: > Any help would be great! I suggest to use raw_input for this specific application. Regards, Martin From mcherm at destiny.com Fri Mar 22 13:22:11 2002 From: mcherm at destiny.com (Michael Chermside) Date: Fri, 22 Mar 2002 13:22:11 -0500 Subject: Popular style document? Message-ID: <3C9B7653.2080204@destiny.com> > If you mean requirement to say def meth(something, arg) instead of def >> meth(arg), compiler does not necesarily know when compiling whether >> function will be used as method or not. (Methods can be defined >> outside of class statement and assigned as method later.) > > Yes, this is what I meant. How does this work though, when assigning a > method to a class? I mean, let's say that you have a method taking two > arguments, concatenate (x, y). When assigning this method to a class, > will that mean that the first argument is always replaced by the class > instance, so I'd have to call it like this: aclass.concatenate (y), and > the first argument, x, will always correspond to aclass? Yes. Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> class MyClass: # CREATE A CLASS pass >>> def concatenate(x, y): # CREATE A FUNCTION print 'concatenating %s and %s' % (x,y) return [x, y] >>> MyClass.concatenate = concatenate # MAKE THE FUNC A METHOD! >>> myInstance = MyClass() # NEED AN INSTANCE >>> myInstance.concatenate(7) # CALL METHOD ON THE INSTANCE concatenating <__main__.MyClass instance at 0x009557A8> and 7 [<__main__.MyClass instance at 0x009557A8>, 7] From tdi01fhu at syd.kth.se Tue Mar 26 14:13:51 2002 From: tdi01fhu at syd.kth.se (FREDRIK HULDTGREN) Date: Tue, 26 Mar 2002 20:13:51 +0100 Subject: stop Message-ID: Ok, so I'm going to be quite honest, I dont write perfect code, so today while working in PythonWin I imported a file. Problem was that the file happened to contain an infinte loop, which the interpreter gladly ran, untill I killed the entrire program. Annoying. Is there no %&/!#ing stop button in PythonWin? /Fredrik From vku at lfpt.rwth-aachen.de Mon Mar 18 05:32:43 2002 From: vku at lfpt.rwth-aachen.de (Viatcheslav Kulikov RWTH Aachen) Date: Mon, 18 Mar 2002 11:32:43 +0100 Subject: Python + Omni CORBA libraries link References: <3C95AF61.5D25C8CD@lfpt.rwth-aachen.de> Message-ID: <3C95C24A.D2B5D92F@lfpt.rwth-aachen.de> Duncan Grisby wrote: > In article <3C95AF61.5D25C8CD at lfpt.rwth-aachen.de>, > Viatcheslav Kulikov RWTH Aachen wrote: > > >ImportError: DLL load failed: Das angegebene Modul wurde nicht gefunden. > > Can you translate that error please? "The requested module was not found" (sorry, an OS is German) > > >I am using Python 2.1. and OmniORB compiler 1.0. The _omnipy module is > >available there with a .pyd extension (a compiled library). This message > >is received when the library is present at the PythonPath; when it is > >not, the interpreter simply finds no module name _omnipy. > >Please advise what can be done. I am new to the Python programming, so > >please give as much detail as possible. > > You should be using omniORBpy version 1.4. Are you using the version > compiled for Python 2.1? If not, that would explain the problem. > Thank you, seems you have covered the problem. Well, as I am quite new to the Python, I can't give the exact version of the package, but the compiler shows version 1.0. Also, all files of the package are dated 21-06-2001 as the latest. The module CORBA.py from the package shows the following ID: # $Id: CORBA.py,v 1.27.2.3 2001/05/17 14:05:01 dpg1 Exp $ Hopefully I provided sufficient information, if not, please give me a hint how to get more. Is this version compiled only for Python 2.0? If so, please give a link to the place where I can download the version 1.4 or higher which would eliminate the error. I would be very grateful. Best regards, Viatcheslav Kulikov From jkraska at san.rr.com Sun Mar 10 23:03:06 2002 From: jkraska at san.rr.com (Courageous) Date: Mon, 11 Mar 2002 04:03:06 GMT Subject: How "expensive" are Exceptions? References: <3C8C2A95.C3C754AC@engcorp.com> Message-ID: <3jbo8u0jjbgel0h1vqgpbcnlfe96vmvu9j@4ax.com> >> exceptions, too. This is the major cost of exception-handling >> in Python: checking every return value. (Good C++ compilers >> cleverly avoid this cost; Python doesn't, alas.) But it's really irrelevant in any case. The cost doesn't contribute in any significant measurable way to the execution time of a Python program, I'd say. C// From alf at logilab.fr Wed Mar 27 07:42:14 2002 From: alf at logilab.fr (Alexandre Fayolle) Date: Wed, 27 Mar 2002 12:42:14 +0000 (UTC) Subject: overwrite bytes in file References: <3ca1c344.16256546@news.easynews.net> Message-ID: In article <3ca1c344.16256546 at news.easynews.net>, Marcus Stojek wrote: > Hi, > how can I overwrite certain bytes in a file (Win NT) and > keep the rest unchanged. > All open options are truncating the file. Opening the file in 'r+' mode should do the trick. Alexandre Fayolle -- LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Narval, the first software agent available as free software (GPL). From phlip_cpp at yahoo.com Wed Mar 27 20:03:49 2002 From: phlip_cpp at yahoo.com (Phlip) Date: 28 Mar 2002 01:03:49 GMT Subject: Why does this work? References: Message-ID: Delaney, Timothy wrote: >> And we like to find ways to cure the "magic member bug". If >> you can think of >> any others, please share. > > __slots__ Thanks! And 'import from __future__ nested_scopes' would provide similar checks. -- Phlip http://www.greencheese.org/HatTrick From WDraxinger at darkstargames.de Sun Mar 3 17:35:35 2002 From: WDraxinger at darkstargames.de (WDraxinger at darkstargames.de) Date: Sun, 3 Mar 2002 23:35:35 +0100 Subject: Python Embedding, stdin/-out redirection Message-ID: Hi there, I'm just trying to embedd python in my 3D Engine which works fine, except the problems with my console: I'd like to do the PyRun_InteractiveLoop(stdin, ""); for my Engines console, because the python interactive mode is just perfect. To make it as simple as possible I redirected stdin/-out to 2 pipes which I read out and print to my 3D window's console. Within my programm all I/O stream releated stuff just works fine. Mysteriously that doesn't work with python. Below you see an example of what I tried: #include #include #include enum {PIPE_READ, PIPE_WRITE}; int stdin_pipe[2]; int stdout_pipe[2]; int stderr_pipe[2]; void python_thread() { // Sync with console Py_Initialize(); PyRun_InteractiveLoop(stdin, ""); Py_Finalize(); } void console_thread() { // Sync with python // Show me the stuff written to stdout while(!eof(stdout_pipe[PIPE_READ])) { int r=read(stdout_pipe[PIPE_READ], buffer, 80); buffer[r]=0; cprintf(buffer); } // The same with stderr while(!eof(stderr_pipe[PIPE_READ])) { int r=read(stderr_pipe[PIPE_READ], buffer, 80); buffer[r]=0; cprintf(buffer); } } int main(int argc, char **argv) { char buffer[80]; _pipe(stdin_pipe, 512, 0); _pipe(stdout_pipe, 512, 0); _pipe(stderr_pipe, 512, 0); _dup2(stdin_pipe[PIPE_READ], 0); _dup2(stdout_pipe[PIPE_WRITE], 1); _dup2(stderr_pipe[PIPE_WRITE], 2); start_console_thread(); start_python_thread(); return 0; } The output of my programm code is written in the pipe, but python output still goes to the system console. I also tried PyRun_SimpleString("os.dup2(, sys.stdout.fileno())\n"); but it doesn't work and python complies about an invalid file descriptor. I thought it would share the files since it runs in the same process, doesn't they? Has anybody an idea how to solve this problem. -- +------------------------------------------------+ | +----------------+ WOLFGA NG DRAXINGER | | | ,-. DARKSTAR | lead programmer | | |( ) +---------+ wdraxinger at darkstargames.de | | | `-' / GAMES / | | +----+'''''''' http://www.darkstargames.de | +------------------------------------------------+ From etrofsouls at aol.com Sat Mar 2 00:35:14 2002 From: etrofsouls at aol.com (EtrOFsouls) Date: 02 Mar 2002 05:35:14 GMT Subject: newbie password question Message-ID: <20020302003514.13693.00001116@mb-fw.aol.com> Im a newbie to programming, and am having trouble with a certain task. I'd like to know how to keep track of how often a person guesses at a password and limits it to x many guesses. Here's a sample of what I've got so far. password = "foobar" while password != "unicorn": password = raw_input ("Password:") print "Welcome In" I understand all this (thank god), but I'm having trouble figuring out how to get it to keep track of the number of guesses and then print a message such as "Halt, you do not have access!" if the number of guesses exceeds the limit. I'm learning this thru on-line tutorials and this was given as an excersise. All I have to work with is variables and statements such as...while, if, elif and else. Any help would be greatly appreciated From rnd at onego.ru Fri Mar 8 08:48:28 2002 From: rnd at onego.ru (Roman Suzi) Date: Fri, 8 Mar 2002 16:48:28 +0300 (MSK) Subject: PEP Parade In-Reply-To: <15496.46742.14715.837893@12-248-41-177.client.attbi.com> Message-ID: On Fri, 8 Mar 2002, Skip Montanaro wrote: > > Roman> Just one comment about > > Roman> PEP 270 - uniq method for list objects > > Roman> maybe adding dict <-> list conversion functions will make this > Roman> automatically? > >Nothing new is necessary since 2.2 was released: > > >>> mylist = [1,2,3,5,6,6,9,9,1,2,3,4] > >>> mydict = dict(zip(mylist,mylist)) > >>> mydict > {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 9: 9} > >>> mydict.values() > [1, 2, 3, 4, 5, 6, 9] Wow. Then I am a bit underinformed. What uniq is for then? To cover lengthy: def uniq(x): return dict(map(None, x, [None])).keys() ? :-) OK, uniq is convenient, I agree. But then other set operations should follow. d.update(d1) # d = d + d1 ??? # d = d * d1 ??? # d = d - d1 (i know it's easy to make class for them, but so is for uniq) Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Friday, March 08, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "People are always available for work in the past tense." _/ From cliechti at gmx.net Thu Mar 21 15:09:16 2002 From: cliechti at gmx.net (Chris Liechti) Date: 21 Mar 2002 21:09:16 +0100 Subject: Telnet References: Message-ID: "Billy Ng" wrote in news:yAqm8.1723$Tk.98335 @newsread1.prod.itd.earthlink.net: > I am trying to write a telnet client program. Here is the code: > > ID = "123445" > PASSWORD = "333" > > try: > tn = telnetlib.Telnet() > tn.read_until("Please enter your id? ") > tn.write(ID+"\n") > tn.read_until("Enter your password? ") > tn.write(PASSWORD+"\n") > print tn.read_all() > tn.close() > except: > tn.close() > print 'connection failed' > tn.close() > > It stops after the ID was written. If I use the actual telnet > client, it returns "Enter your password? " after my ID is > submitted. why does not tn.read_until() find the "Enter your > password? " string ? Is there any other way to handle the password > prompt? don't write the entire prompt in read_all. insteand use read_all("word?") this way you circumwent problems with additional spaces, case atc. and make sure that your server works with just a "\n", maybe it needs a "\r\n". HTH chris -- Chris From peter at engcorp.com Wed Mar 20 02:14:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Mar 2002 02:14:00 -0500 Subject: Java and Python References: <3C96DBB4.6040109@pobox.com> <3C97FB8A.5B9E9247@engcorp.com> <3C98108D.5010002@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> Message-ID: <3C9836B8.150B4DA@engcorp.com> Ahmed Moustafa wrote: > > Peter Hansen wrote: > > 1. As others have said, there is no such thing as an unbiased > > comparison of almost anything, let alone programming languages, > > let alone two with such, uh, "dedicated" users as Java and Python. > > Nevertheless, even if we could find such a thing, the response > > would really depend entirely on the application area. > > How about web development? Also, how is Python doing in the embedded > applications? Python is excellent for web development. I can't say exactly how it compares with Java, but this is a very active area for Python (see Zope, for example). You may also have heard of Jython, which compiles Python source to Java .class files which can then run on any Java VM. Since Python source is often more readable and compact than languages derived from C, the result can be "the best of both worlds." If by "embedded" you mean truly embedded systems, with microcontrollers in dedicated-purpose systems and generally limited user interfaces, Python is somewhat less suitable than Java, since there are the KVM and similar Java variants focussed specifically in this area. Python is in use in some PC104-based embedded systems (that's what we use it for in the embedded area) and has also been ported (in early forms) to the Palm Pilot, for example. The language itself is perhaps slightly less effective for embedded systems in some respects, because it is higher level than Java. If your constraint is performance and code size, Java might be better (but then, C might be much much better...) whereas if development time and cost is the constraint, Python may well be the winner. (This is why we use it.. much faster development, easier testing, etc.) On the other hand, two years ago I made the choice between Java and Python for the embedded arena, and Java was no hell at the time, so I chose Python. I'm still quite satisfied with the decision. > > The point is, I would never hire you or anyone _because_ > > you knew Python, or Java. I would hire you because > > I thought you were capable of learning it and using it > > effectively. I actually tend to shy away from people > > with great lists of "certifications" in languages because > > it suggests to me they have difficulty learning and > > think it's a very impressive thing that they managed > > to learn enough to write an exam which tests knowledge > > of syntax but little about programming skill. > > I agree a certificate does not mean a great programmer, and I think the > employers know that, but it still tells that one is serious about the > profession. I have been programming with Java for +4 years now. I got > certified 2 months ago. I feel my resume is stronger now. That may be, depending on the one doing the hiring. I consider *any* competent programmer fully capable of learning a language such as Java or Python within at the absolute most a few months and, if necessary, taking these certifications. The fact one has taken it holds no special merit in my mind, since it is a "least common denominator" type of thing. I can judge a developer's competence much better during an interview with discussion than I can by seeing a certification on her resume. It is _not_ the knowledge of language syntax and idioms that matters, but many less technical traits, where I'm concerned. As for showing your seriousness, I suppose it might do that. For me, the breadth and depth of your experience on projects does that. After four years, I would expect to see several major projects and experience in a variety of areas such as networking, database, GUI, and multithreaded work. The certification pales in comparison to those items on any resume I've seen. But that's certain a matter of opinion. Some people think a P.Eng. (professional engineering, or PE in the States) designation means a lot. Others remember some of the people they went to school with and realize some P.Eng's are quite competent, while others may be less so. It's no guarantee. -Peter Hansen, P.Eng. :-) From jgardn at alumni.washington.edu Wed Mar 6 09:09:51 2002 From: jgardn at alumni.washington.edu (Jonathan Gardner) Date: Wed, 06 Mar 2002 23:09:51 +0900 Subject: Getting stdout and stderr from popen References: Message-ID: Stefan Heimann scribbled with his keyboard: > I want to launch an external process and have stdout and stderr > redirected to one output stream, You are on Unix, right? > something like > > f = os.popen('cvs status 2>&1') > > does the right thing, but does not work on all platforms. > > If I write > > pin, pout, perr = os.popen3('cvs status') > > I get the output of stderr and stdout but not in the right order. What do you mean in the right order? Do you mean that it is returning in, err, out or that err and out are spitting out stuff simultaneously? > > I tried also > > sys.stderr = sys.stdout > f = os.popen('cvs status') > f.read() > > but still I get only the output from stdout (what cvs outputs on > stderr is written directly to the console). > Okay, let's talk about what is really happening deep underneath the hood. These popen functions are a shorthand for a very common thing in the world of Unix. It goes something like this: 1) make three pipes (in, out, err) 2) fork. 3) If you are the child (pid == 0) then close the writing part of in, and the reading part of out and err. 4) Now, make in be my stdin, out my stdout, err my stderr. (this has to be done at a lower level - you need to use the dup type functions.) 5) Now, execute the program I wanted to execute ("cvs status") and exit when it is finished. "cvs status" should be reading from and writing to the pipes. 3) If you are the parent (pid != 0, pid is the child's pid) then close the reading part of in, the writing part of out and err. If you want to send something to the child's stdin, write to in. If you want to see what he is saying, read from out. If you want to hear what he is crying about, read from err. (Yes, I meant to write (3).) 4) go on with your parental role and discipline your child if he misbehaves. That is what is happening under the hood. There are four things the parent gets when he makes a child like this - in, out, err, and the pid. os.popen plays a funny trick. He only gives us back one file that we can either read from or write to. You have to choose one. If you choose the write to file, then you are going to be writing to the child's stdin. If you choose the read from one, then you will be reading from his stdout. You can't read from stderr from this one. It will use stderr from the parent. (Note: this may be different from sys.stderr.) os.popen2, 3, and 4 do something similar, but they will give you back multiple pipes. Read the documentation closely. My favorite, for when I am a control freak, is the Popen2, 3, or 4 class in popen2 module. Take a look at that for how that works. More questions about pipes and child processes? Take it to a Unix programmer. Windows does a horrible job with it, and Windows programmers tend to only know about it, but are not able to do much with it. Jonathan From paul at boddie.net Wed Mar 13 11:29:02 2002 From: paul at boddie.net (Paul Boddie) Date: 13 Mar 2002 08:29:02 -0800 Subject: Converting relative URLs to absolute References: <23891c90.0203130331.6f030f5b@posting.google.com> <3C8F3B94.1020409@mxm.dk> Message-ID: <23891c90.0203130829.119872b2@posting.google.com> Dave Cole wrote in message news:... > >>>>> "Max" == Max M writes: > > Max> So perhaps you could get it added to the urllib instead? > > That would be the best result - we could all use it then. What embarrassment! I have some code which only covers some of the cases, and then only in a form relevant to the application in question. However, it's possible to sketch out what might be needed, so I've uploaded a module which implements a "first draft" of a split function. The join function is an exercise for the interested reader... http://www.boddie.org.uk/downloads/urlutils.py Paul From ak at silmarill.org Fri Mar 29 10:53:38 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Fri, 29 Mar 2002 15:53:38 GMT Subject: Anyone need a program written? References: <3ca43ef4.3666136@news.tudelft.nl> <7o_o8.17314$Ou.7311@atlpnn01.usenetserver.com> Message-ID: In article <7o_o8.17314$Ou.7311 at atlpnn01.usenetserver.com>, Steve Holden wrote: > "Fused" wrote in > message news:3ca43ef4.3666136 at news.tudelft.nl... >> I'm currently trying to master Python, but to succeed I need to >> exercise. However, I detest building programs that have already been >> built a kazillion times and aren't of use to anyone. >> Can anyone think of a program that I could build that would actually >> have use to someone (you?)? I'm trained in Delphi, know some Java and >> rudimentary C, so the programs don't need to be newbie-easy ( I like a >> challenge: the greater the challenge, the faster I'll learn ;-) ). > > I'd really like to see a Python mail/newsreader. That would teach you a lot, > and keep you busy for a while... > I'd like to second that. I use slrn and mutt and they're pretty good but I'd hack on a few things, polish rough edges, etc if they were written in python. A program that tries to do both probably won't be very good at either, if I were you I'd either make a news or - an email reader. - Andrei > > regards > Steve > > > > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From jkraska at san.rr.com Sun Mar 10 13:25:42 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 10 Mar 2002 18:25:42 GMT Subject: should i learn it first ? References: <3C8AD9B6.5CEE7588@engcorp.com> Message-ID: >But are there any tasks for which C++ (or C++/Python) is really better >than C/Python? While it's not impossible, it's quite laborious (!) o write object oriented code with C. While I am a big skeptic of buzzword compliance for its own sake (OOP, bleach!), the path of least resistance in C is to not write code which is as neatly encapsulated as one generally gets when one writes simple C++ code. This matters. Even if one doesn't use all of C++'s fancy features, inheritance, virtual functions, and good basic data encapsulation are real life savers that make it hard to want to regress to pure C code. I have written object oriented code in C, using the Xt/Intrinsics approach. It's a pain. It also greatly increase the syntax to functionality ratio quite significantly. That's a very bad thing. C// From peter at engcorp.com Sun Mar 24 12:02:24 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 24 Mar 2002 12:02:24 -0500 Subject: Memory sizes of python objects? References: Message-ID: <3C9E06A0.EC4D51E3@engcorp.com> Erno Kuusela wrote: > > In article , "Clark C > . Evans" writes: > > | Is there some rule of thumb that I can use to estimate, > | for example, take the character data you have and multiply by > | a factor of 4 to find the in-memory footprint of tuples, and > | each map is 1K plus 64 bytes per entry.. > > make a zillion of them, check memory usage increase with ps (or > equivalent on your platform), and divide by zillion. Keeping in mind Python's propensity for finding already-existing entities and binding to them instead of creating new objects. The difference in memory consumption between creating a list of size 1,000,000 filled with 0's and the same size list filled with integers from 0 to 999,999 is rather large... -Peter From James_Althoff at i2.com Mon Mar 4 18:58:47 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 15:58:47 -0800 Subject: Status of PEP's? Message-ID: [James_Althoff] > > if I want to iterate up (smaller up to larger) I need to > write the for-loop as > for smaller <= i <= larger: # can *only* iterate up > but if I want to iterate down (larger down to smaller) I need to write the > for-loop with the reverse relational operators > for larger >= i >= smaller: # can *only* iterate down [Greg Ewing] > Sorry, I missed that you wanted the order of iteration > to be variable. You're right, but I don't see that as > a major disadvantage. The vast majority of all for-loops > over integers that I write have a fixed iteration order. > In the rare cases that I wanted otherwise, I'd be > quite happy to write the loop another way. I guess it depends on the type of loops in the given application. I hit it right away when I was playing around with my experimental implementation of the "for i in 0 <= ints <= x:" variant. I just thought this should be noted as a limitation of any approach that uses relational operators. Jim From Greg.Lindstrom at acxiom.com Fri Mar 15 14:08:58 2002 From: Greg.Lindstrom at acxiom.com (Lindstrom Greg - glinds) Date: Fri, 15 Mar 2002 13:08:58 -0600 Subject: Pretty Integers Message-ID: I would like to add commas to the integers I am writing (for example: 12345678 --> 12,345,678). I have a fairly ugly method that relies heavily upon mods, but am convinced there must be a "pretty" way to do it. How would you go about this task? Thanks, everyone! Greg Lindstrom Acxiom Corporation, mail: CWY10011149 InfoBase Products Development office: (501) 342-1626 301 Industrial Blvd, Conway, AR, 72032 fax: (501) 336-3911 email: Greg.Lindstrom at acxiom.com "The great thing about standards is there are so many to choose from" Michael Hudson ********************************************************************* The information contained in this communication is confidential, is intended only for the use of the recipient named above, and may be legally privileged. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution, or copying of this communication is strictly prohibited. If you have received this communication in error, please re-send this communication to the sender and delete the original message or any copy of it from your computer system. Thank You. From ggerrietts at yahoo.com Mon Mar 4 17:11:57 2002 From: ggerrietts at yahoo.com (Geoff Gerrietts) Date: Mon, 4 Mar 2002 14:11:57 -0800 Subject: Stedents Question In-Reply-To: <3C83EA76.BEA9C041@ccvcorp.com> References: <3c80126f_1@news.iprimus.com.au> <3C83EA76.BEA9C041@ccvcorp.com> Message-ID: <20020304221157.GF1792@isis.gerrietts.net> Quoting Michael Janssen (Janssen at rz.uni-frankfurt.de): > Tony K wrote: > > > > Write a Python function findABBC which takes a single string as > > parameter and returns all substrings thereof which match the > > regexp pattern ab+c. You are NOT allowed to use the re module. I love these little challenges :) This one's not much shorter than Michael's but I think it'll run faster. import string def abbc(instr): subs = [] str = instr while str: start = string.find(str,"ab") if start == -1: break for i in range(start+2,len(str)): if str[i] == "b": continue if str[i] == "c": end = i+1 break start = end = i break sub = str[start:end] if sub: subs.append(sub) str = str[end:] print subs If your python supports string methods, cut that back to: def abbc(instr): subs = [] str = instr while str: start = str.find("ab") if start == -1: break for i in range(start+2,len(str)): if str[i] == "b": continue if str[i] == "c": end = i+1 break start = end = i break sub = str[start:end] if sub: subs.append(sub) str = str[end:] print subs And now as I prepare to send this to the list (after mistakenly sending it to the poster I replied to last time, oops), I'm betting it would be even quicker to use find twice: def abbc(instr): subs = [] str = instr while str: start = str.find("ab") finish = str.find("c",start) if (start == -1) or (finish == -1): break if (str[start:finish] == "a" + ("b"*(finish-start-1))): finish = finish + 1 subs.append(str[start:finish]) else: finish = start + 1 str = str[finish:] print subs Maybe I'll try testing this hypothesis later.... --G. -- Geoff Gerrietts -rw-rw-rw-: permissions of the beast From sandskyfly at hotmail.com Fri Mar 15 17:27:48 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 15 Mar 2002 14:27:48 -0800 Subject: psyco, jython, and python speed tests References: Message-ID: I'm reposting this because the first one didn't go through for some reason... Skip Montanaro: > How did you "psycoize pystone"? I found the best results when > psyco.bind()ing Proc0, Proc1 and Proc8. I think it's important when > documenting psyco speedups to indicate what steps you took since there are > so many possibilities. Basically, I took the pystone included in Armin's psyco cvs distribution and simplified the main() function to get rid of the comparitive stuff. I think the key binding in this case is in pystones_psycho(): f = psyco.proxy(Proc0) # with Proc0 calling other Procs... regards, Sandy ----------------------snip------------------------------------------ #! /usr/bin/env python """ "PYSTONE" Benchmark Program Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes) Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013. Translated from ADA to C by Rick Richardson. Every method to preserve ADA-likeness has been used, at the expense of C-ness. Translated from C to Python by Guido van Rossum. Version History: Version 1.1 corrects two bugs in version 1.0: First, it leaked memory: in Proc1(), NextRecord ends up having a pointer to itself. I have corrected this by zapping NextRecord.PtrComp at the end of Proc1(). Second, Proc3() used the operator != to compare a record to None. This is rather inefficient and not true to the intention of the original benchmark (where a pointer comparison to None is intended; the != operator attempts to find a method __cmp__ to do value comparison of the record). Version 1.1 runs 5-10 percent faster than version 1.0, so benchmark figures of different versions can't be compared directly. """ LOOPS = 1000000 # number of loops for Psyco run from time import clock __version__ = "1.1" [Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6) class Record: def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0, IntComp = 0, StringComp = 0): self.PtrComp = PtrComp self.Discr = Discr self.EnumComp = EnumComp self.IntComp = IntComp self.StringComp = StringComp def copy(self): return Record(self.PtrComp, self.Discr, self.EnumComp, self.IntComp, self.StringComp) TRUE = 1 FALSE = 0 def mydiv(a,b): try: return float(a) / b except: return float("nan") def main(): print "Pystone(%s) time loops per second" % __version__ psy_time = pystones_psycho(LOOPS)[0] print "Psyco for %d passes %g %g" % (LOOPS, psy_time, mydiv(LOOPS, psy_time)) def pystones_psycho(*loopslist): import psyco old_dict = Record.__dict__.copy() try: # replace all methods of Record by proxies #for key, value in old_dict.items(): # if type(value) is type(main): # Record.__dict__[key] = _psyco.proxy(value, 99) f = psyco.proxy(Proc0) return map(f, loopslist) finally: Record.__dict__.update(old_dict) def pystones_reg(*loopslist): return map(Proc0, loopslist) IntGlob = 0 BoolGlob = FALSE Char1Glob = '\0' Char2Glob = '\0' Array1Glob = [0]*51 Array2Glob = map(lambda x: x[:], [Array1Glob]*51) PtrGlb = None PtrGlbNext = None def Proc0(loops=LOOPS): global IntGlob global BoolGlob global Char1Glob global Char2Glob global Array1Glob global Array2Glob global PtrGlb global PtrGlbNext PtrGlbNext = Record() PtrGlb = Record() PtrGlb.PtrComp = PtrGlbNext PtrGlb.Discr = Ident1 PtrGlb.EnumComp = Ident3 PtrGlb.IntComp = 40 PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING" String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING" Array2Glob[8][7] = 10 starttime = clock() for i in range(loops): Proc5() Proc4() IntLoc1 = 2 IntLoc2 = 3 String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING" EnumLoc = Ident2 BoolGlob = not Func2(String1Loc, String2Loc) while IntLoc1 < IntLoc2: IntLoc3 = 5 * IntLoc1 - IntLoc2 IntLoc3 = Proc7(IntLoc1, IntLoc2) IntLoc1 = IntLoc1 + 1 Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3) PtrGlb = Proc1(PtrGlb) CharIndex = 'A' while CharIndex <= Char2Glob: if EnumLoc == Func1(CharIndex, 'C'): EnumLoc = Proc6(Ident1) CharIndex = chr(ord(CharIndex)+1) IntLoc3 = IntLoc2 * IntLoc1 IntLoc2 = IntLoc3 / IntLoc1 IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1 IntLoc1 = Proc2(IntLoc1) benchtime = clock() - starttime return benchtime def Proc1(PtrParIn): PtrParIn.PtrComp = NextRecord = PtrGlb.copy() PtrParIn.IntComp = 5 NextRecord.IntComp = PtrParIn.IntComp NextRecord.PtrComp = PtrParIn.PtrComp NextRecord.PtrComp = Proc3(NextRecord.PtrComp) if NextRecord.Discr == Ident1: NextRecord.IntComp = 6 NextRecord.EnumComp = Proc6(PtrParIn.EnumComp) NextRecord.PtrComp = PtrGlb.PtrComp NextRecord.IntComp = Proc7(NextRecord.IntComp, 10) else: PtrParIn = NextRecord.copy() NextRecord.PtrComp = None return PtrParIn def Proc2(IntParIO): IntLoc = IntParIO + 10 while 1: if Char1Glob == 'A': IntLoc = IntLoc - 1 IntParIO = IntLoc - IntGlob EnumLoc = Ident1 if EnumLoc == Ident1: break return IntParIO def Proc3(PtrParOut): global IntGlob if PtrGlb is not None: PtrParOut = PtrGlb.PtrComp else: IntGlob = 100 PtrGlb.IntComp = Proc7(10, IntGlob) return PtrParOut def Proc4(): global Char2Glob BoolLoc = Char1Glob == 'A' BoolLoc = BoolLoc or BoolGlob Char2Glob = 'B' def Proc5(): global Char1Glob global BoolGlob Char1Glob = 'A' BoolGlob = FALSE def Proc6(EnumParIn): EnumParOut = EnumParIn if not Func3(EnumParIn): EnumParOut = Ident4 if EnumParIn == Ident1: EnumParOut = Ident1 elif EnumParIn == Ident2: if IntGlob > 100: EnumParOut = Ident1 else: EnumParOut = Ident4 elif EnumParIn == Ident3: EnumParOut = Ident2 elif EnumParIn == Ident4: pass elif EnumParIn == Ident5: EnumParOut = Ident3 return EnumParOut def Proc7(IntParI1, IntParI2): IntLoc = IntParI1 + 2 IntParOut = IntParI2 + IntLoc return IntParOut def Proc8(Array1Par, Array2Par, IntParI1, IntParI2): global IntGlob IntLoc = IntParI1 + 5 Array1Par[IntLoc] = IntParI2 Array1Par[IntLoc+1] = Array1Par[IntLoc] Array1Par[IntLoc+30] = IntLoc for IntIndex in range(IntLoc, IntLoc+2): Array2Par[IntLoc][IntIndex] = IntLoc Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1 Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc] IntGlob = 5 def Func1(CharPar1, CharPar2): CharLoc1 = CharPar1 CharLoc2 = CharLoc1 if CharLoc2 != CharPar2: return Ident1 else: return Ident2 def Func2(StrParI1, StrParI2): IntLoc = 1 while IntLoc <= 1: if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1: CharLoc = 'A' IntLoc = IntLoc + 1 if CharLoc >= 'W' and CharLoc <= 'Z': IntLoc = 7 if CharLoc == 'X': return TRUE else: if StrParI1 > StrParI2: IntLoc = IntLoc + 7 return TRUE else: return FALSE def Func3(EnumParIn): EnumLoc = EnumParIn if EnumLoc == Ident3: return TRUE return FALSE if __name__ == '__main__': main() From aahz at panix.com Sun Mar 10 21:30:49 2002 From: aahz at panix.com (Aahz Maruch) Date: 10 Mar 2002 18:30:49 -0800 Subject: should i learn it first ? References: Message-ID: In article , Patrick wrote: >"Aahz Maruch" wrote in message >news:a6g7ra$lm6$1 at panix2.panix.com... >> >> But are there any tasks for which C++ (or C++/Python) is really better >> than C/Python? > >One example is an extremely complex and long-running simulation in which the >time-critical components are a very substantial chunk of the project. In >those (rare) situations you need ruthless efficiency with slightly better >than rudimentary abstraction capabilities. C++ fits the bill, but only if >every processor cycle and every byte counts. Right, and if you've got a project like that, you'd better have someone like Alex Martelli handy, because otherwise your C++ program will bloat with every advanced C++ feature you use. I'd bet that 90% of so-called C++ programmers would do far better in this case with C/Python. I once had to deal with a C++ DLL written by a programmer who I had a decent amount of respect for. I did not (and do not) know C++, and don't particularly consider myself a C programmer -- but in a week I'd used C to rewrite his DLL mostly from scratch. I removed the Windows-isms (because I was developing on Solaris), and my code was shorter, faster, and bugless. The part I was most aghast about was that he did the moral equivalent of this: buffer = '' for tmp_buf in input: buffer = buffer + tmp_buf -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "Argue for your limitations, and sure enough they're yours." --Richard Bach From martin at v.loewis.de Fri Mar 1 19:08:18 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Mar 2002 01:08:18 +0100 Subject: Windows Memory Mapped Files References: Message-ID: Spencer Ernest Doidge writes: > Is there a way, running a Python script in a console window, to read/write > Memory Mapped files? Using the mmap module, this should be possible. Regards, Martin From huaiyu at gauss.almadan.ibm.com Tue Mar 5 14:09:26 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 5 Mar 2002 19:09:26 +0000 (UTC) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: <7xbse3j3u4.fsf@ruckus.brouhaha.com> Message-ID: On 04 Mar 2002 15:44:19 -0800, Paul Rubin wrote: >huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) writes: >> So my question now is: What do I do to tell Python to compile with -lieee? > >I just edited the makefile and found the LIBS line and added -lieee. >I didn't uncomment that #define that you found. OK, this solves the immediate problem. But there are quite a few puzzles: 1. The -lieee is indeed the most direct cure. On prestine source, do configure; make; mv python python.bak; make -n python. This shows the final linking command, which has no -lieee. Use that line plus -lieee to produce a new python binary. Testing both with 1e-200**2. One raises OverflowError while the other does not. 2. Is there a configure option to guarantee -lieee? Changing pyconfig.h.in to #define HAVE_LIBIEEE 1 does not make -lieee appear in the Makefile, even though it get into pyconfig.h. 3. errno 34 (or -lieee) may not be the sole reason. On a RedHat 6.1 upgraded to 7.1 (both gcc and glibc), errno 34 is indeed raised in a C program linked without -lieee, and Python is indeed compiled without -lieee, but Python does not raise OverflowError. It appears that the problem is neither gcc nor glibc, as Konrad Hinsen reported that on a stock RedHat 7.1 Python did raise. 4. Is there an easier way to debug such problems? Maybe a C test program should be included in the configure script or in the Tools directory so that people can easily report various conditions? Such environmental testing is essential if Python is defining its own numerical behavior indenpendent of IEEE or C. (but see below) I once asked a question about a wierd behavior of Octave and the author sent me a C program and asked for results. He modified the program and asked me to test it again. The problem was solved in just two rounds of exchange. 5. How is 1e200**2 handled? Since both 1e-200**2 and 1e200**2 produce the same errno all the time, but Python still raises OverflowError for 1e200**2 when linked with -lieee, there must be a separate mechanism at work. What is that and how can I override it? I know this is by design, but I think the design is dumb (to put it politely). I won't get into an argument here. I'll write up my rationale against this when I have some time. I do remember there being several discussions in the past, but I don't remember any convincing argument for the current decision. Any URL would be greatly appreciated, beside the one pointed by Tim. Achieving uniformity across platform alone is not a convincing reason at all - you could let all computation return zero all the time to achieve the greatest uniformity. :-) I hope the above provides enough details and independence among the issues for experts to ponder about. Huaiyu From lluang at northwestern.edu Thu Mar 28 11:25:07 2002 From: lluang at northwestern.edu (Louis Luangkesorn) Date: Thu, 28 Mar 2002 10:25:07 -0600 Subject: calling a java application result into Python (JPE???) References: <3C9D66E9.4070802@northwestern.edu> Message-ID: <3CA343E3.C03ABF90@northwestern.edu> Thanks for the help. I ended up using os.chdir(path) instead of os.path and that worked. However, I was never able to get the java program to get its result into Python (I ended up solving my problem in a completely unrelated way). As a more academic question, (and since my solution may not cover all the bases so I may have to revisit this) how do you call a Java application and return the result into Python. I saw the Java-Python Extension, but I could not figure out how to get started. Thanks. Louis -- K Louis Luangkesorn lluang at northwestern.edu http://pubweb.nwu.edu/~kll560 PGP:0xF3E2D362 Whatsoever things are true, ... honest, ... just, ... pure, ... lovely, ... of good report; if there be any virtue, and if there be any praise, think on these things.- motto - Northwestern University From Kevin.Smith at theMorgue.org Tue Mar 5 15:05:10 2002 From: Kevin.Smith at theMorgue.org (Kevin Smith) Date: 5 Mar 2002 20:05:10 GMT Subject: Compiling Python 2.2 with GCC in HPUX 10.20 does not work References: <3C848CBF.9000201@vip.fi> <3C84F129.70905@vip.fi> Message-ID: <20020305150516592-0500@braeburn.na.sas.com> I got Python 2.2 to compile on HPUX 10.20 with gcc 2.95.3. I got a very similar error to what was in your message. I actually just added the following line to Modules/socketmodule.c at line 161 just above the '#ifndef RISCOS' block. int h_errno; Otherwise, it didn't look like h_errno was ever being declared. I can't help you with the curses problem. I still haven't gotten that to work. Kevin Smith In <3C84F129.70905 at vip.fi> pekka niiranen wrote: > >--------------020604040107000300090304 >Content-Type: text/plain; charset=us-ascii; format=flowed >Content-Transfer-Encoding: 7bit > >True, HP-UX's default compiler is only meant for compliling the kernel >therefore I installed binutils v2.11.2, gcc v3.01 and gmake v3.79.1 from >HP's software repository and tried compiling with this script: > >#! /usr/bin/sh >export CCOPTS='+z' >unset LANG >gmake distclean >CC=gcc ./configure --with-gcc --with-threads=no --without-cxx >--prefix=/opt/python > >gmake fails twice: > >1) >/osasto/home/niirape/python_softa/Python-2.2/Modules/getaddrinfo.c:544: >warning: `h_error' might be used uninitialized in this funcn >In file included from >/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c:239: >/osasto/home/niirape/python_softa/Python-2.2/Modules/getnameinfo.c: In >function `getnameinfo': >/osasto/home/niirape/python_softa/Python-2.2/Modules/getnameinfo.c:184: >`h_errno' undeclared (first use in this function) >/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c: In >function `gethost_common': >/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c:1975: >`h_errno' undeclared (first use in this function) >WARNING: building of extension "_socket" failed: command 'gcc' failed >with exit status 1 > >2) >gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I. >-I/osasto/home/niirape/python_softa/Python-2.2/./Include -I/usr/local/incluo >ld -b build/temp.hp-ux-B.10.20-9000/777-2.2/_cursesmodule.o >-L/usr/local/lib -lncurses -o build/lib.hp-ux-B.10.20-9000/777-2.2/_curl >ld: DP relative code in file /usr/local/lib/libncurses.a(lib_addch.o) - >shared library must be position > independent. Use +z or +Z to recompile. >WARNING: building of extension "_curses" failed: command 'ld' failed >with exit status 1 > >Anybody solved these problems > >-pekka- > >Martin von Loewis wrote: > >>pekka niiranen writes: >> >>>I tried the build script below in HP-UX 10.20 >>>( HP-UX B.10.20 A 9000/777 2002144332 two-user license) >>>and got the following errors during make: >>> >>>cc -Ae -c -DNDEBUG -O -I. -I./Include -DHAVE_CONFIG_H -o >>>Modules/python.o Modules/python.c >>>(Bundled) cc: warning 480: The -A option is available only with the >>>C/ANSI C product; ignored. >>>(Bundled) cc: warning 480: The -O option is available only with the >>>C/ANSI C product; ignored. >>> >> >>It seems that you are using the bundled compiler. Python source code >>is ANSI C, you need an ANSI C compiler to compile it. Try either the >>HP ANSI C compiler, or gcc (the former being recommended). >> >>Regards, >>Martin >> > > >--------------020604040107000300090304 >Content-Type: text/html; charset=us-ascii >Content-Transfer-Encoding: 7bit > > > > > >True, HP-UX's default compiler is only meant for compliling the kernel
    >therefore  I installed  binutils v2.11.2,  gcc v3.01 and >gmake v3.79.1 from
    >HP's software repository and tried compiling with this script:
    >
    >#! /usr/bin/sh
    >export CCOPTS='+z'
    >unset LANG
    >gmake distclean
    >CC=gcc ./configure --with-gcc --with-threads=no --without-cxx - >-prefix=/opt/python >
    >
    >gmake fails twice:
    >
    >1)
    >/osasto/home/niirape/python_softa/Python-2.2/Modules/getaddrinfo.c:544: >warning: >`h_error' might be used uninitialized in this funcn
    >In file included from /osasto/home/niirape/python_softa/Python >-2.2/Modules/socketmodule.c:239:
    >/osasto/home/niirape/python_softa/Python-2.2/Modules/getnameinfo.c: In >function >`getnameinfo':
    >/osasto/home/niirape/python_softa/Python-2.2/Modules/getnameinfo.c:184: >`h_errno' >undeclared (first use in this function)
    >/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c: In >function >`gethost_common':
    >/osasto/home/niirape/python_softa/Python-2.2/Modules/socketmodule.c:1975: >`h_errno' undeclared (first use in this function)
    >WARNING: building of extension "_socket" failed: command 'gcc' failed with >exit status 1 
    >
    >2)
    >gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I. >-I/osasto/home/niirape/python_softa/Python-2.2/./Include >-I/usr/local/incluo
    >ld -b build/temp.hp-ux-B.10.20-9000/777-2.2/_cursesmodule.o -L/usr/local/lib >-lncurses -o build/lib.hp-ux-B.10.20-9000/777-2.2/_curl
    >ld: DP relative code in file /usr/local/lib/libncurses.a(lib_addch.o) - shared >library must be position
    >    independent.  Use +z or +Z to recompile.
    >WARNING: building of extension "_curses" failed: command 'ld' failed with >exit status 1 
    >
    >Anybody solved these problems
    >
    >-pekka-
    >
    >Martin von Loewis wrote:
    >
    >
    pekka niiranen   href="mailto:krissepu at vip.fi"><krissepu at vip.fi>
    >  writes:

    >
    >
    I tried the build script below in HP-UX 10.20
    ( HP > -UX B.10.20 A 9000/777 2002144332 two-user license)
    and got the > following errors during make:

    cc -Ae -c -DNDEBUG -O -I. > -I./Include -DHAVE_CONFIG_H -o
    Modules/python.o > Modules/python.c
    (Bundled) cc: warning 480: The -A option is > available only with the
    C/ANSI C product; ignored.
    (Bundled) > cc: warning 480: The -O option is available only with the
    C/ANSI > C product; ignored.
    >
    >

    It seems that you are using the bundled > compiler. Python source code
    is ANSI C, you need an ANSI C > compiler to compile it. Try either the
    HP ANSI C compiler, or gcc > (the former being recommended).

    Regards,
    Martin
    >
    >
    > > >>--------------020604040107000300090304--> From laz at strakt.com Tue Mar 5 04:23:09 2002 From: laz at strakt.com (Fredrik Juhlin) Date: Tue, 5 Mar 2002 10:23:09 +0100 Subject: ICU wrapper for Python? In-Reply-To: References: Message-ID: <20020305092309.GB15135@strakt.com> On Fri, Mar 01, 2002 at 10:00:43PM +0100, Martin v. Loewis wrote: > Fredrik Juhlin writes: > > > I was fiddling around with a Python wrapper for the ICU libraries this > > weekend, when it occured to me to check if anyone else is/has been working > > on the same thing. I looked around a bit on the net but couldn't find > > anything, so I figured I'd drop a question here too :) > > Did you make any progress on that? I'd be most interested in exposing > the codecs. Yes I did, actually. My main interest was in collation, so that's what I've done so far. Now I'm at the point where I need to write some docs and such. However, I'm relying on the fact that since Python uses UCS-2 and ICU uses UTF-16 for their respective internal format, any Python unicode string can be used as an ICU unicode string. So for the collation I don't need to do any conversion between the two. To expose the codecs, one would have to convert the resulting strings from UTF-16 to UCS-2. I have functions to convert between Python unicode strings and ICU dittos and while they do work, they need to go through the "make it right" and "make it fast" stages. Also, so far I've only tested this on my own (x86 Linux) system. If you're interested in what I have so far, I'll stick it on a web server for downloading. That'll have to wait until tonight though, since my latest version is at home. Any feedback would certainly be welcome! //FJ From dsavitsk at e-coli.net Thu Mar 14 00:35:43 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 14 Mar 2002 05:35:43 GMT Subject: basic statistics in python References: Message-ID: it looks like there is a D/COM interface to R, though. Not really a python solution, but it might work anyway. "Matthew Austin" wrote in message news:QTUj8.10299$Ex5.957528 at bgtnsc04-news.ops.worldnet.att.net... > RPy has not been ported to Windows yet. > > > "Emile van Sebille" wrote in message > news:a6on8n$frj93$1 at ID-11957.news.dfncis.de... > > "dsavitsk" wrote in message > > news:OvQj8.10177$k5.3810357 at newssvr28.news.prodigy.com... > > > hi all, > > > > > > never having done numeric calculations in python* i am seeking advice > > on how > > > to best go about doing some basic statistics. in particular, i need > > to find > > > standard deviations and point bi-serial correlations**, and i am > > seeking > > > advice on the best way to go about it. i know how to do them, but i > > am > > > wondering if there are prebuilt modules that might simplify the task. > > > > You might want to take a look at rpy at > > http://www.cmat.edu.uy/~walterm/rpy/ > > > > -- > > > > Emile van Sebille > > emile at fenx.com > > > > --------- > > > > From florian.konnertz at web.de Fri Mar 15 15:19:14 2002 From: florian.konnertz at web.de (Florian Konnertz) Date: Fri, 15 Mar 2002 21:19:14 +0100 Subject: MySQL-mod: setup-error: invalid distrib.option 'platforms' Message-ID: <3C925742.8040001@web.de> Hi! Any idea how to solve this prob? root at xy /usr/local/mysql/MySQL-python-0.9.1 > python setup.py build error in setup script: invalid distribution option 'platforms' OS: SuSe 7.2 Python 2.0 MySQL: /usr/local/mysql/bin/mysql Ver 11.17 Distrib 3.23.49a, for pc-linux-gnu (i686) In setup.py I changed the following var. to my local paths: ... if sys.platform in ("linux-i386", "linux2"): # most Linux include_dirs = ['/usr/local/mysql/include/mysql'] # include_dirs = ['/usr/include/mysql'] library_dirs = ['/usr/local/mysql/lib'] # library_dirs = ['/usr/lib/mysql'] I appreciate your help! What's wrong? Are my paths too irregular? Thanx. From martin at v.loewis.de Fri Mar 29 18:11:37 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 00:11:37 +0100 Subject: IOError on file close References: Message-ID: "Michael S. Fischer" writes: > It appears that the write() call is the one that's failing, not the > close() call. Python is throwing the exception at the wrong time. > Should I report this as a Python bug? Not really. My guess is that the C library buffers the write call, and attempts to flush the stream when closing the file. This, in turn, produces the error - the write itself succeeds. Python uses the code n2 = fwrite(s, 1, n, f->f_fp); if (n2 != n) { PyErr_SetFromErrno(PyExc_IOError); clearerr(f->f_fp); return NULL; } so it would definitely report an exception if fwrite reported an error. Just try opening the file without buffering. Regards, Martin From rs96057 at hotmail.com Sat Mar 23 08:46:58 2002 From: rs96057 at hotmail.com (Dimitris Garanatsios) Date: Sat, 23 Mar 2002 15:46:58 +0200 Subject: Info needed on metaclasses / type-ing Message-ID: I recently browsed through an unfinished book of Bruce Eckel, "Thinking in Python", Revision 0.1.2 I can't remember the URL where i got it, but i found it through searching for documentation on Python from the main site, www.python.org I found the following peace of code there: ------------------------------------------------------------------ #: c01:SingletonMetaClass.py class SingletonMetaClass(type): def __init__(cls, name, bases, dict): super(SingletonMetaClass, cls).__init__(name, bases, dict) original_new = cls.__new__ def my_new(cls, *args, **kwds): if cls.instance == None: cls.instance = original_new(cls, *args, **kwds) return cls.instance cls.instance = None cls.__new__ = staticmethod(my_new) class bar(object): __metaclass__ = SingletonMetaClass def __init__(self,val): self.val = val def __str__(self): return `self` + self.val ... #:~ ------------------------------------------------------------------ My question is about the "SingletonMetaClass" class. I have tried in the past to create my own types using Python and just could not find a way of doing that since built-in type objects' structure where not documented. The "SingletonMetaClass though", as far as i can understand, please help me with that, is doing exactly what i wanted: a new type definition. I browsed Python's manuals to find more about the attributes and functions that are used, but found nothing... Could anyone help me find information about the meaning and use of the following attributes/functions/objects? These are: --- the "__metaclass__" attribute of the "bar" class (derived from object) --- the "object" object itself --- the "super" function used in the "SingletonMetaClass" class (a class for a new type object?) --- the "__new__" attribute/method of a class (applies to any class?) --- the "staticmethod" function used in the "SingletonMetaClass" class --- any additional info about related classes or functions that are not used in the above example but exist and are available to use Thanx, Dimitris From metaliu at yahoo.com Mon Mar 4 13:55:55 2002 From: metaliu at yahoo.com (Bill) Date: Mon, 4 Mar 2002 10:55:55 -0800 Subject: new images from strings using PIL References: Message-ID: Ahhhh. Thanks very much. "Fredrik Lundh" wrote in message news:Vvxg8.22784$n4.4309187 at newsc.telia.net... > try this instead: > > >>> pixels = "1 2 3 4 5 6" > >>> i = Image.new("L", (3, 2)) > >>> i.putdata(map(int, pixels.split())) > > >>> list(i.getdata()) > [1, 2, 3, 4, 5, 6] > > >>> i.getextrema() > (1, 6) > > (getdata returns a sequence object of an undefined type. to > see what's in it, convert it to a list or tuple before printing it) > > > > From peter at engcorp.com Sun Mar 31 01:44:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 01:44:33 -0500 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> <3CA5F90F.BF37B528@engcorp.com> Message-ID: <3CA6B051.6D55B4D5@engcorp.com> "Martin v. Loewis" wrote: > > Peter Hansen writes: > > > So does this change proposes to change the readability so that > > it is clear at a glance (at the source, not the documentation, which > > seems an odd thing to base this on) that those functions return > > boolean conditions rather than integers? > > The documentation should change as all, documenting that certain > functions return bool. But your point in the message I was replying to was that there are 300 functions which have code that says "return 0" or "return 1" or "return None" and the change will help users of those functions. Didn't that imply those users are not looking at the documentation, but are trying to read the source to figure out how the code works? If the documentation must be changed, why not just make it clear in the documentation what it means when a method returns 1 or 0 or None? > > Furthermore, there will be code breakage, and that should always > > rate very high on the list of reasons to leave well enough alone. > > Can you show examples of (real!) code that will break? Preferably code > you've written yourself. I don't even need to dig up examples since I so often put this code at the start of my modules: True, False = 1, 0 Or, now that I think of it, will that continue to work as these will just be built-ins now hidden by my local definitions? If so, my bad for mentioning code breakage. -Peter From phr-n2002a at nightsong.com Tue Mar 26 19:10:30 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 26 Mar 2002 16:10:30 -0800 Subject: python on Sharp Zaurus References: Message-ID: <7xadsuan0p.fsf@ruckus.brouhaha.com> Dave Reed writes: > Does anyone know if Python runs on the new Sharp Zaurus? > > http://www.idg.net/go.cgi?id=656429 Yes, it does. From fgeiger at datec.at Mon Mar 25 08:56:46 2002 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 25 Mar 2002 14:56:46 +0100 Subject: VideoCapture 0.7 causes Blue Screens on W2k Prof. Message-ID: Win2k Prof. / SP2 (German) DirectX 8.1 (German) PIL 1.1.2 VideoCapture 0.7 ActivePython 2.1.1 (Build 212) I'm experiencing Blue Screens when working with VideoCapture, especially after rerunning the app after correction of syntax errors: "STOP: 0x0000001E (0xC0000005, 0x00110010, 0x0000000, 0x00110010) KMODE_EXCEPTION_NOT_HANDLED Beginn des Speicherabbildes " Did anyone have this problem too and could get rid of it? Any other ideas? Thanks in advance and best regards Franz GEIGER From grante at visi.com Sat Mar 16 00:38:52 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 16 Mar 2002 05:38:52 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <2b57f654.0203151009.296bb7da@posting.google.com> Message-ID: In article <2b57f654.0203151009.296bb7da at posting.google.com>, wealthychef wrote: > grante at visi.com (Grant Edwards) wrote in message news:... >> In article <2b57f654.0203141934.391d1bcc at posting.google.com>, wealthychef wrote: >> >> > selectables = [theProcess.childerr, theProcess.fromchild] >> > (input, output, exc) = select.select([],selectables, selectables) >> >> It looks like you've got the first two parameters to select >> reversed. After the above call, output is going to contain >> writable sockets. If you're wanting to read data, you should >> do: >> >> (output, input, exc) = select.select(selectables,[],selectables) > > Ding ding ding! You are correct, sir! Thanks for the help, I was > doing it backwards. The python docs are a bit unclear to me on this > point. Thanks for the help, it now works perfectly as expectorated. Here's hint: Many of the Python libraries are just thin wrappers around the standard OS library calls. Doing a "man select" will get you more detailed information that may help you understand the Python docs better. Sometimes not. -- Grant Edwards grante Yow! HELLO, little boys! at Gimme a MINT TULIP!! Let's visi.com do the BOSSA NOVA!! From zugz.public at DELETEMEcwcom.net Tue Mar 19 13:07:01 2002 From: zugz.public at DELETEMEcwcom.net (Zugz) Date: Tue, 19 Mar 2002 18:07:01 -0000 Subject: Pure python alternative to mx.DateTime? References: Message-ID: <1016561221.17563.0.nnrp-13.c2463c5f@news.demon.co.uk> >Skip Montanaro" wrote in message news:mailman.1016547271.18075.python-list at python.org... > > Lutz> Unfortunately I'm in need of some simple time and date > Lutz> calculations (ISO-time, how many days from now, weekdays, etc.). > > Lutz> Is there any alternative to mx without inventing the wheel for the > Lutz> second time and programming it by myself? > > There's Jeff Bauer's NormalDate module: > > http://starship.python.net/crew/jbauer/normaldate/index.html Thanks for this link. Zugz. From gerson.kurz at t-online.de Sat Mar 9 12:21:39 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sat, 09 Mar 2002 17:21:39 GMT Subject: [ANN] UNBABTIZED - The language Message-ID: <3c8a4042.46048234@news.t-online.de> Bored, I spent the past few hours writing a small, 100% useless language. It doesn't have a name, so I call it UNBABTIZED (as in: has not been given a name yet), which is, right there, a self-contradiction. What a good start! Because the interpreter is written in python, you can enhance your existing scripting apps by a small, 100% useless language! You might even want to rewrite all your autocoding (TR) tools in UNBABTIZED if you find it easier to learn than plain python . Having said that, its a procedural language in that its not a functional one, and is probably best thought of as one very elaborate excursion away from brainfuck. You can write integer literals: "0", "1", and so on. UNBABTIZED has an array of 1000 memory cells. You can refer to memory cells: "?0" is the first memory cell, "?1" is the second memory cell, "?999" is the last memory cell. You can assign data to memory cells: "!x,y" will assign the value y (either literal or memory cell) to the memory cell of index x. Obviously, you cannot assign values to literals. Instructions are separated by ".", so "A.B.C" means three consecutive instructions A, B and C. You can do basic arithmetic: "~x,y" will set memory[x] to memory[x]+memory[y] "(x,y" will set memory[x] to memory[x]-memory[y] ")x,y" will set memory[x] to memory[x]*memory[y] "[x,y" will set memory[x] to memory[x]/memory[y] and evaluation "Ax,y" will set memory[x] to memory[x]memory[y] "&x,y" will set memory[x] to memory[x]>=memory[y] "/x,y" will set memory[x] to memory[x]<>memory[y] If you need logic functions, write wrapper code using arithmetic functions and evaluation. You can do output ":x" will write x as char "@x" will write x as integer There is no input. There is a philosophy behind this, you know! To my view, there are two kinds of input, user input and hardcoded input. User input sucks, and hardcoded input rules, so there. You can do a DO-WHILE-NOT style loop better expressed as a computed goto. This c-code loop_begin: ... if( memory[x] ) goto loop is written as "," ...(instructions here)... "-x" Loops can be nested (at least in theory, but I haven't tested this ;). There are no comments. Comments are for wimps! Note that Newlines, Tabs, Spaces etc. are considered comments, too, so they are not allowed either. Get an editor that can handle long lines, if you want to mess with UNBABTIZED. Examples? This :72.:101.:108.:108.:111.:32.:87.:111.:114.:108.:100 will print "Hello, World", and this !0,1.!1,1.!2,1.!3,1.,.@?0.!4,?0.!0,?1.~4,?0.!1,?4.~2,?3.!5,?2.A5,10.-5 will print the first ten fibonacci numbers. The interpreter reqiures Python 2.2 (or higher ;) because of the changes in lambda-scope. I'm using some of my lambda tricks here. The code looks very pythonesque, IMHO: ------------------------------- (cut here) ----------------------- import sys f = sys.argv[1] o = [0,[],[0]*1000,lambda x:o[4]("o[2]")+"x,o[2][x]%sy)" %x, lambda x:x+".__setitem__(",open(f).read().split("."),0, 1,None,lambda x,y:o.__setitem__(x,y),lambda:o[9](7,o[6] .find("?")),lambda:len(o[6][o[8]:o[8]+1]) and o[6][o[8] :o[8]+1] in "0123456789",lambda:o[9](6,o[6][:o[7]]+"o["\ "2]["+o[6][o[7]+1:o[8]]+"]"+o[6][o[8]:]),lambda:(o[11]( )and(o[9](8,o[8]+1),o[13]())or 0),lambda:o[7]>=0 and(o[ 9](8,o[7]+1),o[13](),o[12]()),lambda:"(lambda x=None,y"\ "=None:%s)(%s)"%({'!':o[4]("o[2]")+"x,y)",'@':"sys.std"\ "out.write(str(x)+chr(10))",':':"sys.stdout.write(chr("\ "x))",'~':o[3]("+"),'(':o[3]("-"),')':o[3]("*"),'[':o[3 ]("/"),"A":o[3]("<"),"?":o[3]("<="),"$":o[3]("=="),"%": o[3](">"),"&":o[3](">="),"/":o[3]("<>"),',':"o[1].appe"\ "nd(o[0])",'-':"o[2][x] and ("+o[4]("o")+"0,o[1][0]-1)"\ ",o[1].__setslice__(1,len(o[1]),o[1][1:]))or 0",}[o[6][ 0]],o[6][1:]),lambda:(o[9](6,o[5][o[0]]),o[10](),o[14]( ),eval(o[15]()),o[9](0,o[0]+1)),lambda:o[0] < len(o[5]) and(o[16](),o[17]())] o[17]() ------------------------------- (cut here) ----------------------- One thing though, I wanted to make o[17]() the last item in o, but that didn't work. Because, at the time o[17] is evaluated, o does not yet exist. [Long explanation: If you write o = then the interpreter will first evaluate , then create o and assign it. So you cannot refer to o other than in lambda statements. Even if you were to cheat by writing something like this o,x = ,o[17]() it wouldn't work, because the right side is treated as a tuple and evaluated first, and only THEN assigned to the left variables.] Has anybody any idea of how, with a possibly insane abuse of the rules, you could put the whole code in an array? Should I write a PEP? Anyway, enjoy! Gerson Kurz http://p-nand-q.com ps: Congratulations to Jason Orendorff for winning in this years IOCCC. From greg at cosc.canterbury.ac.nz Wed Mar 6 21:28:09 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Mar 2002 15:28:09 +1300 Subject: how to give an object as argument for a method References: Message-ID: <3C86D039.5FF7A99F@cosc.canterbury.ac.nz> Marco Herrn wrote: > > hmm, do I have to implement that in _every_ method or just in > methods who use the 'self' statement? In every method. The instance is always passed in as the first parameter, so there must be a parameter there to receive it, even if it's not used inside the method. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From grante at visi.com Mon Mar 11 14:15:34 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Mar 2002 19:15:34 GMT Subject: wxProgressDialog wonky under Win32 References: Message-ID: In article , Grant Edwards wrote: > Under Win32, the bargraph in a wxProgressDialog hits "full" > about 10-20% of the way to the "max" value. As usual, one never finds the answer until after the posting hits the net... According to one of the wx mailing list archives, this is a known bug in the MSW port of wxWindows (the "size" value of a gauge is treated as a 16-bit number). It's been fixed, but it's still available only from CVS. -- Grant Edwards grante Yow! .. the HIGHWAY is at made out of LIME JELLO and visi.com my HONDA is a barbequed OYSTER! Yum! From curtin at ubsw.com Tue Mar 5 18:29:47 2002 From: curtin at ubsw.com (craig curtin) Date: 5 Mar 2002 15:29:47 -0800 Subject: stdout/stderr disabled when debugging in pythonwin (somehow i disabled it...) References: <4c7395cb.0203050706.668a8eaa@posting.google.com> Message-ID: <4c7395cb.0203051529.26e77892@posting.google.com> i may have found the problem. i'm doing some WebDAV stuff and getting large quantities of XML data back from an Exchange 2000 server. well when i got the resultant data. sometimes the data had characters above 128. i did a search and decided to try this in my code: >>> import sys >>> reload(sys) >>> sys.setdefaultencoding('mbcs') and i *seemed* to fix the problem... but blew away my stdout/stderr in the mean time. craig From dsavitsk at e-coli.net Thu Mar 21 16:12:23 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 21 Mar 2002 21:12:23 GMT Subject: quick win32 pipe and objects question Message-ID: when writing and reading from a pipe, is it okay to do something like ... >>> t = (0, 1, 2, 3) >>> r = win32pipe.CallNamedPipe(pipename, t, 512, 0) of should i pickle t first? -d From shimmie at shimmie.com Tue Mar 19 08:07:59 2002 From: shimmie at shimmie.com (Shimmie) Date: Tue, 19 Mar 2002 13:07:59 GMT Subject: socket programming References: Message-ID: Here is a neat little UDP example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 Shimmie. > > Anybody know where can i find a good (beginner) tutorial > > about Socket Programming using Python ? From tchur at optushome.com.au Sun Mar 17 03:11:34 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 17 Mar 2002 19:11:34 +1100 Subject: Pythonic Porter stemmers (Was: Re: Word frequencies -- Python or Perl for performance?) References: Message-ID: <3C944FB6.221C0EAC@optushome.com.au> Bengt Richter wrote: > > On Sat, 16 Mar 2002 09:50:32 +1100, Tim Churches wrote: > [...] > > > >I concur with Bengt's suggested approach, plus you might want to use > >something like the Porter Stemmer algorithm to convert words to their > >"base" forms eg stepped -> step > > > >See http://www.tartarus.org/~martin/PorterStemmer/python.txt for a > >Python implementation. > > > Any idea on the license status of that? I saw nothing mentioned > in the text itself except and apparent reference to a book. No idea re that code, but the Porter stemming algorithm was described in the computer science literature about 20 years ago, and AFAIK, the algorithm is not encumbered by any patents (but you probably should do a patent search anyway). Also, there are a number of other algorithms which have been developed since, but I have no idea whether any of them are generally better, or better for particular purposes. To my lay eyes, computational linguistics seems like a fascinating but sprawling field of endeavour and one really needs an expert guide to find one's way around. > > E.g., if I rewrote it to my taste, could I put the result under PSF > if I wanted to? It you worked from a description of the Porter stemmer algorithm rather than the existing code, you would be free to license the result any way you please. Now, I have just discovered another Python implementation of the Porter stemmer sitting on my hard disk, but I have no idea where I downloaded it from, and alas, there is no clue to its source or the licensing in the file, so I sincerely hope I am not violating the terms under which I originally downloaded it by placing a copy at http://gestalt-system.sourceforge.net/Porter.py in case anyone is interested in it or can identify its provenance. Cheers, Tim C From hughett at mercur.uphs.upenn.edu Fri Mar 8 10:41:37 2002 From: hughett at mercur.uphs.upenn.edu (Paul Hughett) Date: 8 Mar 2002 15:41:37 GMT Subject: ANN: BBLimage 0.66 now available Message-ID: The source distribution kit for BBLimage version 0.66 is now available from http://www.med.upenn.edu/bbl/bblimage BBLimage is a collection of tools for processing volume images, especially medical images; it includes Pyvox, a Python extension for large multi-dimensional arrays. Features added in release 0.66 include: The qdv image viewer now supports 2x zoom, and linking the two displayed images so that image motion commands apply to both; this facilitates the comparison of related images using the blink comparator. Computation of the chamfer distance and various image statistics have been added. Most functions for array norms, metrics, and histograms now accept an optional weight argument. The registration classes now support the Pearson product moment correlation as a similarity metric; they also support an initial/baseline transform and yield a transform relative to that baseline. BBLimage is currently available as an alpha release under an open- source license and is written in ANSI C and designed to be easily portable to any Unix or Posix-compatible platform. Some programs also require the X Window System. Paul Hughett ================================================================ Paul Hughett, Ph.D. Research Associate Brain Behavior Laboratory 10th floor Gates Building Hospital of the University (215) 662-6095 (voice) of Pennsylvania (215) 662-7903 (fax) 3400 Spruce Street Philadelphia PA 19104 hughett at bbl.med.upenn.edu A rose by any other name confuses the issue. -Patrick E. Raume ================================================================ From jimd at vega.starshine.org Mon Mar 25 02:27:40 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 25 Mar 2002 07:27:40 GMT Subject: files and reading from them References: Message-ID: In article , ricky wrote: > not sure what you mean > but check out the "shelve" module >"Avi Homes" wrote in message >news:auzn8.71680$Vl.2635455 at typhoon.austin.rr.com... >> I am writing a dictionary to a file, like so >> f.write(str(Info)) >> and what it is writing to the file is the following.. >> {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} >> and if i write in two things, i get.. >> {'IPrice': '3', 'IName': 'lame lame', 'IDesc': 'stuff} >> {'IPrice': '2', 'IName': 'notworking, 'IDesc': 'annoying'} >> What i would like to do is pull a readline or somesuch.. and have it >> take in the whole thing, and then just let me assign that to a empty >> name, and turn it into a new dictionary.. like say >> file.seek(1) >> //thats how i'd go to the first place in the file correct? >> X=file.readline() >> and now i can say print X['IName'] ... and its turned into a >> dictionary.. i am most likely going about this *all* wrong. It sounds like you're trying to write your file out in "repr" form (representing an object as the string or command that would instantiate it). I guess you'd do something like: f=open("...","r") objlist = [] for each in f.readlines(): objlist.append(eval(each)) To create an list of anonymous objects. In your case that would be a list of dictionaries. From martinkaufmann at yahoo.com Tue Mar 12 07:22:18 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Wed, 13 Mar 2002 01:22:18 +1300 Subject: Question about scientific calculations in Python Message-ID: Hello Newsgroup I'm trying to write a program to calculate diffraction patterns for electron diffraction on clusters (100-10'000 atoms). So far I used Python only for CGI programming and system tools (on a rather low level...). Therefore I don't know whether it's reasonable to program such a project in Python (I really like the language). Presently my man concern is speed as the main function of the program is a nested loop, the inner over several 1000 bins of a histogram and the outer over several 1000 values of scattering factors. In the end I should be able to simulate diffraction patterns and compare them to the experimental data (i.e. run this function several times). Now my questions: Would it be best to (a) write the whole program in C/C++ (I know only the basics of C but it would be a good "excuse" to learn it...)? (b) write the main program in Python but the heavy calculations in C (I played today with scipy.weave -- the speed is much better but I didn't really understand what I was doing...)? (c) program it in Python and don't care about speed (or buy a new workstation...)? Are there any libraries or other resources that would help? I used the Scientific Python library for the histogram but it was much slower than my DIY approach. I hope my questions are not too much OT. Thanks a lot for your help. Martin From hzhu at mars.localdomain Tue Mar 5 03:55:52 2002 From: hzhu at mars.localdomain (Huaiyu Zhu) Date: Tue, 05 Mar 2002 08:55:52 GMT Subject: mult-indexed xrange? References: Message-ID: On Mon, 4 Mar 2002 22:06:24 -0600, Jason Orendorff wrote: >Huaiyu Zhu wrote: >> I forgot to mention: without generating temporary lists. >> >> > >> >for (x,y) in [(i,j) for i in range(2) for j in range(3) ]: >> > print x,y >> >0 0 0 >> >0 0 1 >> ... >> >> Is list comprehension lazy, ie. without generating the actual list? > >No, list comprehensions are eager. > >You want generators: > >from __future__ import generators > >def pairs(n, m): > for i in xrange(n): > for j in xrange(m): > yield (i, j) > >for (x, y) in pairs(2, 3): > print x, y > >## Jason Orendorff http://www.jorendorff.com/ > Well, that was what I started with. :-) I gave a more general solution, which could be an extension of xrange to multiple indices. I was wondering if there is a builtin facility for this. Looks like there isn't. Huaiyu From fperez528 at yahoo.com Fri Mar 15 10:06:53 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 15 Mar 2002 15:06:53 +0000 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: Jonathan Gardner wrote: > I have a free software program (http://sf.net/projects/bttotalcontrol/) and > I am having great difficulty writing an installation script for windows. > > I don't want to use distutils because I am not writing a module - but an > entire distribution with images, data files, and executable programs. I > would like to put icons on the desktop and stuff in the start menu as well. > > I am at a major disadvantage because I don't have access to a windows > machine, and so I can't test anything directly. However, I do have a few > people who actively test for the project at home. > > Anyone have any suggestions on where I should go? Anyone can help me out > here? > > Jonathan This was my rough solution. It may be a reasonable starting point for you. If you want to test it (it won't work on its own), grab the IPython package from http://www-hep.colorado.edu/~fperez/ipython/ and install it on a Windows box (have one of your testers do it) to see how it works. Let me warn you though that doing the development in linux and the debugging in windows will be tricky. IPython was all written in linux, but for writing this setup script I had to install PythonWin so I could actually do the testing. Good luck, f. """Use this script to install IPython in Windows platforms. Wrapper around setup.py which creates appropriate entries in the Start Menu. This is quick and dirty, but seems to work reasonably well.""" #***************************************************************************** # Copyright (C) 2001 Fernando P?rez. # # Distributed under the terms of the GNU Lesser General Public License (LGPL) # # The full text of the LGPL is available at: # # http://www.gnu.org/copyleft/lesser.html #***************************************************************************** __author__ = 'Fernando P?rez. ' __version__= '0.1.0' __license__ = 'LGPL' import sys,os,shutil from win32com.shell import shell import pythoncom import _winreg as wreg #-------------------------------------------------------------------------- def make_shortcut(fname,target,args='',start_in='',comment='',icon=None): """Make a Windows shortcut (.lnk) file. make_shortcut(fname,target,args='',start_in='',comment='',icon=None) Arguments: fname - name of the final shortcut file (include the .lnk) target - what the shortcut will point to args - additional arguments to pass to the target program start_in - directory where the target command will be called comment - for the popup tooltips icon - optional icon file. This must be a tuple of the type (icon_file,index), where index is the index of the icon you want in the file. For single .ico files, index=0, but for icon libraries contained in a single file it can be >0. """ shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink ) shortcut.SetPath(target) shortcut.SetArguments(args) shortcut.SetWorkingDirectory(start_in) shortcut.SetDescription(comment) if icon: shortcut.SetIconLocation(*icon) shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(fname,0) #-------------------------------------------------------------------------- # 'Main' code # First run the distutils generic installer setup = os.path.join(os.getcwd(),'setup.py') sys.argv = [setup,'install'] try: execfile(setup) except: einfo = map(str,sys.exc_info()[:2]) print '\n\nThere were problems with the installer:',' '.join(einfo) raw_input('Press Enter to exit') sys.exit() # Now make some windows-only niceties. # Find where the Start Menu and My Documents are on the filesystem key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") programs_dir = wreg.QueryValueEx(key,'Programs')[0] my_documents_dir = wreg.QueryValueEx(key,'Personal')[0] key.Close() # File and directory names ip_dir = 'C:\\Program Files\\IPython' ip_prog_dir = programs_dir + '\\IPython' doc_dir = ip_dir+'\\doc' ip_filename = ip_dir+'\\IPython_shell.py' pycon_icon = doc_dir+'\\pycon.ico' if not os.path.isdir(ip_dir): os.mkdir(ip_dir) # Copy startup script and documentation shutil.copy(sys.prefix+'\\Scripts\\ipython',ip_filename) if os.path.isdir(doc_dir): shutil.rmtree(doc_dir) shutil.copytree('doc',doc_dir) # make shortcuts for IPython, html and pdf docs. print '\n\n\nMaking entries for IPython in Start Menu...', # Create shortcuts in Programs\IPython: if not os.path.isdir(ip_prog_dir): os.mkdir(ip_prog_dir) os.chdir(ip_prog_dir) manual_dir = doc_dir + '\\manual' man_htm = manual_dir + '\\manual.html' man_pdf = manual_dir + '\\manual.pdf' make_shortcut('IPython.lnk',sys.executable, '"%s"' % ip_filename, my_documents_dir, 'IPython - Enhanced python command line interpreter', (pycon_icon,0)) make_shortcut('Manual in HTML format.lnk',man_htm,'','', 'IPython Manual - HTML format') make_shortcut('Manual in PDF format.lnk',man_pdf,'','', 'IPython Manual - PDF format') print """Done. I created the directory C:\\Program Files\\IPython. There you will find the IPython startup script and manuals. An IPython menu was also created in your Start Menu, with entries for IPython itself and the manual in HTML and PDF formats. For reading PDF documents you need the freely available Adobe Acrobat Reader. If you don't have it, you can download it from: http://www.adobe.com/products/acrobat/readstep2.html Finished with IPython installation. Press Enter to exit this installer.""", raw_input() From erno-news at erno.iki.fi Fri Mar 1 08:27:31 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 01 Mar 2002 15:27:31 +0200 Subject: Useful, robust shell utilities References: Message-ID: In article , Jonathan Gardner writes: | Is there an effort to make a robust, useful shutil module that has the | equivalent of the unix shell utilities? yes, mostly. (there might be some missing system calls - but they are covered quite well). | I think it would be nice to make things like 'grep' even... | Here is my wish list. [...] you could use the existing utilities and save the trouble :) | If there isn't an effort to make this, or if no one has done anything like | this yet, I am willing to volunteer some time to do it. It would be really | nice if they ended up being compatible with Windows and Macintosh - give | them some powerful tools they didn't even know existed! you can get the real things for windows with cygwin. macintoshes are natively unix-based these days. if you decide to go ahead with it, you could look into for ideas and inspiration. -- erno From gerhard at bigfoot.de Thu Mar 14 22:06:32 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 15 Mar 2002 03:06:32 GMT Subject: Python2.2 and expat References: Message-ID: Trent Mick wrote in comp.lang.python: > [Colin Fox wrote] >> Hello, everyone. >> >> I'm trying to build garnome, which requires Python2.2 + Python2.2-xml. >> I've got Python2.2 built, but for some reason it doesn't seem to build >> expat. And when I try to "import xml.parsers.expat" I get: >> >> >>> import xml.parsers.expat >> Traceback (most recent call last): >> File "", line 1, in ? >> File "/usr/local/lib/python2.2/xml/parsers/expat.py", line 4, in ? >> from pyexpat import * >> ImportError: No module named pyexpat >> >> Where is pyexpat supposed to come from? > > There is a section on building the pyexpat extension in > dist\src\PCbuild\readme.txt. Basically you need a separate build of expat in > the right place so that Python pyexpat build can find and use it. His path didn't look like he's using Windows. Gerhard, picking nits -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From nospam at [127.0.0.1] Mon Mar 11 16:49:32 2002 From: nospam at [127.0.0.1] (Chris) Date: Mon, 11 Mar 2002 21:49:32 +0000 Subject: should i learn it first ? References: <7CWi8.104549$aFN.34864@news1.bloor.is> Message-ID: In article <7CWi8.104549$aFN.34864 at news1.bloor.is>, Qiang.JL writes >yeah. i have been following my post. thanks for everyone's input. It >helps! >seems a lot people recommend C over C++, i would keep this in mind and >get a go at it. i think i get a list of language to learn and go deeper >now : Java, C, Perl, Python, Lisp I've been following it, too, with great interest. I reckon I'm going to go for Python and Java. Java is particularly attractive because you can distribute your programs to absolutely anybody in the form of applets. Not sure about learning Linux though - that seems a bit too much to take on! -- Chris From nhodgson at bigpond.net.au Wed Mar 20 18:21:26 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 20 Mar 2002 23:21:26 GMT Subject: Newspaper infiltration Message-ID: It appears that some Python force is contaminating the ordinarily technically challenged mainstream Australian press. First we get an Interview with Mark, then this Zope article turns up on the second page of the IT section of the local paper: http://www.it.mycareer.com.au/news/2002/03/19/FFXF7G6VSYC.html Could it be a sleeper from the From h.baumgartl at quicknet.nl Wed Mar 6 11:04:04 2002 From: h.baumgartl at quicknet.nl (Henry Baumgartl) Date: Wed, 6 Mar 2002 17:04:04 +0100 Subject: dynamic loading of modules Message-ID: <000701c1c528$8acfea50$c19949d5@dkn02> Hello all, Having recently embarked on my journey into Python land, I would like to know if there is an elegant solution to the following problem: I would like to be able to compound variables that will then form the name of the particular module to be loaded into the active script. Long lists of -if- and -elif- statements don't really do the trick, as one still has to hardcode all possible options and defeating the dynamic nature of the application. A solution I came up with was to write a new module every time the process starts, and loading this to get to the dynamically selected sub-modules. Unfortunately, as the name of the 'new' module needs to be hardcoded for this scheme to work, only one user can safely use the application at any one time, which is not good enough. Any suggestions to resolve my dilemma will be greatly appreciated. Best Regards, Henry Baumgartl From ws at mystrobl.de Sun Mar 17 16:26:21 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Sun, 17 Mar 2002 22:26:21 +0100 Subject: Windows NT shell + extended characters. Bug or what? References: Message-ID: 17 Mar 2002 20:46:57 +0100, martin at v.loewis.de (Martin v. Loewis): >Wolfgang Strobl writes: > >> >This is rather unlikely, I doubt the interactive interpreter will ever >> >be able to properly identify the encoding of the console window. >> >> What's wrong with GetConsoleOutputCP, besides the restrictions >> documented in "Q99795 SetConsoleOutputCP Only Effective with Unicode >> Fonts"? > >There are several problems with that: >- as you point it, it fails for the raster fonts (for no apparent > reason) Carefull. The problem applies to _SetConsoleOutputCP, the reason being "SetConsoleOutputCP() is designed to change the mapping of the 256 8-bit character values into the glyph set of a fixed-pitch Unicode font, rather than loading a separate, non-Unicode font for each call to SetConsoleOutputCP(). " according to the Knowledge Base entry mentioned above. _Identifying_ the input and output encoding of the console window is no problem at all. >- for outputting Unicode, OutputConsoleW is more appropriate, IMO, > since it can also output characters not supported in the output > code page. AFAIK there is no function OutputConsoleW. Do you mean WriteConsoleW? >- we were talking about input. Admittedly, GetConsoleCP might be of > use here Right. >- it is tricky to determine reliably that a file descriptor is > connected to a terminal. I wouldn't want the python interpreter become dependent on whether the stdout file descriptor is connected to a console window or not. Either always use the CPs of the console window associated with the current process, or never. IMHO, a standard module which allows more control over platform specific parameters (like the code pages of the console window, if there is one) would be my prefered solution to this class of problems. -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From sender at usgcl.org Sun Mar 10 08:29:12 2002 From: sender at usgcl.org (United States Green Card Lottery Organization) Date: Sun, 10 Mar 2002 05:29:12 -0800 Subject: Invite: Your American Green Card Application Message-ID: An HTML attachment was scrubbed... URL: From eppstein at ics.uci.edu Mon Mar 11 12:12:44 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 11 Mar 2002 09:12:44 -0800 Subject: lambda question References: Message-ID: In article , "Alves, Carlos Alberto - Coelce" wrote: > first code: > > f='x**3+2*x' > list=[0,1,2,0] > map(lambda x:eval(f),list) > > second code: > > def exe1(f,list): > return map(lambda x:eval(f),list) > > Can someone explain to me why the first code works while second doesn't. You defined exe1 but forgot to call it? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From eppstein at ics.uci.edu Sat Mar 2 01:52:20 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 01 Mar 2002 22:52:20 -0800 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: In article , "Raymond Hettinger" wrote: > There is a pair of ideas that are intuitive, clean, and routinely useful: > for i in indici(seqn) > for i, item in indexed(seqn) Isn't this in PEP 212? Maybe it should be undeferred? -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From jwilhelm at outsourcefinancial.com Thu Mar 21 10:18:13 2002 From: jwilhelm at outsourcefinancial.com (Joseph Wilhelm) Date: 21 Mar 2002 08:18:13 -0700 Subject: Python & IRC In-Reply-To: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> References: <_Wcm8.134736$Nn6.6764300@e3500-atl2.usenetserver.com> Message-ID: <1016723894.26539.2.camel@jwilhelm.ofsloans.com> On Wed, 2002-03-20 at 21:07, Felix wrote: > Greetings everyone, > > I'm not sure if you guys here might be > able ot help me but i have been looking up and down for a irc client that > alllows me ot script in python. I found one but it doesn't seem that the > owners of this client are making any type of head way in it's development. I > know Xchat allows to use python as a scripting language but that is with the > linux version not windows. > > If anyone here has experience with irc and creating scripts for a > particular irc client please your help would be greatly appreciated in > pointing me in the right direction. Well, I haven't written any scripts for it myself, but Bersirc v2.0beta (At dev9 right now, dev10 is slightly delayed) does allow Windows Active Scripting, which should let you use Python. http://beta.bersirc.com/ --Joseph Wilhelm From rdsteph at earthlink.net Sun Mar 17 13:36:03 2002 From: rdsteph at earthlink.net (Ron Stephens) Date: Sun, 17 Mar 2002 18:36:03 GMT Subject: Gumbie: a GUI Generator for Jython Message-ID: <3C94E29F.A48FE107@earthlink.net> Jet lagged, but couldn't resist reading an article in Dr Dobbs Journal April print magazine I just picked up. Hoping for alternate ways to create simple GUI apps for the new Sharp Zaurus. Gumbie: a GUI generator for Jython is an article by Peter Brinkman starting on page 46 (I haven't even looked for an online version). Gumbie is an extensible, GPL'ed program that allows for rapid creation of simple user input-output menu driven GUI's for Java programs using AWT. The author suggests it could easily be extended to use Swing widgets, and, since none of the generic classes of Gumbie use Java classes, it could also be extended to use Tk widgets, or , one presumes, wxPython widgets or Qt widgets (which might be extra useful for the new Sharp Zaurus). I am wondering if anyone else who reads this article has any comments. Although I have limited time available, I want to eventually convert some very simple "applets" I have written in Python into nice GUI apps for the Zaurus (which I don't own yet). Hey, it's a hobby.. I have just received my copy of GUI Programming with Python using the Qt toolkit by Boudjewin Rempt, but the copy of Black Adder I ordered online two weeks ago hasn't shown up yet. (sigh) One option for the Zaurus is to use Qtopia to run a GUI created by Back Adder. Another option would be to convert my Python applets to Jython (it worked for one already, with some difficulty) but I need a way to create a simple gui front end for the jython applets. Maybe this Gumbie will work??? I don't want the complexity of using Java's native Swing etc. (but by the time I'm finished, I may wish I had just learned to do it the "hard way" with pure java :_))). I think there must be lots of "non programmers" who want to find an easy way to convert simple command line Python scripts into simple GUI input-output programs. Python makes writing simple command line scripts easy enough for part time duffers; but how to create the gui??? I haven't' checked out easy gui yet, but with so many options, even checking them all out is a time consuming job ;-)) > Python Card seems to be aimed at much more complex stuff than the simple input-output nice -looking gui's I need for my command line programs. A solution for this might interest an awful lot of duffers... Anyway, Gumbie looks like it is easily extensible in many ways. I imagine it could also be easily converted to a pure Python program, rather than Jython, and then easily extended to other widget toolkits; maybe even extended to work on the Zaurus then? Or maybe EasyGUI is a better starting point? If I take a year or so, I might even be able to extend Gumbie myself. If no one does, maybe I will. But someone more able might do it in a day or two; I could help ;-))) Anyone else like Gumbie??? P.S. my first trip to the bookstore upon returning home form my travels also yielded the february issue of Linux Format with anice series of articles on the Sharp Zaurus 5000D (developer version) and the upcoming 5500 commercial release Zaurus running embeded linux with embedded Qt and Jeode (Java version). Anyone seen the developer version and care to comment???? Ron Stephens From albgrig at tiscalinet.it Sat Mar 2 18:44:50 2002 From: albgrig at tiscalinet.it (Alberto Griggio) Date: Sun, 03 Mar 2002 00:44:50 +0100 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: some other examples which may be useful... Mandrake 8.1, GCC 3.0.2, libc 2.2.4 Python 2.2 (#3, Jan 28 2002, 11:45:43) [GCC 3.0.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 0.0 >>> but ... #include #include #include #include int main(void) { double d; errno = 0; d = pow(1e-200, 2); if(!errno) printf("OK: %f\n", d); else printf("Error: %d, %s\n", errno, strerror(errno)); return errno; } prints: Error: 34, Numerical result out of range On slackware 8.0, GCC 2.95.3, libc 2.2.3, both the python and the C code fail. Finally, if you change pow to powf in the C code above, it gives no error. Hope someone can understand what's happening... Bye, Alberto Griggio From skip at pobox.com Mon Mar 25 23:05:25 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 25 Mar 2002 22:05:25 -0600 Subject: Indentation problem In-Reply-To: <7isn6o9fld.fsf@enark.csis.hku.hk> References: <7isn6o9fld.fsf@enark.csis.hku.hk> Message-ID: <15519.62341.138159.906794@12-248-41-177.client.attbi.com> Isaac> I'd rather suggest to have a Python-specific indentation command Isaac> in Emacs that will "reindent a region in a way that fits the Isaac> current indentation style and fit in the current context, but Isaac> retain the original meaning". This really shouldn't be that Isaac> difficult. Anyone will try his elisp skills? Check out python-mode: http://www.python.org/emacs/python-mode/ It already has key bindings C-c > and C-c < which indent or dedent the selected region by the indentation delta. Works like a charm. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From FredandFey at hotmail.com Mon Mar 18 22:00:14 2002 From: FredandFey at hotmail.com (Conchos) Date: Mon, 18 Mar 2002 20:00:14 -0700 Subject: Compile.py References: <3c9570f8_1@corp-goliath.newsgroups.com> Message-ID: <3c96a95e_2@corp-news.newsgroups.com> Sheesh, one little syntax error and ya blow these guys out of the water! I believe what you're looking for is compile.py ( lower case 'c' ) and it can be found at http://starship.python.net/crew/mhammond/ppw32/ under chapter 22. hth, Beware the waiting room. "San" wrote in message news:3c9570f8_1 at corp-goliath.newsgroups.com... > Hello, > > Very new to Python. "Programming on Win32" mentions David Asher's > Compile.py. > I've found a Compile.py in the sources \Tools\compiler folder. This > script seems to be expecting arguments, and in fact I drop into the "no > files to compile" case, presumably from getopt. > > This contrasts "Win32"'s example, where no arguments are used ( thought > a setup.in and source files in the current directory are assumed). Am I > using the right script, or have I totally missed something? > > Thanks, > M.E.I. > > > > > ________________________________________________________________________ ______ > Posted Via Binaries.net = SPEED+RETENTION+COMPLETION = http://www.binaries.net From robin at jessikat.fsnet.co.uk Sun Mar 10 03:29:06 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 10 Mar 2002 08:29:06 +0000 Subject: import gadfly causes 500 Server Error -- anyone know how to fix? References: <3C8AFB43.275714BB@erols.com> Message-ID: <3lL8uKASlxi8Ewsz@jessikat.fsnet.co.uk> In article <3C8AFB43.275714BB at erols.com>, Jerry Gitomer writes ..... > >500 Server Error > >The server encountered an internal error and could not complete >your request. ..... you should probably have a general mechanism at the highest level to trap any uncaught errors. Eg in your top level script you should have something that prints out the traceback. typically try: print getresult() except: print "content-type: text/html" print print "" print "

    An Error Occurred.

    " print "
    "
            import traceback
            traceback.print_exc()
            print "
    " print "" any error in the whole process wil result in a traceback being produced. In this case I suspect that gadfly is not importable in the runing context. To discover why you can import sys and print out sys.path etc in the sectuon after the print "
    " above.
    -- 
    Robin Becker
    
    
    From sagwy at earthlink.net  Mon Mar 25 16:55:06 2002
    From: sagwy at earthlink.net (mo)
    Date: Mon, 25 Mar 2002 14:55:06 -0700
    Subject: RELEASED: Python 2.2.1c1
    References:  
    Message-ID: <032b01c1d447$d7503910$a689ea43@gatesway>
    
    Mo
    
    > Michael Hudson  writes:
    >
    > > Depending on how many problems are found in this release, 2.2.1
    > > final or a second release candidate will follow next week.
    >
    > It will be 2.2.1c2 and it will be released in about 22 hours time.
    
    This is like pacing outside a delivery room.  Thank you for this
    update.   More importantly, thanks to all of you "Doctors" laboring on
    our behalf.
    
    Mo
    
    
    
    
    From mickey at tm.informatik.uni-frankfurt.de  Sun Mar 10 18:01:51 2002
    From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer)
    Date: 11 Mar 2002 01:01:51 +0200
    Subject: How "expensive" are Exceptions?
    Message-ID: <3c8bf3ef@nntp.server.uni-frankfurt.de>
    
    Hi, given the fact that excpetion handling can be very
    expensive in languages like C++ - is python similar in
    this aspect?
    
    For instance, given somefunc() which sometimes (often)
    returns a tuple and sometimes (rare) an integer - which version
    would be to prefer?
    
    Which version would be to prefer if the return types
    are distributed evenly?
    
    a)
    
    try:
        a, b = somefunc()
    except:
        return None
    ...
    b)
    
    selection = somefunc()
    if len( selection ) != 2:
        return None
    else:
        model, iter = selection
    ...
    
    Yours,
    
    Mickey.
    
    
    
    From Kevin.Smith at sas.com  Fri Mar  1 09:31:34 2002
    From: Kevin.Smith at sas.com (Kevin Smith)
    Date: 1 Mar 2002 14:31:34 GMT
    Subject: Swapping out sys.stdout globally
    Message-ID: <20020301093135467-0500@braeburn.na.sas.com>
    
    I am working on a command-line utility written in Python which daemonizes
    itself.  In the process of daemonizing, sys.stdout and sys.stderr are
    redirected to now file-like objects as follows:
    
    sys.stdout = NewFile()
    sys.stderr = NewFile()
    
    However, I have some logging routines in a separate package that already
    have their own references to sys.stdout and sys.stderr which are
    unaffected by this.  Is there a way to chonge where sys.stdout and
    sys.stderr print their output to and have this change affect all existing
    references?
    
    -- 
    Kevin SmithKevin.Smith at sas.com
    
    
    From erno-news at erno.iki.fi  Mon Mar 18 08:29:29 2002
    From: erno-news at erno.iki.fi (Erno Kuusela)
    Date: 18 Mar 2002 15:29:29 +0200
    Subject: select.select() on Regular Files?
    References:     
    Message-ID: 
    
    In article , jimd at vega.starshine.org (Jim
    Dennis) writes:
    
    |  I guess the newer versions of FreeBSD are ahead of Linux in this
    |  category.  Hopefully Ben LaHaise' AIO work will get merged in soon
    |  and in a few years we can relegate "while (1) { nanosleep(); stat(); }"
    |  to the history books.
     
    for linux (and irix), have a look in
    .
    
      -- erno
    
    
    From philh at comuno.freeserve.co.uk  Tue Mar 26 09:44:42 2002
    From: philh at comuno.freeserve.co.uk (phil hunt)
    Date: Tue, 26 Mar 2002 14:44:42 +0000
    Subject: Python UK - April 4th and 5th
    References: <1017148758.18693.0.nnrp-01.c1c3e11b@news.demon.co.uk>
    Message-ID: 
    
    On Tue, 26 Mar 2002 13:19:13 -0000, Paul Brian  wrote:
    >Dear all,
    >
    >This is another gentle reminder for those Python enthusiasts in the UK that
    >the
    >2nd Python UK Conference will take place on April the 4th and 5th near
    >Stratford upon Avon.
    >
    >The two day conference is packed full of talks on cutting edge applications
    >of Python, with time to meet, socialise and even discuss code, life and love
    >with fellow Pythonistas. You even get access to the full ACCU conference,
    >attended by luminaries such as Bjarne Stroustrup.
    >
    >You can register online at www.accuconference.co.uk , and further details
    >are available there too.  Please note that Python attendees should pay the
    >daily rate for the conference (?130 /day for ACCU members, ?155 else) for
    >the one or two days they choose to attend.
    
    Perhaps I'm being a little obtuse here, but why would I want to pay
    260 quid to talk about Python? I can talk about it here for 
    nothing.
    
    I guess this is something intended to be funded by the delegates' 
    employers.
    
    -- 
    <"><"><"> Philip Hunt  <"><"><">
    "I would guess that he really believes whatever is politically 
    advantageous for him to believe." 
                            -- Alison Brooks, referring to Michael
                                  Portillo, on soc.history.what-if
    
    
    From jim at publishingresources.com  Fri Mar 22 15:54:48 2002
    From: jim at publishingresources.com (Jim Abrams)
    Date: Fri, 22 Mar 2002 20:54:48 -0000
    Subject: Python embedded like PHP
    References: 
    Message-ID: 
    
    "Rob Nikander"  wrote in news:Tjtj8.48802$3O2.18198075
    @typhoon.southeast.rr.com:
    
    > Are there any projects out there that allow you to embed python in HTML
    > like PHP?  I like the PHP-style of embedding the bits of program in HTML,
    > but I'd like to use python...
    > Something like:
    > 
    > 
    >       print "
      " > for reptile in ["Crocodile", "Python", "Iguana", "Tortoise"]: > print "
    • %s
    • " % reptile > print "
    " > ?> > While mentioning M$ is this thread might get me lynched I still feel the need to mention (esp since I'm forced to live in a M$ shop) Python in ASP. I find it very attractive to be able to do <% print >> _out, "
      " for reptile in ["Crocodile", "Python", "Iguana", "Tortoise"]: print >> _out, "
    • %s
    • " % reptile print >> _out, "
    " %> or even <% import HTMLgen print >> _out, UL(["Crocodile", "Python", "Iguana", "Tortoise"]) %> adding another jelly bean to the shring to MH ly 'yrs -Jim From acockburn at aol.com Thu Mar 28 20:08:12 2002 From: acockburn at aol.com (Alistair Cockburn) Date: 28 Mar 2002 17:08:12 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Mar 26) References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Message-ID: Geoff Gerrietts wrote in message news:... > I think poetry and code are actually very similar. Some day I may > write a paper on that thesis, but I'm still living the experience > today.... Try "Software Development as Community Poetry Writing", http://members.aol.com/acockburn/papers/swaspoem/swpo.htm That's the best I did along that track... (some systems programmers told me it described their life accurately) Alistair From syver-en+usenet at online.no Tue Mar 12 21:26:06 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Wed, 13 Mar 2002 02:26:06 GMT Subject: Redirecting output in Windows NT References: <96e9dee5.0203120044.33a1e19c@posting.google.com> <3C8DC473.2070809@skippinet.com.au> <5cf809e9.0203121718.6d999426@posting.google.com> Message-ID: peter.schwalm at epost.de (Peter Schwalm) writes: > > >It is a bug in the NT command prompt. Works OK in Win2k. I > believe > > > >there is a FAQ on it too. > > > > You state that *output* redirection works OK in Win2k. I could verify > that, but unfortunately it's not true for the redirection of *input*. > If I want to redirect input, I still have to use the form > > python myprog.py > instead of the simpler > > myprog <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87u1s0eth5.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: Stephen J. Turnbull wrote: ---lots snipped--- Thanks for your well balanced commands, they sure refined my thinking on the subject. > My _very_ personal opinion is that identifiers can be run through an > online dictionary, and I'm fortunate to be pretty good at languages, > so that's fun. Nor do I do programming for a living, I can afford to > concentrate on "fun." Yep fun, but very hard as single word translation is amongs the hardest translation problems. Wouldn't it be better if we had a kind of inter-lingua-meaning-representation and each and every identifier linked to one by the author of the code himself? The `translation' process could then be automated, and everyone could read the source in her/his own language. (I know, in practice next to impossible to achieve such a inter-lingua complete with all the mappings to all the languages out there, but he I'm porting an old project I was involved in that tried this route for general texts, so why not dream on:) > My opinion as a teacher is that I'd really like to be able to teach > programming to my freshmen with a language that uses Japanese > identifiers (including reserved words) and syntax (Japanese is a > reverse Polish language). We used to make fun of the french who had their own version of Algol, but growing older, wiser(?) and more experienced and finally having kids of my own that want to program I've come to appreciate this point more and more. And now with the world getting smaller and smaller thanks to internet, I tent to think it's a problem we should tackle. ... > A correct comment in an illegible character set is harmless, although > perhaps frustrating; an incorrect one that you can read is dangerous. very true > So I'd have to say that except for the very worst cases, there are > benefits to having code in English, or near-English, vocabulary. But > comments should be written in a language you can use for teaching. Well, atleast a language you are reasonably well versed in as to prevent those `incorrect' comments. -- groetjes, carel From junkster at rochester.rr.com Sun Mar 10 10:23:50 2002 From: junkster at rochester.rr.com (Benjamin Schollnick) Date: Sun, 10 Mar 2002 15:23:50 GMT Subject: Walk Directories via Caching (& Dup file detection) Message-ID: A little while ago, some folks were posting some caching routines for dirwalk..... Here's something that I cooked up a while ago.... Now, I've added just recently full & partial MD5 hashing, and I'm slowly adding duplicate file checking... It seems to work fine, but it definetly could use some optimizations & speed ups... Anyone have any input? Is there some faster method I could use, that I've missed? The main idea is that the walk tree is built once, and the class just walks through the list (in memory), instead of walking through the hard drive.... (This was written rather quickly when I realized that searching for hundred's of files, through dirwalk was too slow, because for each file, it would have to go through the hard drive each time.) There are two major data structures: self.index_directory_names = [] self.index_directory_files = [] They are "logically" linked. The files in index_directory_files[x] are in index_directory_names[x], and vice versa. I've just recently added the MD5 code, for duplicate detection, which is really where I'm looking for the majority of any optimization.... It's *FAST*, or at least takes a reasonable amount of time with 45,000 files.... (I think it takes about 30-45 minutes for that...? I haven't timed it) - Benjamin ---------------------------------- #from bas_common import * # True / false syn's for boolean expressions import dircache import sys import os import string import shutil import time import md5 #mac_mode = macintosh mac_mode = 0 # code stored in bas_common if mac_mode: import findertools import findertools import macfs import macostools def full_md5_digest(filename, block=(8*1024) ): """Return 16 byte MD5 digest of entire given file. """ f = open(filename, 'rb') data = f.read(block) D = md5.new() while data: D.update(data) data = f.read(block) f.close() digest = D.digest() return digest def short_md5_digest(filename, block=(8*1024) ): """Return 16 byte MD5 digest of given file. """ f = open(filename, 'rb') data = f.read(block) D = md5.new() D.update(data) f.close() digest = D.digest() return digest class directory_walk: def __init__ ( self ): self.index_directory_names = [] self.index_directory_files = [] self.use_md5 = 1 self.files_to_skip = ["FILE_ID.DIZ", "README.TXT", "READ.ME", "README", "ID.DOC", ".DS_STORE", # Do Not Remove, Mac OS X File "ICON", # Do Not Remove, Mac OS File "ICON_" # Do Not Remove, Mac OS File ] self.upper_case = None def __list_files ( self, arg, dirname, names ): if self.upper_case: self.index_directory_names.append ( string.upper( string.strip(dirname) ) ) for j in range(0, len(names)): names[j] = names[j].upper() else: self.index_directory_names.append ( string.strip(dirname) ) self.index_directory_files.append ( names ) def build_search_tree ( self, base_directory_name): self.index_directory_names = [] self.index_directory_files = [] os.path.walk ( base_directory_name, self.__list_files, None) def use_upper_case ( self ): self.upper_case = 1 def single_file_exist (self, filename): if self.upper_case: filename = string.upper(filename) listing_size = len(self.index_directory_files) for x in range(0, listing_size): try: junk = self.index_directory_files[x].index(filename) return (1, string.strip(self.index_directory_names[x] ) ) except: pass return (None, None) def return_duplicates_filenames ( self ): duplicate_files = [] master_list = [] print "# of directories : ", len(self.index_directory_names) for x in range(0, len(self.index_directory_names)): print ".", for filename in self.index_directory_files[x]: filename = string.strip(string.upper(filename)) if not(filename in self.files_to_skip): if os.path.isfile (os.path.join(self.index_directory_names[x], filename)): master_list.append (filename) if master_list.count(filename) >= 2: if duplicate_files.count(filename) == 0: duplicate_files.append (filename) print return duplicate_files def return_all_directories_from_file ( self, filename): file_directories = [] for x in range(0, len(self.index_directory_names)): if self.index_directory_files[x].count(filename) >= 1: file_directories.append ( self.index_directory_names[x]) return file_directories def filter_via_md5 ( self, dup_file_list, md5_filter ): duplicate_files = [] master_list = [] for filename in dup_file_list: file_locations = self.return_all_directories_from_file (filename) for location in file_locations: duplicate_files.append ( (filename, location, md5_filter (os.path.join(location, filename)) ) ) return duplicate_files fss, ok = macfs.GetDirectory('Duplicate Search Directory:') if not ok: sys.exit(0) else: dup_directory = fss.as_pathname() dir_find = directory_walk() dir_find.use_upper_case() print "Search Tree" dir_find.build_search_tree ( dup_directory ) print "End Search Tree" output_file = open("results.txt", "w") print "Begin" dup_files = dir_find.return_duplicates_filenames () md5_output = dir_find.filter_via_md5 ( dup_files, short_md5_digest ) length_of_md5_output = len(md5_output) optimized_md5 = [] for scan in range(0, length_of_md5_output): optimized_md5.append (md5_output[scan][2]) print "Number of Files to Validate: ", length_of_md5_output for counter in range(0, length_of_md5_output): if optimized_md5.count ( md5_output[counter][2]) >= 2: for scan in range(counter, length_of_md5_output): if (md5_output[scan][2] == md5_output[counter][2]) and scan<>counter: output_file.writelines ( "\r", "-"*40) output_file.writelines ( "\rFile: %s" % md5_output[counter][0] ) output_file.writelines ( "\r\tLocation : %s " % md5_output[scan][1] ) print "\r", "-"*40 print "\rFile: %s" % md5_output[counter][0] print "\r\tLocation : %s " % md5_output[scan][1] while optimized_md5.count ( md5_output[counter][2]): try: optimized_md5.remove( md5_output[counter][2]) except: pass print "\r\tLocation : %s " % md5_output[counter][1] output_file.writelines ( "\r\tLocation : %s " % md5_output[counter][1] ) output_file.close() print "End" #for filename in dup_files: # print "-"*40,"\n" # output_file.writelines ("-"*40,"\r") # print filename # output_file.writelines (filename, "\r") # dup_directories = dir_find.return_all_directories_from_file ( filename ) # for dir in dup_directories: # print "\t%s" % dir # output_file.writelines ("\t%s\r" % dir) # print "-"*40,"\n" # output_file.writelines ("-"*40,"\r") sys.exit(5) From david.abrahams at rcn.com Sat Mar 30 11:08:48 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sat, 30 Mar 2002 11:08:48 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net><008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com><200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net><014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> Message-ID: <01ae01c1d805$83b4e0f0$0202a8c0@boostconsulting.com> ----- Original Message ----- From: "Andrew Koenig" > David> void f(int const&); > David> f(false); // error! > > For the sake of nitpicking correctness, I cannot help but point out > that there is nothing wrong with the call of f(false) above unless you > drop the "const" from f's parameter type. Yeah, I realized that after posting it, and hoped nobody would notice. void f(int const*); bool x = false; f(&x); // error! thanks-for-nothing-ly y'rs, dave From tim.one at comcast.net Wed Mar 6 23:24:08 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 06 Mar 2002 23:24:08 -0500 Subject: The language vs. the environment In-Reply-To: <15494.34706.724985.628479@beluga.mojam.com> Message-ID: [Skip Montanaro] > There has been a huge amount of recent PEP activity related to further > enhancements to the language. I think in general that if more of this > energy was directed at the overall environment (library, support tools, > installers, documentation, etc) we'd be better off in the long run. Let's not discount the short run either . Guido opined today that he wants 2.3 to be a relatively modest "consolidation" release. As a result, I don't expect he's going to approve "new feature" PEPs for 2.3 that aim at the core language proper. to-everything-there-is-a-season-and-a-time-for-every-purpose-under- python-ly y'rs - tim From greg at cosc.canterbury.ac.nz Fri Mar 1 00:08:35 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 01 Mar 2002 18:08:35 +1300 Subject: list vs. dict References: <3C7CF0EE.3010009@vscht.cz> <3C7CFAF8.1080108@mxm.dk> <3C7E8D47.21BE30B3@ccvcorp.com> Message-ID: <3C7F0CD3.E70832BB@cosc.canterbury.ac.nz> David Eppstein wrote: > > It would be good if dict.has_key(x,y) > worked without having to double the parentheses I don't have a recent enough Python at my fingertips to check, but I think if (x,y) in dict does the same thing nowadays. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From quinn at vomit.ugcs.caltech.edu Wed Mar 13 04:47:21 2002 From: quinn at vomit.ugcs.caltech.edu (Quinn Dunkan) Date: 13 Mar 2002 09:47:21 GMT Subject: structseq and keywords? Message-ID: Is structseq supposed to take keyword args? From the source I assume it was meant to, but they're unused. I suppose they'd interact poorly with sequence args, but I'd expect them to be mutually exclusive: ss(attr=bar) #-> attr set to bar, rest set to None ss(a, b, c) #-> initialize with (a, b, c) It also seems odd that structseq expects a single sequence rather than a variable number of args. I've been meaning to give python access to structseqs, since I think it would be useful for python as well as C code. From emile at fenx.com Mon Mar 4 06:51:47 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 4 Mar 2002 03:51:47 -0800 Subject: what is happening at __init__ References: <3C8358C0.81D97AD8@doc.ic.ac.uk> Message-ID: "Benjamin Tai" [snip] > class A: > x = 100 > > class B(A): > > def __init__(self): > # Q1 > print 'inside constructor self is ', self > self = 300 Self is a container. Assign to its attributes, ie, self.x = 300. You've just created a new thing called self as a local variable within __init__. > # Q2 > print 'inside constructor self is ', self Again, as a local variable this is 300. Make the change above then try printing self.x instead. > # Q3 > return None No need to do this. All functions return None when not explicity returning something else. > > b = 200 This is immediately changed with the following statement, and has no effect. > b = B() > print 'after constructor instance b is ', b > # Q4 > print 'instance b contains attribute x, valued ', b.x B has not defined an x attribute, so this comes from A. Work through the appropriate tutorial sections again. HTH, -- Emile van Sebille emile at fenx.com From philh at comuno.freeserve.co.uk Sat Mar 30 17:46:00 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Sat, 30 Mar 2002 22:46:00 +0000 Subject: PEP 285: Adding a bool type References: Message-ID: On Sat, 30 Mar 2002 08:38:00 -0500, Guido van Rossum wrote: > >Tim must be missing something. The obvious way to turn a bool b into >an int is int(b). Will this work on old versions of python? I've just checked that it works on 2.0, but what about 1.5.1 or 1.6? I'd guess (b*1) would work on everything, however. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From michael at stroeder.com Thu Mar 14 10:18:00 2002 From: michael at stroeder.com (=?ISO-8859-15?Q?Michael_Str=F6der?=) Date: Thu, 14 Mar 2002 16:18:00 +0100 Subject: Python-DB2 module and DB2 Connect References: <3C90A125.4020208@stroeder.com> Message-ID: <3C90BF28.8080301@stroeder.com> Michael Str?der wrote: > > Anyone here which had success with using DB2-Python-0.991 (see > ftp://people.linuxkorea.co.kr/pub/DB2/) build against DB2 Connect? Seems to work. (DB2 Connect under Linux against DB2 OS/390 6.x) Ciao, Michael. From orangefree89 at localhost.localdomain Sat Mar 16 07:30:54 2002 From: orangefree89 at localhost.localdomain (orangefree89) Date: Sat, 16 Mar 2002 12:30:54 GMT Subject: Good book on Python? References: Message-ID: On Fri, 15 Mar 2002 18:37:53 +0000, Chris wrote: > Thank you. > I downloaded number 4. > However, it is in a strange form (Tex) for a windows user. > Is it any use to me in that form? > And can it be obtained in any other form? > (It does look good.) Yassas. I'm pretty sure it is also available in pdf. I found the book very useful (I'm not a programmer by training). From susan at mars.provis.com Wed Mar 27 13:00:48 2002 From: susan at mars.provis.com (Susan Williams) Date: Wed, 27 Mar 2002 12:00:48 -0600 (CST) Subject: Linux-related help Message-ID: <200203271800.g2RI0m323782@mars.provis.com> Howdy, y'all, [No one will remember me, but I'm back after a long absense because--you guessed it--I have a problem and I want some help...] We are attempting to port from Solaris to Linux, and I'm having some unpleasant malloc/free problems at exit (sys.exit). We have running software based currently on 1.5.2. We're compiling on Linux with gcc 3.0.3 (on Solaris we were using Sun's compiler, not gcc, I think). Unfortunately I have a 3rd party module I'm linking with python that is rather ancient. We first got it when using python 1.3, we "ported" it to 1.5.2, and I can't quite pin down whether it is the root of the problem or not, perhaps it is doing something not quite kosher. (The idea of trying to get it running with 2.1 gives me the willies, but that is not really today's issue.) Anyone out there using Linux especially with 1.5.2 is this ringing any bells? On exit, python is clearing the list of modules, each module is clearing dictionary entries by setting them to None, and it is the decref that is blowing up. It is not always in the same place, but it is always in the code that is setting a dictionary value to None and deleting whatever was there before. Any ideas welcome. I'm not too well versed on either the innards of python or the proper coding for module extensions. thanks... sue williams From gh_pythonlist at gmx.de Sun Mar 31 20:34:02 2002 From: gh_pythonlist at gmx.de (Gerhard =?unknown-8bit?Q?H=E4ring?=) Date: Mon, 1 Apr 2002 03:34:02 +0200 Subject: Python/Linux In-Reply-To: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> References: <0UMp8.42204$1f1.3348597@e3500-atl2.usenetserver.com> Message-ID: <20020401013402.GA333@lilith.hqd-internal> * Robert Oschler [2002-03-31 18:24 -0500]: > [...] I'd like to know which Web site development tool you like the best, As for a Python web application framework, I like WebWare. Zope is also cool, especially if you can reuse an existing "product". > because I'm going to assume that you're using one that integrates well with > Python. So you're speaking of a HTML editor or what? > Bear in mind that I'm one of those who like to be spoiled by a nice WYSIWIG ^^^^^^^ There is no such thing as WYSIWYG - and as a long-time (Windows) developer you sure know ;-) It's really WYSIWYMGITEUHETSC (what you see is what you might get if the end-user has exactly the same configuration). After all, HTML is a *markup* language, not a page layout system. But of course, you can tell the browser what you think is a good layout by means of CSS. > IDE if possible. If you're into WYSIWYMG, I prefer Mozilla's Composer for that. I use it for prototyping pages. Editing HTML I do with a real editor [tm]. Mine is vim. > Here's is the choice list I've built up after surfing much, post much, and > reading much replies: > Quanta > Bluefish > PHP (Will I need to learn this or any other scripting lang if I'm using > Python for all my custom site stuff?) No, you can do can do everything in Python. Using a framework like Webware/Quixote/Albatross/... makes this even easier. Apart from that, I'm no fan of code-in-html style programming, though all the frameworks support it in one way or the other. > Open Office's HTML tool > Delph/Kylix with perhaps kbmWABD (I'm Delphi prog'er too) > IBM's WebSphere home page builder (yes I know it cost a little) That, and Mozilla seem to be your only options for Linux-native WYSIWYMG. Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 6.3 ?C Wind: 0.5 m/s From ocscwar at h-after-ocsc.mit.edu Wed Mar 13 13:54:50 2002 From: ocscwar at h-after-ocsc.mit.edu (Omri Schwarz) Date: 13 Mar 2002 13:54:50 -0500 Subject: Newbie regex question. Message-ID: I have a regex = re.compile('yadda (widget1) (widget2) yadda') and want to search a string I know to have multiple instances of this regex. I'm a tad confused by the RE Howto, so I'd like to ask, how do I properly get a for loop to access the widget1 and widget2 strings of each instance? for instance in regex.search(string).groups() seems to be the right thing, but isn't working. -- Omri Schwarz --- ocscwar at mit.edu ('h' before war) Timeless wisdom of biomedical engineering: "Noise is principally due to the presence of the patient." -- R.F. Farr From gry at ll.mit.edu Mon Mar 11 13:56:20 2002 From: gry at ll.mit.edu (george young) Date: Mon, 11 Mar 2002 13:56:20 -0500 Subject: 2.2 install fails with "SyntaxError: invalid token" compiling many library files Message-ID: <20020311135620.6caa78e5.gry@ll.mit.edu> Python 2.2, SuSE Linux 7.3 [2.4.10] When running(as root) make install of Python 2.2, I get many (550 !) errors like: File "/usr/local/lib/python2.2/Bastion.py", line 1 " ^ SyntaxError: invalid token in compile_all.py. In fact a manual: ./python Python 2.2 (#5, Mar 11 2002, 13:03:58) [GCC 3.0.4] on linux2 >>> import py_compile >>> py_compile.compile('/usr/local/lib/python2.2/Bastion.py') gets the same error. If I edit the Bastion.py file and put a blank line at the front, it compiles fine. What gives? ................................................. Also at the end of the install, it crashes with: running build running build_ext skipping 'regex' extension (up-to-date) skipping 'pcre' extension (up-to-date) skipping '_hotshot' extension (up-to-date) skipping 'strop' extension (up-to-date) WARNING: removing "strop" since importing it failed Traceback (most recent call last): File "./setup.py", line 793, in ? main() File "./setup.py", line 787, in main scripts = ['Tools/scripts/pydoc'] File "/home/geoyou/Python-2.2/Lib/distutils/core.py", line 138, in setup dist.run_commands() File "/home/geoyou/Python-2.2/Lib/distutils/dist.py", line 893, in run_commands self.run_command(cmd) File "/home/geoyou/Python-2.2/Lib/distutils/dist.py", line 913, in run_command cmd_obj.run() File "/home/geoyou/Python-2.2/Lib/distutils/command/build.py", line 107, in run self.run_command(cmd_name) File "/home/geoyou/Python-2.2/Lib/distutils/cmd.py", line 330, in run_command self.distribution.run_command(command) File "/home/geoyou/Python-2.2/Lib/distutils/dist.py", line 913, in run_command cmd_obj.run() File "/home/geoyou/Python-2.2/Lib/distutils/command/build_ext.py", line 256, in run self.build_extensions() File "./setup.py", line 147, in build_extensions build_ext.build_extensions(self) File "/home/geoyou/Python-2.2/Lib/distutils/command/build_ext.py", line 383, in build_extensions self.build_extension(ext) File "./setup.py", line 179, in build_extension for filename in self._built_objects: File "/home/geoyou/Python-2.2/Lib/distutils/cmd.py", line 107, in __getattr__ raise AttributeError, attr AttributeError: _built_objects make: *** [sharedmods] Error 1 What gives? -- George -- I cannot think why the whole bed of the ocean is not one solid mass of oysters, so prolific they seem. Ah, I am wandering! Strange how the brain controls the brain! -- Sherlock Holmes in "The Dying Detective" From skip at pobox.com Wed Mar 6 17:28:39 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 6 Mar 2002 16:28:39 -0600 Subject: Need feedback - What are the elements of a good hosting service? Message-ID: <15494.38935.365327.383880@beluga.mojam.com> Yesterday afternoon I posted a note soliciting input on what people feel the main issues are related to web hosting services, at least vis a vis Python. As I indicated, I think the secondary issues may be more important than the more obvious "primary" issues. Let me expand on that a bit. My goal is to create a hosting page for the python.org website that will be useful to people looking for a Python-friendly web hosting service. Simply listing all hosting services that provide a Python interpreter probably won't be too useful. Here are what seem to me to be the so-called "primary" questions to ask: * Is Python available? What version(s)? * Can I install a private version of Python? * Can I write my own CGI scripts? * How do I set up my website? * How many system resources can I use (disk space, bandwidth, email messages, whatever)? * How much does it cost? Most of these questions are readily answered. In fact, except for the last two, I can probably answer them pretty accurately for any given hosting service: yes; 1.5.2 & 2.1; yes, for shell accounts; yes; FTP, Front Page or ssh/scp, depending on the OS and web server running. I've developed and/or maintained two websites for Mojam for several years now. As such, I've been in pretty much full control of the environment. One of the server machines I run is keeping my legs warm as I type this. Over the years, I'd taken lots of stuff for granted: * root access * easily set up mailing lists * start/stop the web server itself and other related software (database servers, sendmail, etc) * set up long-running processes for any of a number of reasons (monitoring, background file processing, etc) * browse Apache access/error logs and configuration files (and modify as necessary) I recently signed up with a hosting service to work on my own corporate website and to experiment with Webware. While they are a reputable company and I'm happy so far with the answers to the primary questions, some of the secondary issues have caused me more trouble than I had anticipated. Here are the stumbling blocks I've run into: * Although they made it easy to view my server's access log, I couldn't tell how to view the error log (that's where the Python traceback winds up with you muff something). I asked. Turned out there is an undocumented command available to execute to view your recent error log contents. Because it's a shell-based service, the machine is pretty tightly locked up, so browsing to see what's available is pretty much out of the question. (I can't "ls /usr/local/bin", for example.) * Though their Acceptable Use Policy said they'd consider long-running programs on a case-by-case basis, when I asked about a specific case (running Webware/WebKit's AppServer), I got an immediate "no". Even though I explained that allowing me to run AppServer would actually reduce CPU resource usage by avoiding startup/shutdown overhead, I have yet to resolve this issue with them. (They can boot me for violation of their AUP. What recourse do I have if they violate it? ;-) * Even though this hosting company supports Python (1.5.2 and 2.1 are installed), and I know they use it heavily in their back office, it's clear their front-line support staff aren't well-versed in Python usage. When I approached them about one problem I was having with a CGI script, they ran it at the shell prompt without setting the proper environment variables (like REQUEST_METHOD), saw the traceback and concluded it was broken. * My almost idle webserver was getting lots of clear breakin attempts - accesses to paths like /scripts/..%255c../winnt/system32/cmd.exe. I reported this to them and suggested it would be not much more difficult for them to block and report such malicious accesses for their entire suite of servers than for me to block on an IP-by-IP basis. After several go-rounds I finally got a note from one of their sysadmins indicating they would block on the machine my virtual server resides on. No word on actually reporting the bad guys. As you can see, these startup issues have very little to do with Python. They do lead me to a set of secondary questions, however: * What facilities or commands are available over and above the usual Unix or Windows stuff? Corollaries: What non-standard Python libraries are installed? PIL? Zope? MySQLdb? How up-to-date are they? How complete is their documentation? * What about long-running programs? Really? * How well do front-line support staff understand basic Python issues? * How well do they operate as responsible net citizens? Do they go after the bad guys or is that your problem? I'm not sure those questions form a complete "basis set" of questions whose answers will help people make intelligent decisions about a hosting service, but had I known to ask them ahead of time, I would have had a somewhat easier introduction to the realm of web hosting. How do other peoples' experiences jive with mine? What do you feel it important to ask going into the process over and above what I've referred to as the "primary questions"? Do you agree that those that seem important to me are actually of general importance? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From tim.one at comcast.net Fri Mar 8 16:38:37 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 08 Mar 2002 16:38:37 -0500 Subject: PEP Parade In-Reply-To: Message-ID: [Donn Cave] > I have proposed before that those of us who are into having > a viable tool instead of a moving target, should just pick one > and stick with it. 2.1.1, for example. 2.1.2 would be a better choice, unless you also object to people fixing bugs for you . > Of course you and I can do that, solving the problems with our > respective groups - but putting us in kind of a backwater. If we > sort of collectively agree on 2.1.1 (or whatever) for that role, > though, that backwater could get pretty lively. I expect PythonLabs will continue wrapping up bugfix releases in the 2.1.x series for as long as someone volunteers to produce them. At the moment, 2.1.2 is the end of that line, as 2.1.2 was the last 2.1.x release to attract a volunteer. The longer someone waits to start on a 2.1.3, the harder it will be to sort through, and backport, relevant fixes now going into 2.2.1 (which Michael Hudson is producing) and 2.3 (where most current development occurs). "lively"-is-less-useful-than-someone-willing-to-work-ly y'rs - tim From peter at engcorp.com Sun Mar 31 11:01:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 11:01:26 -0500 Subject: Most important extensions? References: <3CA6ADEC.80859964@engcorp.com> Message-ID: <3CA732D6.91163F1E@engcorp.com> Aahz wrote: > > Peter Hansen wrote: > >I take it PyXml and PyUnit no longer qualify as "extensions"? > > You got it. > > >(Not that the idea of unit testing would necessarily appeal > >to Perl programmers anyway.) > > Let me make clear that one of my goals for this tutorial (despite my > occasional snarks here on c.l.py) is to have NO advocacy and NO war. That's a far better form of advocacy than T-shirts promoting Jesus' hatred of Java! I do hope you will have a chance to mention PyUnit anyway, even if not as an extension. Learning how to use it will definitely improve a programmer's productivity. -Peter From bokr at oz.net Sun Mar 3 04:50:58 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Mar 2002 09:50:58 GMT Subject: RFC PEP candidate: q''quoted ? Message-ID: Problem: How to put quotes around an arbitrary program text? Obviously a program may contain quoted material using all the defined string quoting methods (and this new method as well), so the problem is defining delimiters that won't occur in the text. I propose using a variation of the MIME multipart delimiter idea: The leading delimiter for this new quoted string will be written just like a raw string, except using 'q' in place of 'r'. The interpretation of '\' escapes within q'xxx' will be identical to r'xxx' Immediately following the trailing quote(s) of the q'xxx' (or q'''xxx''') string, the quoted content starts. '\' characters will be scanned as just another literal character, and have no escape effect in this content. The content continues until the defined raw delimiter q-string occurs, i.e., the xxx part of q'xxx' or q"""xxx""" etc. Thus the whole value of the q'delim'...delim string representation is exactly just the characters between the delimiters. E.g., you could write assert q'<-=delim=->'content here<-=delim=-> == 'content here' # this would be true without getting an error. Note the lack of quotes around the final delimiter string, since it itself is the final delimiter. This can also be used to solve the final unescaped backslash problem for quoting windows paths: q'|'c:\foo\bar\| Also note nestability, assuming you guarantee unique delimiter strings (which you could do by generating a guid if paranoid, or if you had access to the whole string before outputting the delimiter, you could e.g. use an MD5 hash of the content in hex as delimiter): q' C7593104AF1DE7534F169D5EF1579BF6 'q'|'c:\foo\bar\| C7593104AF1DE7534F169D5EF1579BF6 (Note two EOLs in the delimiter besides the MD5, so the quoted content itself has no EOL in it here) To make this line oriented quoting a little cleaner (i.e., no funny ' at the beginning of the first quoted line), one could use Q'xxx'z123 to mean q'xxxz'123 I.e., include the first raw character in the otherwise super-quoted content as part of the delimiter, and start the content with the next character. Below is assumed a single character EOL. Thus you can include an EOL at both ends of the delimiter, and assert Q' C7593104AF1DE7534F169D5EF1579BF6' q'|'c:\foo\bar\| C7593104AF1DE7534F169D5EF1579BF6 == q'~'q'|'c:\foo\bar\|~ would not fail (we can write the last, since we know the content). of course knowing the content here, you could also wrap with r"q'|'c:\foo\bar\|" A null q delimiter could be defined to imply delimiting by the end of the file or other representation container. I.e., q''<-- content up to EOF --> Escapes are recognized according to raw string rules inside the quotes of the q delimiter string, so the delimiter itself does have a final backslash problem, but that shouldn't be too hard to live with, since there's no such problem for the quoted payload. A q string could theoretically allow putting unescaped arbitrary binary data in a source file, though many editors would have problems dealing with it. Even so, there might be some use for that. E.g., a binary .gif file could easily be converted to an importable file binding a symbol to the gif data as a string. Just prefix symbol = q'' as in symbol = q''. Or you could delimit on both ends of course. BTW, this will provide a better raw data encapsulation mechanism than XML has ;-) (XML's construct can't nest, because of the fixed delimiters -- though maybe they have a fix by now. I haven't looked for the most recent spec). I don't know how hard q'xxx'...xxx would be to implement, but I would think a relatively minor variant of raw string processing would do it (just at the usual end continue instead of wrapping up, and look for the string you have so far as a trailing delimiter for a new string starting with the next character). The Q'xxx'z...xxxz variant isn't essential. Just a way to put an EOL at the z for aesthetics. Regards, Bengt Richter From theller at python.net Tue Mar 26 10:15:14 2002 From: theller at python.net (Thomas Heller) Date: Tue, 26 Mar 2002 16:15:14 +0100 Subject: PEP262 - database of installed packages References: Message-ID: "A.M. Kuchling" wrote in message news:slrnaa13du.cmq.akuchlin at crystal.mems-exchange.org... > In article , Wolfgang Strobl wrote: > > ownerdescriptor=GetFileSecurity(filename,OWNER_SECURITY_INFORMATION) > > ... owner=ownerdescriptor.GetSecurityDescriptorOwner() > > ... ownername=LookupAccountSid(None,owner) > > ... return ownername[0] > > That wouldn't be hard to support on Windows. The question for Windows > developers is simply: is it useful to support this? I'll defer to > Thomas or Tim on that point. > This code requires Mark's win32all extensions to be installed. win32all may be a very common extension, but it is definitely not a requirement. I keep the suggestion I made before: So, for PEP 262, wouldn't it be sufficient to use "" as user (since we don't care), and the value of S_IMODE(st[ST_MODE]) as permission? Tim, what do you think? Thomas From phr-n2002a at nightsong.com Wed Mar 6 17:46:13 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 06 Mar 2002 14:46:13 -0800 Subject: The language vs. the environment References: Message-ID: <7x1yexe2mi.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > There has been a huge amount of recent PEP activity related to further > enhancements to the language. I think in general that if more of this > energy was directed at the overall environment (library, support tools, > installers, documentation, etc) we'd be better off in the long run. While we're at it, am I the only one bothered by how unsharp the boundary is between the language and the environment? I'd consider things like sys.exc_info to be part of the environment, but there's no other way to get the info. From robin at jessikat.fsnet.co.uk Fri Mar 1 04:07:58 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 1 Mar 2002 09:07:58 +0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> Message-ID: . .... > >However, if you are on a 9x platform, and quoting the command just as >you want the command interpreter to see it on the command line doesn't >work, you might just want to revert to using the short (non-space) >version of the name. So in your example you would replace "program >files" with "progra~1" (or whatever it may be in the unlikely event >it's different than that). > >-- >-- David this is win2k. I have tried quoting with "", but I still seem to be getting no such command C:\program etc -- Robin Becker From greg at cosc.canterbury.ac.nz Thu Mar 7 22:11:44 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 08 Mar 2002 16:11:44 +1300 Subject: Integers class...? References: Message-ID: <3C882BF0.B7B6A239@cosc.canterbury.ac.nz> Magnus Lie Hetland wrote: > > from ints import ints > > for x in ints[0, 2, ..., 10]: > print x If you're doing that, it might be better to use the existing slice notation: for x in ints[0:11]: ... The only new thing to learn then is that 'ints' is a sequence containing (conceptually) all the integers. Hmmm, I'm sure someone suggested this before... The only thing you don't get from that is an easy way to iterate backwards. The best I can think of is for x in reverse(ints[0:11]): But then to make it lazy, reverse() would have to do some interesting things. (And no, I don't want an xreverse function! I hate x... names.) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From jamie.carl at salientnetworks.com.au Tue Mar 5 17:55:41 2002 From: jamie.carl at salientnetworks.com.au (Jamie Carl) Date: Tue, 05 Mar 2002 22:55:41 GMT Subject: python IDE, komodo References: <3c84f0eb.27475796@news.easynews.net> Message-ID: <3c854cbd$1_1@news.iprimus.com.au> "Trent Mick" wrote in message news:mailman.1015348989.22065.python-list at python.org... > [Marcus Stojek wrote] > > Hi, > > > > I am looking for an Python IDE. Nothing extremly special, just > > easy debugging, tracing maybe profiling. Is Komodo okay? > > Is there something else (except Visual Studio .NET) I should > > look at. Something free would be nice. > > Komodo is good, but I am biased. :) > Take a look at: > http://www.python.org/editors/ > Didn't he say free would be nice? Komodo isn't free. > > Trent > > -- > Trent Mick > TrentM at ActiveState.com > From johnroth at ameritech.net Wed Mar 13 20:13:50 2002 From: johnroth at ameritech.net (John Roth) Date: Wed, 13 Mar 2002 20:13:50 -0500 Subject: Why I think range is a wart. References: Message-ID: "Daniel Dittmar" wrote in message news:a6o24g$5t5$1 at news1.wdf.sap-ag.de... > > It happens to me too, mostly when I'm using a sliding window > > type algorithm, that is, I need to look at two adjacent members > > of the list. You can't do this easily by iterating through the list; > > unrolling the first entry and the last entry are a pain. > > > > Is there a way of handling this nicely? Somehow I doubt it. > > class ListWindow: > def __init__ (self, list): > self.list = list + [None] # assuming None is a suitable out of > bounds value > > def __getitem__ (self, index): > return self.list [index:index + 2] > > for currentItem, nextItem in ListWindow (mylist): > > > Daniel Nice solution. Thanks. John Roth > > From brobbins333 at shaw.ca Sat Mar 9 18:41:17 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Sat, 09 Mar 2002 23:41:17 GMT Subject: round() function strange behaviour References: <3c8a9261.149508269@news> <3C8A972E.8517ABEF@mega-nerd.com> Message-ID: <3c8a9c23.152007063@news> I understand the problem of rounding errors with binary numbers. However, the rounding functions of other languages work around it and return a usable result. What have they got that Python hasn't got? BR ps -- your name is very familiar. i think i've read one of your books. On Sat, 09 Mar 2002 23:13:50 GMT, Erik de Castro Lopo wrote: >brobbins333 at shaw.ca wrote: >> >> the round() function will sometimes return a predictable result, as >> in: >> >> round(45.67891, 2) >> >>> 45.68 >> >> but sometimes it will return something like: >> >> round(56.78923, 2) >> >>> 56.789999999999999 >> >> 2.1 and 2.2 both behave this way on two different (Windows) computers. >> What's going on here? > > >What you will fins is that some numbers like 2, 0.25 etc can be >represented exactly in floating point format while others like >2/3 cannot. > >Thats just the way it is. > >Erik >-- >+-----------------------------------------------------------+ > Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid) >+-----------------------------------------------------------+ >BSD: A psychoactive drug, popular in the 80s, probably developed at UC >Berkeley or thereabouts. Similar in many ways to the prescription-only >medication called "System V", but infinitely more useful. (Or, at least, >more fun.) The full chemical name is "Berkeley Standard Distribution". From d_blade8 at hotmail.com Wed Mar 27 18:54:58 2002 From: d_blade8 at hotmail.com (Lemniscate) Date: 27 Mar 2002 15:54:58 -0800 Subject: Python & Poetry References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> Message-ID: <7396d2b2.0203271554.5a564e1b@posting.google.com> FYI, this is a very interesting topic to me, so this post is a bit on the long side with little-to-no technical aspect. Geoff Gerrietts wrote in message news:... > Quoting Gon?lo Rodrigues (op73418 at mail.telepac.pt): > > On Tue, 26 Mar 2002 20:04:50 -0800, Geoff Gerrietts > > wrote: > > > > >Quoting Courageous (jkraska at san.rr.com): > > >> > > >> >I'd say the skills required to write clear, readable > > >> >software and clear, readable novels are not entirely > > >> >disjoint! I agree, but with a slightly different twist. There is a skill in writing prose, just as there is a skill in writing poetry and they do not always seem to go hand in hand (many great poets could not be even lackluster prose writers and this_statement.reverse() ). However, there is basic skill that both emcompass and that is the skill of conveying an idea. A truly obscure and obfuscated story or poem isn't really interesting unless the reader can identify with the idea in some way. Incidently, this is related to why, historically, some poets looked down at prose as a mode of expression (poets, they argued, convey ideas, thought, emotion while prose writers had to be concerned with conveying the plot). It's all about what ideas we are trying to convey... > > Poetry and coding are similar in that they are both creative activities > > needing inteligence, imagination, etc. But there is also a world of > > difference between the two. A simple way to see this is how they relate > > to their heritage, their common dead. In our case, coding is conveying an idea of a behavior to the computer. Once again, the conveyance of an idea is the main objective. Now, just as any writer will tell you, you convey your point best when you use the least amount of information required. I agree very much with this point; it is very much like the performance art of magic, my other paid 'hobby' (I've previously seen a thread on "Is magic poetry?" so I don't want to rehash it here, but I do have a point). The method of conveying an idea is at least as important as the idea itself; any decent magician will tell you that poor showmanship by the magician can kill the best trick in the world even if the trick itself was performed flawlessly. The same can be said of coding. There are various old thereoms and ideas about short code using less memory and being faster and the like (I'm just using this an example, I am not making the argument one way or the other). But the fact remains that the quicker and cleaner that one can communicate the idea they want to the computer, the quicker the computer may respond (please note: the response phase is omitted in this statement, I am merely referring to the time until the computer can begin its response) > Writing code is a lot like writing a poem, with a vocabulary that is > extremely restricted and formal requirements that are invariably > rigid. The sense of meaning one derives from a program is generally > more pragmatic than what one gets from a poem. But both are > appreciated as much for what they say as for how they say it. Excellent point. If we all remember back to learning about poetry and the Bard's use if iambic pentameter (let us assume, for now, that WS did all his own writing), we will recall how strict poetry can be. A haiku is another great example. One must be both a linguist and a puzzle-teer (what do you call somebody who does a lot of puzzles?). Writing code is the same way. There is a python book, I seem to think it is "Python Annotated Code" (or something like that), that has the code for determining if a number is a prime. Let us say the number is x. It takes the approach of dividing the number by every number x/2 and below (except for 1) and checking for a remainder (no remainder means the number is evenly divisible, thus not prime). This code works, but could be made to run much faster by using math.sqrt(x) instead of x/2 as the first number (this is a mathematical property of numbers, a number that has multiple larger than its square root has one that is smaller [e.g. 100 has 50 and 2, 25 and 4, 20 and 5]. Additionally, one could start at 2 and increment up to the square root (another property of numbers, more numbers are divisible by 2 than by 3 in a sequential series of at least four numbers; this will reduce the amount of time needed to find more numbers). When I saw the alternative way to compute primes (I saw the x/2 method first, somewhere else long ago), I thought that here was a perfect example of how code could be poetic. It made me understand what was meant by the term 'elegant' code. > One notable difference between programming and poetry is that a > programming cliche is acceptable, a rote that people are encouraged to > re-use, whereas dropping someone else's clever turn of phrase into > your poem is likely to backfire. As mentioned before, this can be the same argument used for why code is not the same as prose (you aren't supposed to plagarize). However, coding styles can be likened to poetic styles (the aforementioned haiku or iambic pentameter). One could also make the argument (and I am NOT) that the use of symbols in poetry is equivalent to the reuse of code in coding. One takes advantage of something that is already there and draws further information to or from it (see how this works whether one is talking about modules or an albatross necklace?). > > I'm still a long way from a thesis, but I think the similarities are > pretty astounding. > > Maybe that thesis isn't so many years off, after all.... > > --G. Very nice and thought-provoking D From hfoffani at yahoo.com Fri Mar 22 11:52:39 2002 From: hfoffani at yahoo.com (Hernan M. Foffani) Date: Fri, 22 Mar 2002 17:52:39 +0100 Subject: "Zope-certified Python Engineers" [was: Java and Python] References: Message-ID: <20020322115241.429$rK@news.newsreader.com> "Steven Majewski" escribi? > > > On 21 Mar 2002, Cameron Laird wrote: > > > So, for example, I've heard that Python isn't as serious > > as Java because it's not possible to hire "Zope-certified > > Python Engineers". Sun does that for Java, Zope doesn't > > for Python, therefore Python isn't as trustworthy as > > Java. > > In the light of earlier discussion on this thread, here's my suggestion: > > Rather than just giving another test, let someone pull out a significant > non-trivial task from the Python "to-do" list for each applicant for > certification. After review of satisfactory completeion of 3 tasks in > different categories, you get certified. Review might include having > to write up something on why you did it that way, or some other > explaination -- basically an essay question. Some organization > ( Zope? PSA? Python.org ? ) will have to be responsible for final review > and approval, but largely it will be through "community review" -- i.e. > submitting to SourceForge, posting to mailing-list/newsgroup for > discussion, etc. -- although perhaps a little more formalized, like > the PEP procedure. ( Or maybe this begs for a Slashdot like system to > distribute the review, grading and selection of projects. ) We already have a sort of Python certification program. And with several layers of qualifications. ;-) - Python Devs with commit permission. - Other Python Devs - Known c.l.py contributors - Authors of modules, recipes, etc. I know this is not a formal procedure (see the smiley.) But for hiring programmers, wouldn't be better if the applicant can show off (pun intended) his/her previous work? If Python skills "certificated" through public collaboration develops as a our common practice, the community would benefit a lot. And we honor Python Open Source spirit. Regards, -Hernan From mxp at dynalabs.de Tue Mar 5 15:13:19 2002 From: mxp at dynalabs.de (Michael Piotrowski) Date: Tue, 05 Mar 2002 21:13:19 +0100 Subject: HP-UX 10.2 deprecated? References: <1015292901.342132@cswreg.cos.agilent.com> Message-ID: martin at v.loewis.de (Martin v. Loewis) writes: > weeks at vitus.scs.agilent.com (Greg Weeks) writes: > >> Is HP-UX 10.2 deprecated for more recent versions of Python? > > Not specifically. HP-UX is deprecated :-) Seriously, it is only as > good on any platform as Python users care about it being. None of the > regular Python contributors has access to HP-UX, so any problem > reported and any patch suggested is hearsay. Unfortunately, the > patches often tend to break things on systems that the patch authors > have no access to. Sometimes, patches must be rejected because they > *obviously* break things on other systems, so the problem that the > patch submitter wanted to fix remains unfixed. I was able to get some HP-UX related fixes into 2.2, but there are still some open problems on HP-UX (somewhere on SourceForge), for which I lacked the time for further investigation. I'm not currently using Python, but I'd nevertheless offer to cooperate with anybody interested in better support for HP-UX (10.20 and 11)--I'm just not motivated enough to do it alone. >> PS: Here's the problem with the Python 2.2 ./configure for HP-UX 10.2. To >> determine if _POSIX_THREADS is defined in unistd.h, it runs the C >> preprocessor on a file with the contents: >> >> #include >> #ifdef _POSIX_THREADS >> yes >> #endif >> >> Unfortunately, with the C preprocessor invocation used by ./configure, the >> indented #ifdef is not recognized, which results in the #ifdef construct >> being mindlessly echoed, which is erroneously interpreted as the answer >> "yes". This causes _POSIX_THREADS to not be defined in pyconfig.h, >> resulting in a bunch of undefined thread-related functions at link time. > > What C compiler? I doubt that aCC (which is available for 10.20 as > well) has this problem; do not use the bundled C compiler for anything. aCC is the C++ compiler; the unbundled ANSI C compiler is cc. But since the OP was able to compile Python, I doubt he used the bundled compiler--you wouldn't get that far with a K&R compiler, I think. My guess is that, like this problem, most problems on HP-UX are in configure. 10.20 and threads is, ahem, a bit problematic; the DCE threads are _not_ POSIX threads. -- Michael Piotrowski, M.A. From ken at ineffable.com Thu Mar 7 17:51:38 2002 From: ken at ineffable.com (Ken Causey) Date: 07 Mar 2002 16:51:38 -0600 Subject: Problem with cgitb In-Reply-To: <15495.58404.946778.996505@beluga.mojam.com> References: <1015532454.1203.4.camel@temp> <15495.58404.946778.996505@beluga.mojam.com> Message-ID: <1015541499.1203.12.camel@temp> On Thu, 2002-03-07 at 16:05, Skip Montanaro wrote: > > Ken> While trying to work out an appropriate fix for my problems with > Ken> sgmllib I decided to try Python2.2, at which point I could start > Ken> using cgitb. Unfortunately cgitb has a problem when some of the > Ken> data it outputs includes HTML, since it does not escape the > Ken> appropriate bits and so the browser gets very upset. > > Can you post a bit of the fractured HTML it generates? If you think it's > truly a bug and not just an issue that cgitb can't recover because of > earlier generated HTML fragments, you should file a bug report on > SourceForge. > > -- > Skip Montanaro (skip at pobox.com - http://www.mojam.com/) > I'm reluctant to send attachments to the list, and I'm not sure the problem is clear unless you see a complete example. If anyone would like to see an example I will happily email you a 5K tarball with an example, just send me some email. Ken From usenet at thinkspot.net Tue Mar 12 19:25:31 2002 From: usenet at thinkspot.net (Sheila King) Date: Tue, 12 Mar 2002 16:25:31 -0800 Subject: frustrated stupid newbie question References: <8B012C611E@kserver.org> Message-ID: [posted and mailed] On Tue, 12 Mar 2002 17:59:54 -0600, "Scott Kurland" wrote in comp.lang.python in article : > > > Why isn't this $%^*#$% program working? > > > > > #Searching for perfect numbers > > > > > > howhigh= input ("How high should I check?") > > > for number in range (1,howhigh): > > > factorsum = 0 > > > halfnumber=number/2 > > > for checking in range (1,halfnumber): > > > if number/checking == int (number/checking): > > > factorsum = factorsum + checking > > > if number == factorsum: > > > print number > > > > > > > What do you mean it isn't working? It ran without crashing when I tried > it. > > Here is the output from a sample run: > > > > >>> > > How high should I check?50 > > 10 > > > > Are you expecting some other type of output? What are you expecting? > > Well, I was expecting failure, which we got. What I hoped for was the two > perfect numbers between 1 and 50, 6 and 28. You really should play with the interpreter window open, or add more print statements to your code so that you can see what is happening at all of the intermediate steps. Consider the data in this interactive session: >>> howhigh = 10 >>> range(1,howhigh) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, howhigh + 1) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> for number in range(1, howhigh + 1): print "for number = ", number, print "halfnumber = ", number/2 for number = 1 halfnumber = 0 for number = 2 halfnumber = 1 for number = 3 halfnumber = 1 for number = 4 halfnumber = 2 for number = 5 halfnumber = 2 for number = 6 halfnumber = 3 for number = 7 halfnumber = 3 for number = 8 halfnumber = 4 for number = 9 halfnumber = 4 for number = 10 halfnumber = 5 >>> Is this what you expect of the data in the intermediate steps? > > > Flame away, I can't feel dumber than this. > > > > Oh, now what newsgroup mistreated you so, that you would expect such a > > thing? We don't do that here in comp.lang.python! > Goodness! I'll have to mind my manners carefully, then; usenet has roughened > them some. > > Thank you, Sheila. Are you saying, that we need to watch out for flames from you??? Oh, dear! (donning my asbestos suit...) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From mwh at python.net Fri Mar 8 12:06:57 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 8 Mar 2002 17:06:57 GMT Subject: Where is quote (again)? References: <1f5252d4.0203080721.3bfc5c14@posting.google.com> <3C88E7B4.A910D281@earthlink.net> Message-ID: Hans Nowak writes: > It would be interesting to have lazy evaluation though... > I'm not sure if it's possible to implement, or if it will be > useful at all. It sure makes sense in functional languages, > but in Python? Hm. > The combination of lazy evaluation and non-functional semantics are only good for creating confusion. functional non-functional strict ml python lazy haskell brrr Cheers, M. -- All programs evolve until they can send email. -- Richard Letts Except Microsoft Exchange. -- Art -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From tejarex at yahoo.com Sat Mar 23 10:35:50 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Sat, 23 Mar 2002 15:35:50 GMT Subject: simple question References: <2UVm8.30655$J54.1855090@news1.west.cox.net> Message-ID: "Christopher Palmer" wrote in message news:mailman.1016868517.25439.python-list at python.org... > Let's say I have a variable called a Actually, you have a name 'a'. > and a contains an integer, say 4522 and the name is bound to an int, conventionally written 4522. > and I want 4, 5, 2, and 2 to be items in a list instead of an integer... Do you want the list to contain 4 ints (answer given by Johann as: map(int, str(a)) ) or 4 digits: ''.split(str(a)) ? Terry J. Reedy From shalehperry at attbi.com Tue Mar 26 11:07:09 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 26 Mar 2002 08:07:09 -0800 (PST) Subject: reduce vs. for loop In-Reply-To: <20020326072936.GA12343@matijek> Message-ID: On 26-Mar-2002 m2 at plusseven.com wrote: > > Just out curiosity, > why is fact2 a bit faster than fact1? > > def fact1(n): > return reduce (operator.mul, range(1L,n + 1)) > > def fact2(n): > result = n * 1L > for i in range(1 , n): > result *= i > return result > bigger problem here. fact2 returns a long, fact1 returns an integer. So fact1(100) fails. From kragen at pobox.com Tue Mar 19 02:43:08 2002 From: kragen at pobox.com (Kragen Sitaker) Date: 19 Mar 2002 02:43:08 -0500 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <_kqk8.25881$N7.5410299@ruti.visi.com> Message-ID: <83elihknoz.fsf@panacea.canonical.org> David Bolen writes: > In more concrete terms (and more to the context of this thread), it > provides perhaps a cleaner approach to interrupting the blocked > select. With select you might try to forceably interrupt the select > by closing the socket, or sending fake data to another (or the same) > socket, or having a fairly quick timeout and check for a flag. Or use a signal. In Unix, nearly everything (with the exceptions of SysV IPC message queues and semaphores and child process status changes) that can generate events are already file descriptors; if you're communicating with another cooperating process, you're probably already doing it with a file descriptor, so it fits into select() neatly. Signals fit into this rather poorly, but they do interrupt select() and cause the appropriate handler to run, which is generally what you need. > But all of those approaches are really ways to try to work around > the fact that select only works on I/O operations to file handles. > With Win32 native functions, I'd just define an extra event object, > and wait on that event object along with the event objects related > to the sockets. To shut it down, just signal the special event > object. Consider the following: But all of those approaches are really ways to try to work around the fact that WaitForMultipleObjects (sp?) only works on signaling of event objects. With Unix native functions, I'd just define an extra file descriptor, and wait on that file descriptor along with the file descriptors related to the sockets. To shut it down, just signal the special file descriptor. I think the difference is just in how you look at things. > It's interesting that all of these approaches do have one thing in > common - they tend not to be portable. Does Winsock not have socketpair()? My Win32 API references are all in another state. From gerhard at bigfoot.de Thu Mar 21 00:35:11 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 21 Mar 2002 06:35:11 +0100 Subject: sys.path append problem In-Reply-To: References: Message-ID: <20020321053511.GB4522@lilith.hqd-internal> * hejduk [2002-03-20 21:08 -0800]: > I've recently installed python 2.2.1 on my slak 8.0 linux computer. I > want to do some gui programming with wxPython, but in order to do that > I have to change the module search path (sys.path) to include the > wxPython module. I've tried the following: > > import sys > sys.append('/some/new/dir') > > This works, but when i shut Python down and restart it the Path has > been reset to the default, meaning that it is impossible to run > scripts that attempt to import modules from outside of this default > path. That's the way it's supposed to be. If you want to append to sys.path for all programs that you start, you must either set the PYTHONPATH environment variable, or, preferrably, put a sitecustomize.py file somewhere in your PYTHONPATH or into one of the directories of sys.path. Alternatively, you can create a .pth file in the site-packages directory. > When I used python on windoze the sys.path saved when I appended to > it, so I'm assuming that this is what is suppossed to happen. Really? That would be news to me. > I realize that there are several work arounds to this problem, but I > would prefer to correct it rather than cheat around it, because it > could be just a symptom of a larger problem. > > Anyone know what the problem is? You didn't install wxPython with "python setup.py install", did you? It will then be installed into the site-packages directory and you don't need to do customize anything. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From nospam at bigfoot.com Wed Mar 20 09:31:13 2002 From: nospam at bigfoot.com (Gillou) Date: Wed, 20 Mar 2002 15:31:13 +0100 Subject: Process to process synchronization (unix) References: <83pu20ieob.fsf@panacea.canonical.org> Message-ID: It would be a good idea but both programs must run in an asynchronous manner (fire and forget) because the "client" program is a Web server (Zope) and the "server" program may process data for some minutes. In addition "popen" runs the program for the same user/group as the client program (nobody/nogroup) an I need additional privileges to run the server program. I think that named pipes or exchanging sync through the database is the best solution. I need to learn those named pipes. Are there pythonic examples somewhere ? TIA --Gilles > > Why don't you use os.popen("otherprogram", "w") from Zope to start the > other program, then write to the pipe whenever there is data > available? > > Maybe that's not possible because of the way the other program starts > and you have to use named pipes or sockets. But this would be simpler > if it is possible. > From anthony at ekit-inc.com Wed Mar 6 19:48:29 2002 From: anthony at ekit-inc.com (Anthony Baxter) Date: Thu, 07 Mar 2002 11:48:29 +1100 Subject: HP-UX 10.2 deprecated? In-Reply-To: Message from weeks@vitus.scs.agilent.com (Greg Weeks) of "Wed, 06 Mar 2002 18:14:29 -0000." <1015438469.628881@cswreg.cos.agilent.com> Message-ID: <200203070048.g270mTc07900@burswood.off.ekorp.com> >>> Greg Weeks wrote > With this, "make" does indeed create an executable. But "make test" fails > both times on test_threads, dying at the end with: > > test_thread > *** Termination signal 14 > > Stop. > > Oddly enough, signal 14 (ALRM) is ignored the first time "test_thead" is > listed. And now you enter the cycle of pain... Getting threading working on HP/UX appears to depend on a) The HP/UX major and minor version b) The compiler and version c) Wierd and mysterious compile options that vary with a) and b) d) The phase of the moon. This has come up many times in the past - what is needed is for someone with deep HP/UX knowledge and exposure to a bunch of different HP/UX versions to volunteer to fix it. If HP offered something like Compaq's TestDrive machines, or donated some boxes to the sourceforge compile farm, someone might be able to look at it. At the moment, there's no-one who's stepped forward to fix this. Anthony -- Anthony Baxter It's never to late to have a happy childhood. From uwe at rocksport.de Mon Mar 25 13:57:49 2002 From: uwe at rocksport.de (Uwe Schmitt) Date: 25 Mar 2002 18:57:49 GMT Subject: Random... References: Message-ID: FREDRIK HULDTGREN wrote: | I want to generate random numbers, very large random numbers. If I use | randrange() I get an out of bounds error since it only supports numbers | up to (2**31)-1. However, I can use uniform(), but then I get the number | returned in 7.9655120654553743e+018 or something simaler, and I would | rather have it in a "L" format(796551206545537430183218312890381031L). | How do I do this? | thanx | /Fredrik You could generate two random numbers and clue them together to a longer number. there is a mp (multip precision) library at http://gmpy.sourceforge.net Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Uwe.Schmitt at num.uni-sb.de Universitaet des Saarlandes Angewandte Mathematik Building 36.1 Room 4.17 PO-Box 151150 D-66041 Saarbruecken Mobile:0177/6806587 Fax:+49(0)681/302-4435 Office:+49(0)681/302-2468 From huaiyu at gauss.almadan.ibm.com Tue Mar 5 15:46:03 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 5 Mar 2002 20:46:03 +0000 (UTC) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: <7xbse3j3u4.fsf@ruckus.brouhaha.com> <7xwuwqn6ch.fsf@ruckus.brouhaha.com> Message-ID: On 05 Mar 2002 11:48:46 -0800, Paul Rubin wrote: >> 5. How is 1e200**2 handled? >> >> Since both 1e-200**2 and 1e200**2 produce the same errno all the time, >> but Python still raises OverflowError for 1e200**2 when linked with >> -lieee, there must be a separate mechanism at work. What is that and how >> can I override it? I know this is by design, but I think the design is >> dumb (to put it politely). > >What do you want it to do? return inf. Huaiyu From bobnotbob at byu.edu Wed Mar 13 18:22:14 2002 From: bobnotbob at byu.edu (Bob Roberts) Date: 13 Mar 2002 15:22:14 -0800 Subject: data persistent from run Message-ID: What is the best way to keep data like window size and position for the next time I run the program? I know in win2k, stuff like that is usually stored in the registry. Are there any python commands to store such information in a platform-independent manner? From BPettersen at NAREX.com Thu Mar 7 11:31:18 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 7 Mar 2002 09:31:18 -0700 Subject: Status of PEP's? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192215154@admin56.narex.com> > From: Alan Daniels [mailto:daniels at mindspring.com] > > Michael Chermside wrote in message > news:... > > The objection you quoted was from me originally, so I feel > compelled to respond to it here. > [snip] > > There's still some MAJOR problems I see with PEP 276: > > 1) Right now, we have complete orthogonality between "for" > and "if". "for i in seq:" will be called for each value where > "if i in seq:" is true. Adding "for i in 5" destroys this. This surely doesn't have to be true. The for loop implicitly calls iter(seq) to get an iterator, and the if statement first tries to call __contains__ when faced with an 'in' test. It's trivial to implement a __contains__ method for type int that preserves the orthogonality. You're right though that the PEP should probably say whether it also proposes to implement __contains__ for type int. -- bjorn From huaiyu at gauss.almadan.ibm.com Wed Mar 13 19:18:13 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Thu, 14 Mar 2002 00:18:13 +0000 (UTC) Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: On Wed, 13 Mar 2002 22:39:02 GMT, Terry Reedy wrote: >> >> [Clark C . Evans] >> | Very nice idea. This is PEP worthy. It is nice beacuse it >> | does not introduce anything new; a list can easily be viewed >> | as a mapping having a positive integer domain. This is simple, >> | consistent, and quite elegant. >> >> I would like to see: >> .keys() >> .items() >> .iterkeys() >> .iteritems() > >I like this idea too. Best suggestion so far for replacing >range(len(skjf))./ Question: Which is better: items(x) or x.items()? I think items(x) can just piggy-back on the current iterator protocol, and can be made to work on any iteratable objects. On the other hand, x.items() has to be implemented by each and every list-like classes. Their subclasses need to override them whenever necessary. So else being equal, I'd prefer items(x) to x.items(). Question: Which is better name: keys or indices? items or indexed? I think the latter two (indices, indexed) are more descriptive of sequence types. This is especially true if one ever want to use a seqdict type. Question: Which name is better: iterkeys or xkeys? I thought the general trend is that x- prefix is going to be used for iterators. Then I found out that xrange(3) is not an iterator by itself. And {} has iteritems, iterkeys, itervalues, instead of the x- variety. So, suppose we'll have an xzip eventually, will it be called iterzip? Huaiyu From eppstein at ics.uci.edu Tue Mar 12 01:25:46 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 11 Mar 2002 22:25:46 -0800 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> <3C8C02B3.674898B0@engcorp.com> <3C8C0460.993A4F81@engcorp.com> <3C8D9956.5920AA52@engcorp.com> Message-ID: In article <3C8D9956.5920AA52 at engcorp.com>, Peter Hansen wrote: > Resulting in a grand total Crackpot Index of about 3471, surely > an all-time record. I guess you haven't seen some of the more persistent math and physics crackpots. This guy came, didn't get a lot of support, and went quickly, without destroying the newsgroup for months or years. Much less of a waste of bits... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From martin at v.loewis.de Mon Mar 18 17:00:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Mar 2002 23:00:45 +0100 Subject: XML help References: Message-ID: Vincent Foley writes: > I have a XML document . > I want to put the latest_version value in a variable. How would I do > that? The following should work fine from xml.sax import make_parser, ContentHandler class find_latest_version(ContentHandler): def __init__(self): self.in_latest_version = 0 def startElement(self, name, attrs): if name == 'latest_version': self.in_latest_version = 1 self.data = "" def endElement(self, name): if self.in_latest_version: self.in_latest_version = 0 def characters(self, data): if self.in_latest_version: self.data += data c = find_latest_version() p = make_parser() p.setFeature("http://xml.org/sax/features/namespaces", 0) p.setContentHandler(c) p.parse("vim.xml") print c.data HTH, Martin From dortmann at lsil.com Mon Mar 11 10:46:16 2002 From: dortmann at lsil.com (Daniel Ortmann) Date: 11 Mar 2002 09:46:16 -0600 Subject: python name spaces References: <3C8C45F2.E0F6D9EC@earthlink.net> Message-ID: Hans Nowak writes: > Daniel Ortmann wrote: > > I must admit I am frustrated by Python's seeming lack of powerful > > name space support. For example, in Perl I can do something like > > this, > > our $b = "...b"; > > > > { > > my $a = "...a"; > > our $f = sub { print $a, "\n" }; > > our $g = sub { $a = "foo" } > > } > > > > $f->() > > $g->() > > > > # prints ...a, followed by foo. > > # the "$a" variable is ONLY seen by the unnamed $f and $g > > # subroutines. > I don't know much about Perl, but this seems a bit like a closure like > Lisp and Scheme have them. Yes! (I was avoiding buzzwords.:-) > Python namespaces don't work like this. If you want a variable to be > only visible by a few functions, and shared by those functions, the > Pythonic solution would be, writing a class. But must I _name_ everything? What if I want to build a closure, apply it several times locally, and then throw it away? Am I correct that Python "lambda"s, in name only, resemble Scheme lambdas? (I posted since I saw no PEP addressing these issues.) -- Daniel Ortmann, LSI Logic 3425 40th Av NW, Suite 200, Rochester, MN 55901 dortmann at lsil.com / 507.529.3887 (w) / 535.3887 (int) ortmann at isl.net / 507.288.7732 (h) From eppstein at ics.uci.edu Wed Mar 6 20:57:57 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 17:57:57 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , Steve Lamb wrote: > On Wed, 06 Mar 2002 16:57:03 -0800, David Eppstein > wrote: > > I think you have made my point for me, that range is hard to use > > correctly. Did you try running range(n-1,0)? What list did it give you? > > >>> range(-10,0) > >>> [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1] I started with a positive number n, and claimed that it was hard to create and understand expressions such as range(n-1,-1,-1). You said that if that was so hard, I should instead simply create range(n-1,0) and reverse it. range(n-1,0) is empty when n is positive. You should have told me to reverse range(n). So, clearly, you did not understand the expression range(n-1,-1,-1), contradicting your claim that range is easy to understand. And of course, this only helps when you want the reversal of a half-open interval, it still does nothing about the understandability of closed or open intervals. > And? How does this prove your point other than some minor nit I'm sure > you're going to pick? Point stands, there are other ways of doing it. I agree, there are already ways to do it. There are already ways to do everything you might ever want to do in Python, because like most sensible languages it's Turing-complete. So should we stop trying to improve the language? My point is that the ways that exist now are either cumbersome (create a range then reverse it then loop over the reversed range, use a while loop instead of a for loop) or difficult to program correctly and difficult to understand once programmed (multi-parameter range), and that the proposed syntax gives a simple easy-to-understand alternative. Anyway, according to it's not a problem if there's more than one way of doing things, but there should preferably one obvious way. This proposal would give one obvious way of doing most integer loops. > While I've got your attention, let me ask you this. In your notation how > would you do the following? > > for x in range(n-1,-1,-2): > > That, unlike the allusion you made above, is not a nit. Stops to think... range starts with n-1 ... can't understand the second argument before I see the third ... steps downward so starting with n-1 should be interpreted as all numbers less than n rather than all numbers greater than n-2 ... step size is 2 ... now we can go back to the second argument, we stop before we get to -1, which with a step size of 2 means we stop either at 0 or 1. Ok, what you want is almost like for n > x >= 0 but you want to skip every second value. That's not covered by the current proposal. It's supposed to be an improvement, not a panacea -- now is a good time for another Tim-quote "now is better than never", which is what we'll get if we wait for a perfect solution to all our problems. It's hard to tell without some context (and I'm not convinced a context exists in which this is the loop you want), but if I had to write this loop, without further information on where n came from or whether it's odd or even, I'd probably skip the range() and go for: x = n - 1 while x >= 0: ...loop body... x -= 2 of course, that requires more care about not continuing from the middle of the loop, and you have to look multiple places to even figure out that it's a loop over a progression of integers, but even so I think it's preferable to range(n-1,-1,-2). Another possibility, depending on *why* you want to skip every second value, is: for n > x >= 0: if x & 1 != n & 1: ...loop body... which could likely be simplified if we know the parity of n in advance. From martin at v.loewis.de Thu Mar 21 01:06:55 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Mar 2002 07:06:55 +0100 Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: mlh at vier.idi.ntnu.no (Magnus Lie Hetland) writes: > Hm. I just tried freeze (with a simple 'print "Hello, world"') script > and it failed miserably "Fail miserably" is not a very precise description if you expected that somebody improves freeze - so I conclude you are not really interested in seeing freeze improved. > I guess not. There is always the hope that if one gripes about > something someone else will be inspired to do something about it ;) This is only one aspect of how free software works. Another is that enough users of some package contribute enhancements. If *all* users just gripe, development stalls. Regards, Martin From l0819m0v0smfm001 at sneakemail.com Fri Mar 15 15:49:57 2002 From: l0819m0v0smfm001 at sneakemail.com (Joshua Macy) Date: Fri, 15 Mar 2002 20:49:57 GMT Subject: unittest.py: what is TestResult.__repr__ ? References: <332433e4.0203151141.1e7d92d7@posting.google.com> Message-ID: <3C9224EA.4030201@sneakemail.com> Richard Harlos wrote: > I'm not a Python programmer (at least, not yet ;) > > I am, however, trying to port the unittest.py framework to another > language. Of all the languages that this testing framework has been > ported to, I thought that Python would be the easiest for me to > decipher. For the most part, it seems pretty straightforward, except > for... > > I'm presently stuck in the TestResult class. Though I've searched for > the meaning of "__repr__" in the Python22 documentation, I cannot find > it. > > Please help me understand this this convention of using leading and/or > trailing underscores in Python. > > Thanks in advance... > > Richard > Check the documentation under special method names: http://www.python.org/doc/current/ref/specialnames.html Basically, any method name that both begins and ends with a double-underscore is a way for your own class to define behavior that happens when certain syntax is used, e.g. if you define an __add__ method, that method is called when an object of your class is discovered to the left of a + sign in an expression. The __repr__ special method is used to define a string representation of the object; it is called when someone invokes repr() on your object, or by backticks, e.g. `myObj`, or when you type the object name and nothing else at the interactive prompt. It's supposed to return a string that can be eval-ed to recreate the object (if possible) or a simple description like '' E.g. >>> class Test: ... def __init__(self, value): ... self.value = value ... def __repr__(self): ... return 'Test(%s)' % self.value ... >>> t = Test(1) >>> t Test(1) >>> repr(t) 'Test(1)' >>> `t` 'Test(1)' >>> t2 = eval(repr(t)) >>> t2 Test(1) Hope this helps, Joshua From flognat at flognat.myip.org Tue Mar 19 04:17:15 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Tue, 19 Mar 2002 09:17:15 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: | > p.s.2 what is the status on win9x? Give it up or ;-) | | More difficult as 9x doesn't have API support for retrieving the Unicode | names, so it could require reading the directory bytes directly. Maybe if I new the codepage used by the user, and use that to convert the 8bit string to unicode?? /Andy -- The eye of the beholder rests on the beauty! From tim-dated-1016292456.1fd5be at catseye.net Sat Mar 9 10:27:33 2002 From: tim-dated-1016292456.1fd5be at catseye.net (Tim Legant) Date: 09 Mar 2002 09:27:33 -0600 Subject: PEP 284, Integer for-loops In-Reply-To: References: Message-ID: <868z91bw2i.fsf@skitty.catseye.net> usenet at microtonal.co.uk (Graham Breed) writes: > Tim Legant wrote: > > > Out of curiosity I ran a couple of quick greps over the TMDA source. > > TMDA doesn't really fall into either of your "alternative" categories; > > it's small, but definitely not throwaway and it's an application, not > > a core library. It's a mail processor to eliminate SPAM. However, > > it's pure Python; there's no integration with C or Java. > > How small is small? I did a quick wc -l. We have 8 scripts calling upon 9 modules (in a package). The total line count is just over 4500, but since the usage docstring in each of the 8 scripts is fairly long, I'm going to guess that the real line count is closer to 3300. > I have a script at with > around 1490 lines (including comments and blank lines) and 35 uses > of range, some probably evil, most for for loops. Two warty > examples > > for n in range(1,n+1,2): > > and > > for element in range(firstIndex, maxBasis+1): > > where the +1 is used for inclusive boundaries. 7 straight > range(len(..))s. I think there's no question that range is sometimes needed, and that in certain cases it reads a little wonky! In your latter 7 cases I'd probably loop over the sequence and keep track of the index myself, but I don't think there's any clear reason for preferring one way over the other. > Well, I've stuck my head above the parapet. Have a look at the code, and > see if I'm expressing myself badly. It doesn't integrate with C, Java or > COM but does do a lot of work with integers. That's not something Python > excels at, but it's such a good language generally that it's still worth > using outside its niche. This is also a good point. Since TMDA processes text (email messages and filtering rules) we don't use integers much. I would imagine that, when your problem domain is numbers, you'd have to loop over them a great deal more. I think this is what David Eppstein has been discovering in his class, as well. Tim From warrierajit at hotmail.com Fri Mar 8 14:52:54 2002 From: warrierajit at hotmail.com (warrier) Date: 8 Mar 2002 11:52:54 -0800 Subject: is there a fully working tar implementation in python Message-ID: I need a fully working (read and write capability) tar implementation in python. Has one already been coded ? I did find some modules but each one had its limitations. From a.martin at perfectwww.de Tue Mar 12 11:37:27 2002 From: a.martin at perfectwww.de (Andreas Martin) Date: 12 Mar 2002 08:37:27 -0800 Subject: Ho to use a regular expression group reference as hash key References: Message-ID: Hi ! I would like to use html templates with my own tags, e.g. and to substitute with the entry hash["faxnumber"] that is to say the saved faxnumber. That's why I would like to substitute the matching by the hash entry and the key string should be referenced by \1 . Something like this: pat = re.compile(r'\') t = pat.sub(hash[\1],TemplateInput) The programm should only substitute my own tags. If I try to substitute every word then words I use as hash key would be substituted too but I don't want this. Thank you "Raymond Hettinger" wrote in message news:... > Maybe the % substitution operator will help. > > >>> person={"entry1":"value1","entry2":"value2"} > >>> target = 'A sample sentence with %(entry1)s and %(entry2)s' > >>> print target % person > A sample sentence with value1 and value2 > > Another method would be to attempt to substitute every word > and if the word is not is the hash replace it with itself. > > >>> import re > >>> target = 'A sample sentence with entry1 and entry2' > >>> person={"entry1":"value1","entry2":"value2"} > >>> re.sub( r'b\w+\b', lambda word: person.get(word,word), target ) > 'A sample sentence with entry1 and entry2' > > > Raymond Hettinger From skip at pobox.com Tue Mar 19 12:58:32 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 19 Mar 2002 11:58:32 -0600 Subject: Returning an element from a C struct In-Reply-To: <3C9772AB.1691D362@saic.com> References: <3C9772AB.1691D362@saic.com> Message-ID: <15511.31816.688155.867647@12-248-41-177.client.attbi.com> Brad> I'm trying to wrap a C structure in a Python class definition and Brad> have come upon this problem. Brad> class foo: Brad> __init__(self, dat): Brad> self.ptr = gnum_t(dat) Brad> __getattr__(self,name): Brad> try: Brad> return self.__dict__[name] Brad> except: Brad> if name == 'A': Brad> return self.__dict__['ptr'].A Brad> elif name == 'B': Brad> return self.__dict__['ptr'].B Brad> elif name == 'C': Brad> return self.__dict__['ptr'].C Brad> # And many others How about def __getattr__(self,name): try: return self.__dict__[name] except KeyError: return getattr(self.ptr, name) ? -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From philh at comuno.freeserve.co.uk Sun Mar 10 19:55:09 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 11 Mar 2002 00:55:09 +0000 Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> Message-ID: On Sun, 10 Mar 2002 15:29:37 -0500, Christopher Browne wrote: > >You might ask the "autocoding" guy if he'd be interested in adding >this as an alternative syntax for his scheme; it might well be more >readable than other options... Is he still posting here? (I killfiled him some time ago). -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From peter at engcorp.com Sat Mar 9 23:15:15 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 09 Mar 2002 23:15:15 -0500 Subject: Standalone Win32 wxPython apps? References: Message-ID: <3C8ADDD3.E3ACC1EB@engcorp.com> Grant Edwards wrote: > > I'm considering writing a wxWindows app for Win32. The only > way I'm willing to do this is by doing all of the development > under Unix, and then grit my teeth while I package up the final > product for Win32. Please tell us you are willing to bend a little and at least *test* under Win32 before you deliver it. Evidence from the Era of Java shows that nothing is write-once-run-anywhere... > Optimally, it would be a single "exe" file that doesn't require > any installation procedure. That's too much to ask for even a native Windows app in most cases these days. > If that's not possible, it would be permissible to use a > typical "isntall-wizard" type installation ... Great, you have several options available. > It looks like Gordon McMillan's installer might fit the bill. That's probably one. I haven't used it. > Anybody care to share any experiences distributing wxWindows > apps for Win32? py2exe will do everything you need except the installer part of the puzzle. But there are many installers available, including freebie versions of some of the better ones. Use py2exe and you'll get a directory with the Python DLL, the wxPython DLL, your EXE, and a few other DLLs as needed (e.g. the native regular expression stuff if you use it). Package and ship, easy as pie. (I've used PowerArc with its option to package into a self-extracting ZIP as a poor-man's version of an installer and it worked nicely.) -Peter From thoa0025 at mail.usyd.edu.au Fri Mar 22 04:04:54 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Fri, 22 Mar 2002 09:04:54 GMT Subject: does anyone have any idea? References: Message-ID: this is so urgent :( From skip at pobox.com Fri Mar 15 09:04:20 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 15 Mar 2002 08:04:20 -0600 Subject: psyco, jython, and python speed tests In-Reply-To: References: Message-ID: <15505.65380.457894.88916@12-248-41-177.client.attbi.com> Sandy> TEST RESULTS: Sandy> ------------ Sandy> (in decreasing order of performance) Sandy> psyco 0.4 (cpython22 running psycoized pystone) Sandy> Pystone(1.1) time for 1000000 passes = 16.1721 Sandy> This machine benchmarks at 61834.8 pystones/second ... How did you "psycoize pystone"? I found the best results when psyco.bind()ing Proc0, Proc1 and Proc8. I think it's important when documenting psyco speedups to indicate what steps you took since there are so many possibilities. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From eppstein at ics.uci.edu Wed Mar 6 11:41:31 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 08:41:31 -0800 Subject: PEP 284, Integer for-loops Message-ID: Abstract This PEP proposes to simplify iteration over intervals of integers, by extending the range of expressions allowed after a "for" keyword to allow three-way comparisons such as for lower <= var < upper: in place of the current for item in list: syntax. The resulting loop or list iteration will loop over all values of var that make the comparison true, starting from the left endpoint of the given interval. Rationale One of the most common uses of for-loops in Python is to iterate over an interval of integers. Python provides functions range() and xrange() to generate lists and iterators for such intervals, which work best for the most frequent case: half-open intervals increasing from zero. However, the range() syntax is more awkward for open or closed intervals, and lacks symmetry when reversing the order of iteration. In addition, the call to an unfamiliar function makes it difficult for newcomers to Python to understand code that uses range() or xrange(). The perceived lack of a natural, intuitive integer iteration syntax has led to heated debate on python-list, and spawned at least four PEPs before this one. PEP 204 [1] (rejected) proposed to re-use Python's slice syntax for integer ranges, leading to a terser syntax but not solving the readability problem of multi-argument range(). PEP 212 [2] (deferred) proposed several syntaxes for directly converting a list to a sequence of integer indices, in place of the current idiom range(len(list)) for such conversion, and PEP 281 [3] proposes to simplify the same idiom by allowing it to be written as range(list). PEP 276 [4] proposes to allow automatic conversion of integers to iterators, simplifying the most common half-open case but not addressing the complexities of other types of interval. Additional alternatives have been discussed on python-list. The solution described here is to allow a three-way comparison after a "for" keyword, both in the context of a for-loop and of a list comprehension: for lower <= var < upper: This would cause iteration over an interval of consecutive integers, beginning at the left bound in the comparison and ending at the right bound. The exact comparison operations used would determine whether the interval is open or closed at either end and whether the integers are considered in ascending or descending order. This syntax closely matches standard mathematical notation, so is likely to be more familiar to Python novices than the current range() syntax. Open and closed interval endpoints are equally easy to express, and the reversal of an integer interval can be formed simply by swapping the two endpoints and reversing the comparisons. In addition, the semantics of such a loop would closely resemble one way of interpreting the existing Python for-loops: for item in list iterates over exactly those values of item that cause the expression item in list to be true. Similarly, the new format for lower <= var < upper: would iterate over exactly those integer values of var that cause the expression lower <= var < upper to be true. Specification We propose to extend the syntax of a for statement, currently for_stmt: "for" target_list "in" expression_list ":" suite ["else" ":" suite] as described below: for_stmt: "for" for_test ":" suite ["else" ":" suite] for_test: target_list "in" expression_list | or_expr less_comp or_expr less_comp or_expr | or_expr greater_comp or_expr greater_comp or_expr less_comp: "<" | "<=" greater_comp: ">" | ">=" Similarly, we propose to extend the syntax of list comprehensions, currently list_for: "for" expression_list "in" testlist [list_iter] by replacing it with: list_for: "for" for_test [list_iter] In all cases the expression formed by for_test would be subject to the same precedence rules as comparisons in expressions. The two comp_operators in a for_test must be required to be both of similar types, unlike chained comparisons in expressions which do not have such a restriction. We refer to the two or_expr's occurring on the left and right sides of the for-loop syntax as the bounds of the loop, and the middle or_expr as the variable of the loop. When a for-loop using the new syntax is executed, the expressions for both bounds will be evaluated, and an iterator object created that iterates through all integers between the two bounds according to the comparison operations used. The iterator will begin with an integer equal or near to the left bound, and then step through the remaining integers with a step size of +1 or -1 if the comparison operation is in the set described by less_comp or greater_comp respectively. The execution will then proceed as if the expression had been for variable in iterator where "variable" refers to the variable of the loop and "iterator" refers to the iterator created for the given integer interval. The values taken by the loop variable in an integer for-loop may be either plain integers or long integers, according to the magnitude of the bounds. Both bounds of an integer for-loop must evaluate to a real numeric type (integer, long, or float). Any other value will cause the for-loop statement to raise a TypeError exception. Issues The following issues were raised in discussion of this and related proposals on the Python list. - Should the right bound be evaluated once, or every time through the loop? Clearly, it only makes sense to evaluate the left bound once. For reasons of consistency and efficiency, we have chosen the same convention for the right bound. - Although the new syntax considerably simplifies integer for-loops, list comprehensions using the new syntax are not as simple. We feel that this is appropriate since for-loops are more frequent than comprehensions. - The proposal does not allow access to integer iterator objects such as would be created by xrange. True, but we see this as a shortcoming in the general list-comprehension syntax, beyond the scope of this proposal. In addition, xrange() will still be available. - The proposal does not allow increments other than 1 and -1. More general arithmetic progressions would need to be created by range() or xrange(), or by a list comprehension syntax such as [2*x for 0 <= x <= 100] - The position of the loop variable in the middle of a three-way comparison is not as apparent as the variable in the present for item in list syntax, leading to a possible loss of readability. We feel that this loss is outweighed by the increase in readability from a natural integer iteration syntax. - To some extent, this PEP addresses the same issues as PEP 276 [4]. We feel that the two PEPs are not in conflict since PEP 276 is primarily concerned with half-open ranges starting in 0 (the easy case of range()) while this PEP is primarily concerned with simplifying all other cases. However, if this PEP is approved, its new simpler syntax for integer loops could to some extent reduce the motivation for PEP 276. - It is not clear whether it makes sense to allow floating point bounds for an integer loop: if a float represents an inexact value, how can it be used to determine an exact sequence of integers? On the other hand, disallowing float bounds would make it difficult to use floor() and ceiling() in integer for-loops, as it is difficult to use them now with range(). We have erred on the side of flexibility, but this may lead to some implementation difficulties in determining the smallest and largest integer values that would cause a given comparison to be true. - Should types other than int, long, and float be allowed as bounds? Another choice would be to convert all bounds to integers by int(), and allow as bounds anything that can be so converted instead of just floats. However, this would change the semantics: 0.3 <= x is not the same as int(0.3) <= x, and it would be confusing for a loop with 0.3 as lower bound to start at zero. Also, in general int(f) can be very far from f. Implementation An implementation is not available at this time. Implementation is not expected to pose any great difficulties: the new syntax could, if necessary, be recognized by parsing a general expression after each "for" keyword and testing whether the top level operation of the expression is "in" or a three-way comparison. The Python compiler would convert any instance of the new syntax into a loop over the items in a special iterator object. References [1] PEP 204, Range Literals http://www.python.org/peps/pep-0204.html [2] PEP 212, Loop Counter Iteration http://www.python.org/peps/pep-0212.html [3] PEP 281, Loop Counter Iteration with range and xrange http://www.python.org/peps/pep-0281.html [4] PEP 276, Simple Iterator for ints http://www.python.org/peps/pep-0276.html Copyright This document has been placed in the public domain. From i.linkweiler at gmx.de Sat Mar 9 09:17:54 2002 From: i.linkweiler at gmx.de (Ingo Linkweiler) Date: Sat, 09 Mar 2002 15:17:54 +0100 Subject: PyQT: shrinked Icons in menubar/QToolbutton Message-ID: <3C8A1992.EEFCBE00@gmx.de> Hi, i want to load images as icons for a toolbar. But the loaded images seem to be "shrinked" ~ 30%. Any ideas how I can avoid this? self.toolbar=QToolBar(self, "Datei Operationen") self.tool_open = QToolButton(QPixmap("./icons/runbig.png"), 'Run it', '', self.slotRun, self.toolbar, 'run it') From leader730 at hotmail.com Mon Mar 4 15:41:34 2002 From: leader730 at hotmail.com (Joseph Youssef) Date: Mon, 4 Mar 2002 15:41:34 -0500 Subject: Super newbie question D: Message-ID: how do I generate a random number in Python, I used to know but I forgot :'( -------------- next part -------------- An HTML attachment was scrubbed... URL: From eppstein at ics.uci.edu Wed Mar 6 21:08:30 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 18:08:30 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , "Delaney, Timothy" wrote: > "PEP 274 [4] proposes to make integers iterable by implementing __iter__, > simplifying ... > > I would also possibly add the discussion of what iter(-x) should mean i.e. > either counting up from -x to 0 (upper bound exclusive, matches slice > semantics), or counting down from 0 to -x (upper bound exclusive, useful for > traversing sequences in reverse order). You would add a summary of this discussion to PEP 284's description of PEP 274? I didn't want to get too detailed, just provide appropriate citations so readers could look up the relevant related proposals. From gcordova at hebmex.com Mon Mar 4 10:41:48 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Mon, 4 Mar 2002 09:41:48 -0600 Subject: ADO GetRows() example for newbies Message-ID: <19650FF08A99D511B19E00B0D0F06323060B31@SRM201002> > > sam_collett at lycos.co.uk (Sam Collett) wrote: > > >How could you do pages of records (in ASP for example), you may only > >want a few records at a time (if you have 1000 records for example)? > >For example I may want a page with 10 records per page, with the page > >numbers at the bottom. > >For 100 records: > >10 pages (10 links) > >Start at 1 on page 1, 11 on page 2 etc) > > Unfortunately, this varies from SQL provider to SQL provider. > In Postgres, for example, I can say: > > SELECT * FROM users ORDER BY lastname OFFSET 20 LIMIT 10; > > That fetches me records number 21 through 30. By changing the OFFSET > value, I change which subset I get. > > SQLServer uses a different syntax. I believe "TOP" is the SQLServer > equivalent of LIMIT, but I don't know how to do "OFFSET". > > Another alternative is to use a cursor, but again the > implementation vaires by backend. > And since the question is squarely in ASPs, I'd do the following: 1. Obtain ALL results into an array of arrays with: import win32com.client, cPickle RS = win32com.client.Dispatch("ADODB.Recordset") RS.Open("...query...", "...connection...") if not RS.EOF: # Fetch ALL rows and transform from it's "natural" form # [ (A_1, A_2, ...), (B_1, B_2, ...), ...] # into a more useful # [ (A_1, B_1, ...), (A_2, B_2, ...), ...] # and pickle into a string. all_rows = cPickle.dumps(zip(*RS.getrows())) # Make up a random filename. fname = make_a_random_filename_somehow() # And save locally on the server. open(Server.MapFilename(fname),"w").write(fname) # AND STORE THE FILENAME. Session("PickleName").Value = fname 2. When you're displaying the results, read the pickle and display from there: fname = str(Session("PickleName").Value) all_rows = cPickle.loads(open(fname).read()) 3. When you're done with the data, destroy the pickle file so it isn't left hanging around there: fname = str(Session("PickleName").Value) os.remove(fname) Session("PickleName").Value = None This helps, because you don't have to query every time you display the results page, and they're cached locally on a file which can be quickly read and displayed. #include Hope this helps. -gustavo From g_braad at survion.com Tue Mar 26 12:55:58 2002 From: g_braad at survion.com (Gerard Braad) Date: 26 Mar 2002 18:55:58 +0100 Subject: Python and the Parrot Message-ID: <1017165359.15705.4.camel@acropolis> Hello, i've been using Parrot since it's initial release and was impressed by it's performance... it's getting better and starting to be a whole lot more useful... i wanted to know if someone else here is using it... and? do you think python should be ported to the parrot vm??? or are you already programming (/porting/testing/etc) on it??? "will Python swallow the Parrot? or will the Parrot swallow Python???" for more information, see: //www.parrotcode.org/ or //dev.perl.org/ greets, Gerard From aahz at panix.com Mon Mar 4 19:29:28 2002 From: aahz at panix.com (Aahz Maruch) Date: 4 Mar 2002 16:29:28 -0800 Subject: Python standards References: Message-ID: In article , CSJedi wrote: > >Can someone tell me if Python has proprietary or consensus standards such as >ANSI? Our standard is Guido. -- --- Aahz <*> (Copyright 2002 by aahz at pobox.com) Hugs and backrubs -- I break Rule 6 http://www.rahul.net/aahz/ Androgynous poly kinky vanilla queer het Pythonista "How come we choose from just two people for President but more than 50 for Miss America?" --AEN From gopesh_sharma at yahoo.com Sun Mar 3 19:29:27 2002 From: gopesh_sharma at yahoo.com (gopesh_sharma) Date: Mon, 04 Mar 2002 00:29:27 -0000 Subject: Calling java servlets using python Message-ID: Dear All: Please let me know how to call java servlets using python? I need this help urgently. Thanks, Gopesh Sharma From martin at v.loewis.de Sat Mar 30 12:19:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Mar 2002 18:19:23 +0100 Subject: PEP 285: Adding a bool type References: <3CA5E2EA.1CADAF70@engcorp.com> Message-ID: Peter Hansen writes: > Are there code snippets which clearly have significantly improved > readability as a result of a rewrite using the proposed bool? The standard library has 110 occurrences of "return 0", 70 occurrences of "return 1", and 136 occurrences of "return None". Optimistically, this makes 300 functions. It would help users of these 300 functions if they would know whether those functions return a boolean or an integral value (if integral, what range?); for the "return None" cases, the boolean type would help to clarify whether this is "return no value", "return False", or "return nil object"; Regards, Martin From eppstein at ics.uci.edu Mon Mar 4 22:13:02 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 04 Mar 2002 19:13:02 -0800 Subject: Status of PEP's? References: Message-ID: In article , Fernando Perez wrote: > And by the way, as far as counting goes one could argue that 1..5 is > even more natural, as it truly spans the set of the natural numbers of which > 5 is a member, as opposed to the less 'standard' set of the 'non-negative > integers less than 5'. But that's a minor nit-pick. While we're picking minor nits, I would consider the natural numbers to include zero. From andrewm at object-craft.com.au Thu Mar 21 18:50:29 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Fri, 22 Mar 2002 10:50:29 +1100 Subject: Python embedded like PHP Message-ID: <20020321235029.B66B438F4C@coffee.object-craft.com.au> > > Albatross encourages (but doesn't enforce) the separation of presentation > > and logic. You might do something like this in Albatross: > > > >
      > > > >
    • > >
      > >
    > > Why, oh why, does it use HTML-like syntax? People keep implementing > templating languages that do this over and over, and it's a bad, bad > idea. Any moderately complex example of templating will violate the > rules of HTML/SGML, with things like ">, which is horrible to read, will anger WYSIWYG > editors to no end, and isn't at all necessary. The intention is that Albatross templates be valid XML - while Albatross will do the expected thing in the example you give above, it generally provides a "better" way, such as: > All you have to do is use [] instead of <> -- it look about the same, > will have all the good cognitive associations (how nesting works, > etc), but is orthogonal to HTML, just like your templating system is > orthogonal to HTML. I.e., you're templates would look like But this wouldn't be XML... 8-) -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From nas at python.ca Thu Mar 7 17:57:05 2002 From: nas at python.ca (Neil Schemenauer) Date: Thu, 7 Mar 2002 14:57:05 -0800 Subject: [OT] range() for unix shell In-Reply-To: <2adab837.0203071409.76588265@posting.google.com>; from bass@slinkp.com on Thu, Mar 07, 2002 at 02:09:31PM -0800 References: <2adab837.0203071409.76588265@posting.google.com> Message-ID: <20020307145705.A4605@glacier.arctrix.com> On my Linux machines: $ seq 5 1 2 3 4 5 $ seq 2 5 2 3 4 5 I don't know how standard seq though. It might only be part of GNU. Neil From greg at cosc.canterbury.ac.nz Sun Mar 24 21:35:51 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Mon, 25 Mar 2002 14:35:51 +1200 Subject: Reloading exception explained (Re: mutlifile inheritance problem simplified) References: <9896e047.0203211303.741f695a@posting.google.com> <3C9BAB77.B4E17C65@hotmail.com> Message-ID: <3C9E8D07.2FD89B05@cosc.canterbury.ac.nz> Marc wrote: > > "D:\PythonCode\pna\eyeTracking\tests\b01.py", line > 8, in __init__ > a01.a.__init__(self) > TypeError: unbound method must be called with > class instance 1st argument I can see what's happening here. It's because you're reloading some modules more than once. When you import b01, you reload a01, and then when you import c01, you relod a01 *again*. The result of this is that there are *two* classes "a" in existence. Class b inherits from the first one, created when you reloaded a01 for the first time, and class c inherits from the second one, created when you reloaded a01 for the second time. Now, when you come to do a01.a.__init__(self) in class b, you're dealing with an instance which has the *first* incarnation of class a as a superclass. But a01.a is bound to the *second* incarnation of class a, so when Python checks whether self is an instance of a01.a, it finds that it's not, and throws an exception. The moral of this is, if you must use reload(), make sure that you reload each module only once, and in the correct order. Also be aware of all the other limitations of reload(), such as the fact that any instances you may have around from before the reload will still be instances of the old versions of your classes. Personally I think it's better to avoid using reload() at all, because of all its limitations. Arranging for your computation to be restartable in some other way, as was suggested elsewhere in this thread, is a much better idea. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From havea at nanar.stebe Wed Mar 6 13:04:58 2002 From: havea at nanar.stebe (faith) Date: Wed, 6 Mar 2002 13:04:58 -0500 Subject: Brenda Lee Ehmka has forgotten about Kevin Ehmka References: Message-ID: "jim dutton" wrote in message news:a65b42$hdk$1 at bob.news.rcn.net... > In article , > xganon wrote: > >Brenda, do you wash your hands and your cunt after you masturbate, or do you > >leave your own skank all over yourself, pretending it's Jackie Tokeman's jism? > > > > Steve chaney Brenda is out of your league. Get over her. > > in other news, chaney is too busy humping his blow-up thanksgiving turkey doll to post. faith ======================================================================== = > Visit a homepage: > www.bishopdutton.org > Read about the internets biggest kook/pedophile/obese/ > chronicly unemployed/women beater. ie the worst of the internet: > http://www.pat-acceptance.org > Feed blobbi the psychopath a hog > http://pat-acceptance.org/bobbi.html > > ======================================================================== = > **whoop whoop chany alert** > now me, i wouldnt call chanby a philistine. > > he's a fanboy. an angry one ... much like the angry ape in the passage > from Measure For Measure that i quoted above. and accordingly we see > chabny once again adopting the cartoontoothed battle-postures of Quake > Arena in order to give his inferiority complex a temporary boner, a > sad, tiny, angry, miniature boner that will last long enough to drop > doomed legacyless chanbyseed across multiple pages of the japanese > preteen rape comix that he holds so defensively close to his heart. > -cb > > >Date: Wed, 31 May 1995 19:21:16 -0600 (MDT) > >From: What happens if I press THIS button? > >To: Talk-List > >Subject: This is the side of Tawnya that GunHed won't tell anyone. (snip) > >There was a lot that caused me to no longer want to be with Steve. Some > >of it was the fact that he was too .. rigid. To me, he had no sense of > >humour and he took all my questions to be personal attacks. Yes, I > >admit that I was a bitch to him for the last year. That's because I did > >not want to be with him. Since April of '94, I told him that I wanted > >out of the relationship. But he wouldn't let me go. He refused to let > >me leave him even though he knew I wasn't happy with him. So, I started > >arguments at any opportunity I could. I made his life a living hell > >trying to get him to let me go, but he wouldn't. (snip) > >It was almost fateful the night that Steve and I got into a monstrous > >argument. It was a stupid argument over which wordprocessor was better: > >WordPerfect 6.0 for DOS or MS-Word6.0. For nearly 2 hours, we argued. > >Finally, Steve cut the "TALK" session that we were holding at 6:58pm, > >MST, on Thursday, March 9th. Since I had a class at 7, I simply logged > >out and went to class. I came back at 10pm, MST, and there was a very > >nasty letter in my box saying that I "fucked up" and he was leaving me > >because "he was tired of my bullshit and how I was treating him like > >shit". It was then that I realized that I was finally free of him. I > >didn't leave him, he left me. (snip) > >Monday morning when I went back online, I found out that Steve had > >started spreading that I cheated on him. I tell you this. I did not > >cheat on him. It was not until the 10th of March, the day AFTER Steve > >left me, that I finally agreed to go out with John. AFTER he had left > >me. > > > >Then, he swore to me that if I did not leave John then he would come > >after me with a shotgun. Now that seems a little farfetched as he won't > >come to New Mexico, where I have always lived and he also swore that if > >I came to California, then he would have a shotgun ready for me and/or > >have me arrested. > > > >But for what? I never once said that I would go see him, and I don't > >think that he owns all of California. He has threatened to do too many > >things to me, anything from Netdeath to reality death. And this hasn't > >been just because I left him, but because I wasn't lett him control me > >any longer. > > > >When he came here in January of '94, it was a happy time. Until I saw > >that he lived for control. I went on IRC one night just to check my > >mail and to say Hi to anyone I knew, I was kicked off by a dork who had > >taken over #talk. But because I didn't go into catatonics, Steve went > >crazy. > > > >He stomped around my room with fists clenched and there was a wild look > >in his eyes. Now I'm 6' and weigh approximately 200 (give or take 5 > >lbs) lbs and I know how to defend myself. However, I was afraid of what > >Steve was going to do as he slammed his fist against the wall (which > >caused it to boom out loudly) and I knew that if he were to strike me, I > >wouldn't be in a good position to do anything against him considering > >he's 6'0 and weighs nearly 300lbs. Basically, I was not safe with him, > >or so I felt. > > > >Probably by now, all of you are bored stiff. I admit that this is not > >what you designed this talk-list for. But please, realize this. I did > >NOT cheat on Steve. He dumped me and there was someone here who was > >willing to go out with me. John is here, with me, in the same area as I > >am. He's not pushing marriage on me. Steve was going to make me either > >have his children or raise them, whereas I didn't want either. Also, > >John shares my love for animals, whereas Steve would rather seem them as > >roadkill. (snip) > >I leave the judgement up to God's hands, as we humans are too flawed to > >judge ourselves. Only the Purest may decide. > > > >Toni A. Anaya > > > > > > > > From jacobs at darwin.epbi.cwru.edu Sat Mar 9 10:24:19 2002 From: jacobs at darwin.epbi.cwru.edu (Kevin Jacobs) Date: 9 Mar 2002 15:24:19 GMT Subject: need something like __init__ in classes __classinit__ References: Message-ID: Jens Gelhaar wrote: > I looks like a conflict between "type" and "extensionclass". > Beside, for me it would be natural to have a hook during "compile > time" like __classinit__. Serveral years ago I worked with FORTH and > there was no difference between compile and runtime. It was easy to do > everything what can be done during compile time. I wouldn't bother -- as soon as Zope3 comes out, all of this will work without hacking the Python core. There is very little chance that such changes will be accepted by Guido, so it is up to you to decide if this issue is worth diverging from the stock interpreter. Esepcially since you can do the following in the mean time: class Primary(Persistent): def __classinit__(cls): # ... # ... # Manually call your own classinit after its definition # NOTE: This wil go away after Zope3 stops using ExtensionClasses Primary.__classinit__(Primary) > I will try to hack a little bit in the source. Thanks If you are truely intent on doing this, then the call to __initclass__ be the final step the end of the ReadyClass function. Regards, -Kevin -- -----------> Kevin Jacobs <-----------|-------> (216) 986-0710 <-------- Informatics Consultant | Department of Epidemiology Primary mail: jacobs at theopalgroup.com | & Biostatistics Alternate mail: jacobs at darwin.cwru.edu | Case Western Reserve University ---------------------------------------------------------------------------- From rnd at onego.ru Sat Mar 30 08:30:46 2002 From: rnd at onego.ru (Roman Suzi) Date: Sat, 30 Mar 2002 16:30:46 +0300 (MSK) Subject: decision tables Re: Another stab at a "switch/case" construct (new proposal): In-Reply-To: <3ca55b4a.6988843@news.t-online.de> Message-ID: On Sat, 30 Mar 2002, Gerson Kurz wrote: >On Sat, 30 Mar 2002 08:33:13 +0300 (MSK), Roman Suzi >wrote: > >>However, I'd liked to see a good paradigm for expressing >>decision tables like this one: >> >>F1 F2 F3 R >>0 0 * do1 >>0 1 0 do2 >>0 1 1 do3 >>1 * * do4 > >just an idea: subclass dict, implement pattern matching in the lookup >func? > >derived_dict( > (0,0,2) : do1, > (0,1,0) : do2, > (0,1,1) : do3, > (1,2,2) : do4 >) > >with lookup > >d[F1,F2,F3](args) Well, that is if do1-4 are functions. But if they are just some short pieces of code? Making them functions will clutter the code... However, I like the idea, thanks! Sincerely yours, Roman Suzi -- _/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/ _/ Saturday, March 30, 2002 _/ Powered by Linux RedHat 6.2 _/ _/ "Answers: $1 * Correct answers: $5 * Dumb looks: Free! *" _/ From bkelley at wi.mit.edu Tue Mar 5 10:44:00 2002 From: bkelley at wi.mit.edu (Brian Kelley) Date: Tue, 05 Mar 2002 10:44:00 -0500 Subject: Python Help - Splash Screen References: <3c84d1cf$1@buckaroo.cs.rit.edu> Message-ID: <3C84E7C0.4020204@wi.mit.edu> I stole this a while ago from the following post from quickdry at users.sourceforge.net deja reference http://groups.google.com/groups?q=tkinter+using+pil&hl=en&selm=3bf9d934%240%2410227%24afc38c87%40news.optusnet.com.au&rnum=1 I modified it to add PIL support for loading images. It shows a splash screen with an image (jpg, gif and others that PIL supports) for a specified number of milliseconds, then it closes and the main window pops up. You will need to have PIL installed http://www.pythonware.com/products/pil/ You'll have to supply your own "python.jpg" file to test :) """SplashScreen A splash screen that displays an image for a predefined number of milliseconds. usage tk = Tk() s = SplashScreen(tk, timeout=2000, image="python.jpg") mainloop() The main window will be shown after the timeout. requires: PIL imaging library """ from Tkinter import * try: from PIL import Image, ImageTk except ImportError: import Image, ImageTk class SplashScreen(Toplevel): def __init__(self, master, image=None, timeout=1000): """(master, image, timeout=1000) -> create a splash screen from specified image file. Keep splashscreen up for timeout milliseconds""" Toplevel.__init__(self, master, relief=RAISED, borderwidth=5) self.main = master if self.main.master != None: # Why ? self.main.master.withdraw() self.main.withdraw() self.overrideredirect(1) im = Image.open(image) self.image = ImageTk.PhotoImage(im) self.after_idle(self.centerOnScreen) self.update() self.after(timeout, self.destroy) def centerOnScreen(self): self.update_idletasks() width, height = self.width, self.height = \ self.image.width(), self.image.height() xmax = self.winfo_screenwidth() ymax = self.winfo_screenheight() x0 = self.x0 = (xmax - self.winfo_reqwidth()) / 2 - width/2 y0 = self.y0 = (ymax - self.winfo_reqheight()) / 2 - height/2 self.geometry("+%d+%d" % (x0, y0)) self.createWidgets() def createWidgets(self): # Need to fill in here self.canvas = Canvas(self, height=self.width, width=self.height) self.canvas.create_image(0,0, anchor=NW, image=self.image) self.canvas.pack() def destroy(self): self.main.update() self.main.deiconify() self.withdraw() if __name__ == "__main__": import os tk = Tk() l = Label(tk, text="main window") l.pack() assert os.path.exists("python.jpg") s = SplashScreen(tk, timeout=2000, image="python.jpg") mainloop() From sheershion at mailexpire.com Sat Mar 2 10:02:45 2002 From: sheershion at mailexpire.com (Robert Amesz) Date: Sat, 02 Mar 2002 15:02:45 -0000 Subject: win32+popen4 References: <$4LupWAmqsf8Ew0o@jessikat.fsnet.co.uk> <3C7FF015.D1A00D13@ccvcorp.com> Message-ID: Robin Becker wrote: > interestingly I don't seem to need the \ quotes in win2k. What > system is it that needs those? Well, usually you don't, but I've found I *had* to escape a \ when it's at the end of the commandline. ISTR that escaping all backslashes didn't hurt, so that would make it a safer option. Presumably, even MS wouldn't treat some \ combination as an escape sequence in a commandline, but there may be other strange combinations. Robert Amesz From skip at pobox.com Tue Mar 5 09:36:35 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 5 Mar 2002 08:36:35 -0600 Subject: bsddb for beginners? In-Reply-To: References: Message-ID: <15492.55283.824251.57402@12-248-41-177.client.attbi.com> (Apologies for the long-winded reply. I've been answering questions on python-help for too long I guess. Just jump to the end for the spoiler. ;-) A> I want to get into databases, but most of the tuts around seem to be A> over my head. >>> import bsddb >>> db = bsddb.btopen('spam.db', 'c') These two lines should be pretty straightforward. Import the necessary module and create a bsddb btree file associated on disk with spam.db. >>> for i in range(10): db['%d'%i] = '%d'% (i*i) Let's restructure this a bit: for i in range(10): key = '%d' % i val = '%d' % (i*i) db[key] = val The first line loops i over the integers 0 through 9 inclusive. The last line associates val with key in the database file. Most database file packages like bsddb (and dumbdbm and dbm) require the keys and values to be strings. If the code was for i in range(10): key = i val = i*i db[key] = val it would make more sense, as it would be just like a dictionary, however it would raise an error. The assignments key = '%d' % i val = '%d' % (i*i) simply convert i and i*i to strings. In this case you could also use key = str(i) val = str(i*i) or key = `i` val = `i*i` When the left-hand argument to the % operator is a string, a new string is produced by interpolating the right-hand argument(s) according to the format specifiers in the string. %d tells the format operator to treat the corresponding argument as an integer. For complete details of string formatting, check out http://www.python.org/doc/current/lib/typesseq-strings.html A> Also, do I take it that the Berkely System comes with Python 2.2, and A> therefore I don't need to download anything else? Or is bsddb merely A> an interface for the Berkely System? The bsddb module is simply a wrapper around the Berkeley DB library. It comes with Python, but Berkeley DB comes probably from your OS vendor. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From gtalvola at nameconnector.com Fri Mar 22 14:23:49 2002 From: gtalvola at nameconnector.com (Geoffrey Talvola) Date: Fri, 22 Mar 2002 14:23:49 -0500 Subject: Why do Windows sockets break after exactly 4 minutes? Message-ID: Gordon McMillan wrote: > Geoffrey Talvola wrote: > > > I've noticed that Windows sockets seem to close all by themselves if > > there is no activity for 4 minutes. Does anyone know why? Is it > > possible to control this behavior? Just a link to some > documentation > > of this behavior would be greatly appreciated. > > > > I don't think the same thing happens on Linux, or maybe it > does but the > > timeout is longer than 4 minutes there. > > > > I've attached a set of 2 test scripts that provoke the > behavior. Start > > up server.py first, then client.py, then wait 4 minutes. > > Does it help to note that if you change: > > > time.sleep(250) > > to time.sleep(15), then the socket closes after 15 seconds? > > Your client does a shutdown(1) after sending some data. > The shutdown(1) causes the server to fall out of the > receive loop. It then sleeps for however long specified, > sends some data and closes the socket. > > In other words, the behavior is exactly what you asked > for, and Windows' socket implementation has nothing to > do with it. But that's not what's happening. If I have the call to time.sleep() sleep any amount of time up to 4 minutes, then the client receives the "goodbye" message after the correct amount of time -- exactly as intended. But once I bump the time up to > 4 minutes, then instead of receiving the "goodbye" message from the server, a socket.error exception gets raised in client.py _exactly_ 4 minutes after the call to shutdown (even if I use time.sleep(1000) or time.sleep(10000)): sent message at Fri Mar 22 14:14:01 2002 socket exception caught at Fri Mar 22 14:18:01 2002 Traceback (most recent call last): File "D:\junk\SocketTimeoutTest\client.py", line 13, in ? data = s.recv(1024) File "", line 1, in recv socket.error: (10054, 'Connection reset by peer') When I use a time shorter than 4 minutes in the time.sleep(), the output from client.py looks like: sent message at Fri Mar 22 14:20:43 2002 Received 15 bytes: Goodbye, world! closed socket at Fri Mar 22 14:20:58 2002 So something is breaking the socket after 4 minutes. I should note that this is on a Windows NT 4.0 SP6 box. Perhaps I'll try Win2K to see if there's a difference there. - Geoff From loewis at informatik.hu-berlin.de Tue Mar 5 04:36:26 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 05 Mar 2002 10:36:26 +0100 Subject: I've got the unicode blues References: <3c846d80.95456984@news.isar.de> Message-ID: gerson.kurz at t-online.de (Gerson Kurz) writes: > Coming from a lowlevel assembler/C background, the most intuitive way > of understanding the whole messy thing is this: ASCII characters are > one byte each, UNICODE characters are two byte each. That is not > correct, but its a pragmatic way of viewing things that has worked so > far on the Windows implementation of UNICODE. Notice however, that for Unicode, there might be a difference between on-disk representation and in-memory representation. Also notice that different on-disk representations are in use (UTF-8, UTF-16, UTF-32, ...) > The first two initial bytes look suspicious, but all bytes after that > are like expected: two bytes per character, and the latin letters look > like their ASCII counterpart. Some searching at http://www.unicode.org > reveals that the first two bytes are identifiers for UNICODE files > like this, called "BOM". Correct. > Back then, in the times of 2.1, two solutions were proposed, neither > of which work: > > >>> unicode(open('test.reg').read(), 'utf-8') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: UTF-8 decoding error: unexpected code byte That can't work; the file is not encoded in UTF-8. UTF-8 is a Unicode encoding where each character does *not* have two bytes; characters from the ASCII subrange need only one byte, whereas, e.g. umlauts need two bytes; Chinese characters even need three bytes. > OK, after a bit of searching I suspect I might have to go for utf-16, > because that seems (to my limited UNICODE knowledge) like its the > two-byte-codec I was looking for: > > >>> encode, decode, reader, writer = codecs.lookup('utf-16') > >>> f = reader(open('test.reg')) > >>> print f.readlines() > [] That should work, in theory. However, a better way to spell it is f = codecs.open('test.reg', encoding='utf-16') > Those are unexpected results in my view. I suspect the reason is the > BOM is not handled by those functions. There was a bug in the UTF-16 stream reader of Python 2.1, where it would not remember the byte order across .readline invocations. That bug is fixed in Python 2.2. > My take on this is, that the builtin file-readlines() *should* really > know about BOM and return UNICODE strings if the file has a BOM. They do now. > I volunteer to patch the readlines function, if some other people > out there feel that this is right, too. Please try Python 2.2 first; if there is any remaing problem, report it to SF. > My first foolish attempt: > > lines = ReadLinesFromAnything("test.reg") > file = open("test.out","wb") > assert(type(lines[0])==types.UnicodeType) > file.write(lines[0]) > file.close() > > gives me the first line, all right, but in ASCII, not UNICODE! Yes, a Unicode string must be converted to a byte string before you can write it to a file. To do that, Python uses the encoding returned in sys.getdefaultencoding(); in the standard installation, that is "ascii". It was considered the most useful value for a general-purpose encoding, since it is also use when you do things like unistring += "HKLM\foo\bar" Here, the byte string on the right-hand-side must be converted to a Unicode string before the two can be added - this is another place where the default encoding is used. Normally, you'll get an error if the default encoding is used in the "wrong" place; this appears one of the few cases where it silently does the wrong thing. > file.write(unicode("test3","utf-16")) > > which raises the following exception: > > File "D:\Scripts\2002\02\read-unicode-lines.py", line 20, in ? > file.write(unicode("test3","utf-16")) > UnicodeError: UTF-16 decoding error: truncated data No surprise: the byte sequence '\x74\x65\x73\x74\x33' does not constitute a valid UTF-16 encoding. > when I desperately try this: > > data = unicode(lines[0],"utf-16") > file.write(data) > > I get the exception > > File "D:\Scripts\2002\02\read-unicode-lines.py", line 20, in ? > data = unicode(lines[0],"utf-16") > TypeError: decoding Unicode is not supported No surprise either: unicode() is a function that constructs a Unicode string, given a byte string (similar to int(), list(), or tuple()). What you want to do is to create a byte string, given a Unicode string; to do that, invoke the string's .encode method file.write(lines[0].encode("utf-16")) > The hexdump looks OK, too. But, when I try to write multiple strings, > I run into trouble again, because each string is prefixed with the > BOM, and not the file only: > > lines = ReadLinesFromAnything("test.reg") > file = open("test.out","wb") > for line in lines: > file.write(line.encode("utf-16")) > file.close() In Python 2.2, this can be rewritten as lines = codecs.open('test.reg',encoding='utf-16').readlines() file = codecs.open('test.reg','w',encoding='utf-16') file.writelines(lines) Due to the bug in Python 2.1, you do indeed get multiple copies of the BOM; to work around this, you can do lines = ReadLinesFromAnything("test.reg") file = open("test.out","wb") file.write(codecs.BOM_LE) for line in lines: file.write(line.encode("utf-16le")) file.close() The LE/BE codecs don't write a BOM, so they operate nicely using sequential write. In fact, this is what the UTF-16 codec does: it first writes the BOM, then writes the data in the chosen endianness. > - *much* better support for UNICODE Textfiles in python > - a *much* better documentation on this in python. > > So now I already feel much better :) I hope I could answer some of your concerns. Contributions of documentation are welcome. To the original Python Unicode infrastructure authors, it is just not clear what problems people run into, as it is not clear how people *expect* that these things should work. Regards, Martin From emile at fenx.com Fri Mar 1 14:13:00 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 1 Mar 2002 11:13:00 -0800 Subject: __abs(self)__? References: Message-ID: "Mike Carifio" wrote in message news:f3Qf8.2391$26.139172 at typhoon.maine.rr.com... > I'm reading about special method names. __abs__(self), which maps to the > abs() method seems unneccessary(?). (Whoops, it got away from me) Compare: class ExampleNumber: def __init__(self, initializer): self.value = initializer def __abs__(self): return abs(self.value) x = ExampleNumber(-1) print abs(x) class ExampleNumber: def __init__(self, initializer): self.value = initializer def abs(self): # name isn't special? return abs(self.value) x = ExampleNumber(-1) print abs(x) HTH, -- Emile van Sebille emile at fenx.com --------- From leader730 at hotmail.com Thu Mar 28 22:26:01 2002 From: leader730 at hotmail.com (Joseph Youssef) Date: Thu, 28 Mar 2002 22:26:01 -0500 Subject: number of lines in a file Message-ID: hello, I am nwe to Python and I'm trying to write this script but I need it to check how many lines is in the file and I don't know how so I'm hoping someone could tell me. -- Too often we lose sight of life's simple pleasures. Remember when someone annoys you it takes 42 muscles in your face to frown, BUT, it only takes 4 muscles to extend your arm and bitch-slap that mother@#?!&! upside the head! -------------- next part -------------- An HTML attachment was scrubbed... URL: From huaiyu at gauss.almadan.ibm.com Wed Mar 6 20:21:38 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Thu, 7 Mar 2002 01:21:38 +0000 (UTC) Subject: PEP 276 -- What else could iter(5) mean? References: <6qu1rtfkdi.fsf@abnoba.intevation.de> Message-ID: >James_Althoff at i2.com writes: > >> > [f(x) for x in (4 in 3) in (2 in 3) if x in (x+1 in x*2)] # just for fun. >> But just to make sure I understand your point, I guess you are saying the >> above is bad because today's equivalent is more clear? >> >> [f(x) for x in range((4 in range(3))) in range((2 in range(3))) if x in >> range((x+1 in range(x*2)))] No. Today's equivalence is Traceback (most recent call last): File "", line 1, in ? TypeError: iterable argument required >> Can you suggest a less contrived example that might be a problem? Bernhard Herzog wrote: > >x, = 1 > >would assign 0 to x instead of raising an error. Exactly. And one can imagine a situation where this may build up to the above contrived example if the error is not detected earlier. Even though this proposal does not directly lead to 3 == (0,1,2), it does imply that you can use an integer in majority of cases where a sequence is required. Eg: f(*6) a,b,c = 3 2 in 4 for a, b in 2, 2, 2, 2: print a, b 3[2][1][0] Huaiyu From seeger at sitewaerts.de Thu Mar 7 06:05:21 2002 From: seeger at sitewaerts.de (Felix Seeger) Date: Thu, 07 Mar 2002 12:05:21 +0100 Subject: time date math problem Message-ID: Hi What I want: Date: 20.03.2002 20.05.2002 - 21.00.0000 = 30.04.2002 I need this for displaying an archive of files by date: The last files from this week Than ever week a file After one month every month a file and so on. How can I do this ? thanks have fun Felix From tejarex at yahoo.com Tue Mar 12 12:47:41 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Tue, 12 Mar 2002 17:47:41 GMT Subject: new to python - please help References: <9e629c01.0203120932.5b3eae15@posting.google.com> Message-ID: <1brj8.202456$pN4.11584493@bin8.nnrp.aus1.giganews.com> "Owen Stevens" wrote in message news:9e629c01.0203120932.5b3eae15 at posting.google.com... > (apologies for last post) > > i made a dictionary (mydict) with the following structure: > mykey=(list1:list2) This is not a legal python statement > i overwrote list1 inside the dictionary with a new list > > templist1=[mydict[mykey][0] Neither is this, so it is hard to know what you actually entered, and therefor hard to comment on what you claim to be the output. Try again, with the actual code you ran (preferably cut and pasted) and a short description of what you are trying to accomplish. Terry J. Reedy From loewis at informatik.hu-berlin.de Tue Mar 5 03:54:29 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 05 Mar 2002 09:54:29 +0100 Subject: Memory leak when importing? References: Message-ID: Harald Kirsch writes: > > > > I'd invoke gc.getobjects() from time to time, to see whether the list > > Sounds good, but in which version does it appear? I cannot find it in > the docs of 2.1 or 2.2, nor a function of a similar name. It's actually gc.get_objects, available since 2.2. Regards, Martin From p.magwene at snet.net Sat Mar 16 21:57:06 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sun, 17 Mar 2002 02:57:06 GMT Subject: why python for the academe? References: Message-ID: On Sat, 16 Mar 2002 21:00:57 -0500, huck wrote: > hello all, > > i've been lurking for a while and am amused at how many people in the > list here use python for scientific computing. why not matlab (or octave > or scilab or whatever)? > > Speaking only for myself of course - flexibility, extensibility, readability, and "shareability" Flexibility: As a general programming language I find Python to be a lot more flexible. I've done the programming thing in specialized environment like Mathematica/Matlab/Octave/R. While particular operations are sometimes simpler in these environements, the general structure of programs seems to be much more constrained. When I'm implementing some new bit of code for my research, often as not, I'm (hopefully) not doing the same things that people have done previously, and so I appreciate the flexibility of a general programming language. Extensibility: I can use precanned extensions like Numeric when I need an extra speed boost, or write a quickie interface to some piece of C code I have lying about (though I HATE to do this - it makes me appreciate python that much more). Readability: I can hand my code to one of my colleagues and chances are they'll understand what's going on, regardless of whether or not they know python. "Shareability": Python is free and widely available (so are Octave Scilab, R, etc., but not Matlab) and there is a large amount of freely shared code available, much of it useful. While many researchers in the US/Europe can probably afford the $500+ licensing fees for something like Matlab, many of our colleagues around the world can not (And I'm generally tired of shelling out more moolah every 12-18 months when the developers of the commercial packages have gotten around to fixing the bugs in the previous release) My-own-two-bits-ly-y'rs, Paul From adeptus at onebox.com Wed Mar 13 17:35:40 2002 From: adeptus at onebox.com (news.earthlink.net) Date: Wed, 13 Mar 2002 22:35:40 GMT Subject: Python / Active Scripting - Value Assignment - HELP References: <3C8F5564.7020502@skippinet.com.au> Message-ID: <0vQj8.13070$P4.1124832@newsread2.prod.itd.earthlink.net> Thanks for your help... One thing I didn't think of at the time is the fact that I was trying to call the script from a HTT file which is used for a custom folder view in win2k. >From within the HTT file, no matter what I try to assign to ax.document.bgColor.Value the following error appears. TypeError: 'unicode' object has only read-only attributes (assign to .Value) When I do the same from within a regular HTML file, I don't get an error... But setting the value doesn't seem to do anything. (which gives me the hunch that the error is still there, just not being brought to anyones attention) After I'm back on my own PC I'll look into geting the MS script debugger. calling repr(ax.document.bgColor) rewards me with u'#808080' (which corresponds to the gray background color) and a unicode str My understanding of both Unicode and COM are not quite what they should be, but your suggestion does confirm that the value is a unicode string. I'm still hoping theres still some simple conversion trick I'm missing. Thanks again for all your help and time (and especialy the libs themselves)... adeptus "Mark Hammond" wrote in message news:3C8F5564.7020502 at skippinet.com.au... > adeptus wrote: > > OK... > > > > Within a script block of a HTML file, I can do the following: > > > > something = ax.document.bgColor > > ax.document.write("Background color is %s:" %something) > > What does: > ax.document.write("Background color is %r:" %something) > > show? (%r == repr(ob)) > > > > > However, unlike all the Javascript and VB examples I see, I can't do > > the > > following: > > > > ax.document.bgColor = "#000000" > > > > I always get an error about unicode strings being read only. > > Post the exact error. > > You could try ax.document.bgColor.Value = "#0000" - expecially if the > object repr() says "" instead of still being a string. > > Mark. > > From geoff at gerrietts.net Tue Mar 5 15:08:33 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 5 Mar 2002 12:08:33 -0800 Subject: Order of constructor/destructor invocation In-Reply-To: References: Message-ID: <20020305200833.GB11517@isis.gerrietts.net> Quoting Brett g Porter (BgPorter at NOartlogicSPAM.com): > > As someone who needed a year or so to separate the C++ and Python halves of > my brain, I sympathize, and can only urge (as gently as possible) Mr Charney > to think Pythonically , instead of dealing with the frustration of expecting > Python to follow C++'s rules. Down that path lies madness. In particular here, I would point out that using constructors and destructors to manage your implementation, while it seems elegant, is really an incoherent design -- incoherent here meant in the technical sense of "does not hold together", not the vernacular "intoxicated". The constructor's purpose is to instantiate the object. The destructor's purpose is to clean up when it goes away. Overloading those methods with logic salient to neither purpose only serves to make the methods unsuitable for generalized use. In a tightly-constrained application, this might not be a problem, but a solution that does not limit itself can work in more general environments. I think that's not only Pythonic, but OO. --G. -- Geoff Gerrietts "If life were measured by accomplishments, most of us would die in infancy." http://www.gerrietts.net/ --A.P. Gouthey From christophe.delord at free.fr Mon Mar 4 15:15:02 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Mon, 04 Mar 2002 21:15:02 +0100 Subject: Problem with SRE's regular expressions Message-ID: <3C83D5C6.7010303@free.fr> Hello, I'm using regular expressions in python in a parser generator. I have some troubles with the module named 're'. In fact it uses the 'sre' module. When I explicitly use the old 'pre' module it works fine. So my problem is when big strings are scanned using non greedy operator (for example ".*?") 'sre' seems to be recursivle and python stack limit is exceeded. With 'pre', their is no problem. Let's consider the following program (I'm using Python 2.2): import sre, pre big_string = "<" + "that's a very very big string!"*1000 + ">" for re in (pre, sre): print "testing", re if re.match('<.*?>', big_string): print "Ok, it works" else: print "Their's a problem here" This displays : [christ at localhost py]$ bug_re.py testing Ok, it works testing Traceback (most recent call last): File "./bug_re.py", line 9, in ? if re.match('<.*?>', big_string): File "/usr/local/python22/lib/python2.2/sre.py", line 132, in match return _compile(pattern, flags).match(string) RuntimeError: maximum recursion limit exceeded [christ at localhost py]$ Is this a bug in 'sre' or just a known restriction. I've tried to send a mail to sre's author (Fredrik Lundh) but his email address seems not to work. Does anyone know if this behaviour is known and if something is planned to correct it? Best regards, Christophe. -- Christophe Delord http://christophe.delord.free.fr/ From junkster at rochester.rr.com Fri Mar 29 05:48:15 2002 From: junkster at rochester.rr.com (Benjamin Schollnick) Date: Fri, 29 Mar 2002 10:48:15 GMT Subject: Another stab at a "switch/case" construct (for Python 3000): References: <3ca33c88@news.mhogaming.com> Message-ID: In article , Steve Lamb wrote: > case: Don't like it. We already have means to do what a case does and do it > more elegantly. It would add a needless redundant portion to the language. We do??? We have the IF .... ELIF statement structure, which can be used to simulate a case statement, but it is not as clear nor as neat as the case statement. IF X == 0: DO_THIS () ELIF X == 2: DO_THIS (2) ELIF X == 4: DO_THIS (X+2) ELIF Y == 6: DO_THIS() ELIF Z == "ZEBRA": DO_THIS ( ZEBRA ) ELSE: DO_NOT_DO_THIS () I am not aware of any "errors" in the above code, and it's totally a BS routine... So please no pointing that out. But, this routine is not exactly readable compared to a case: CASE X of: 0 : DO_THIS() 2 : DO_THIS (2) 4 : DO_THIS (x+2) 6 : DO_THIS () ELSE: DO_NOT_DO_THIS() if Z == "ZEBRA": DO_THIS (ZEBRA) And it can be optimized to: CASE X of: 0,6 : DO_THIS() 2 : DO_THIS (2) 4 : DO_THIS (x+2) ELSE: DO_NOT_DO_THIS() if Z == "ZEBRA": DO_THIS (ZEBRA) The key issue is that I believe the IF / ELIF / ELSE statement can be used with multiple variables during the IF ELIF..... At least I remember using it that way.... The CASE is cleaner, and can only be used to compare a SINGLE variable with multiple values. And I believe it's easier to maintain.....(And can be optimized easier). - Benjamin From quinn at cruzeiro.ugcs.caltech.edu Fri Mar 8 04:11:52 2002 From: quinn at cruzeiro.ugcs.caltech.edu (Quinn Dunkan) Date: 8 Mar 2002 09:11:52 GMT Subject: List of Dictionaries References: <14dc40e2.0203071559.5e3d4550@posting.google.com> <3C88186F.6BEFA3D2@alcyone.com> Message-ID: On Fri, 08 Mar 2002 05:57:50 GMT, Lenny Self wrote: >Here's a chunk of the real code. > >f = open("c:/test.dbx", "rb") >msgs = ReadOEFile(f) # Using 3rd party code to get email out of an Outlook >mailbox > >masterList = [] > >for mesg in msgs: > email = Read_OE_Message(f, mesg.position) # returns a string containg an >individual email > data = MailData(email).getOrderInfo() # Looks though email and sucks out >important information and returns it as a dictionary > # if I print the data variable here It shows data from each of the >messages (all unique) Try printing id(data). If the numbers are the same, getOrderInfo is returning the same dict for some reason (likely a bug since that's a strange thing to do). In that case, you should fix MailData. If it's 3rd party code and you can't or don't want to, do 'masterList.append(data.copy())'. > masterList.append(data) > # If I print the masterList dictionary here it has the right number of >elements in the list but they are all the same. > >Each of the origional dictionaries containd the following key:value pairs >being appended to the masterList looks something like this. ... >An interesting piece of info is that when I append a subset of this data, >say just to key value pairs it works Like just: > >{'sku':'BIO-09','item':'The Rise of Theodore Roosivelt by Morris, Edmund'} Possibly because making a subset creates a new dict, which avoids the aliasing problem. >Same code just smaller dictionary. Could I be surpassing some sort of >limit. I woudn't think this dictionry is that big. No, you are not exceeding a limit. From jeff at ccvcorp.com Wed Mar 27 15:06:19 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 27 Mar 2002 12:06:19 -0800 Subject: win32 problem interacting with word97 References: Message-ID: <3CA2263B.725B8902@ccvcorp.com> Andrew Brown wrote: > Is there some kind of "sendkeys" method? It's available through the Windows Scripting Host. Not quite trivial to get to, but better than nothing... Jeff Shannon Technician/Programmer Credit International From andrewm at object-craft.com.au Tue Mar 12 21:54:46 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 13 Mar 2002 13:54:46 +1100 Subject: Python embedded like PHP In-Reply-To: Your message of "Tue, 12 Mar 2002 20:13:39 GMT." Message-ID: <20020313025446.674FA38F35@coffee.object-craft.com.au> >Are there any projects out there that allow you to embed python in HTML >like PHP? I like the PHP-style of embedding the bits of program in HTML, >but I'd like to use python... >Something like: > > > print "
      " > for reptile in ["Crocodile", "Python", "Iguana", "Tortoise"]: > print "
    • %s
    • " % reptile > print "
    " >?> > You may want to consider Albatross: http://www.object-craft.com.au/projects/albatross Albatross encourages (but doesn't enforce) the separation of presentation and logic. You might do something like this in Albatross:
    An example Albatross CGI application that demonstrates this is: #!/usr/bin/python import albatross ctx = albatross.SimpleContext('.') ctx.locals.reptiles = ["Crocodile", "Python", "Iguana", "Tortoise"] template = ctx.load_template("reptiles.html") template.to_html(ctx) print "Content-Type: text/html" print ctx.flush_content() And "reptiles.html" would contain:
    Albatross also gives you an complete templating language, and client and server side sessions. The extensive manual is available online as HTML at: http://www.object-craft.com.au/projects/albatross/albatross/ -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From jhorneman at pobox.com Fri Mar 1 08:07:00 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: 1 Mar 2002 05:07:00 -0800 Subject: fileinput not Unicode compatible? / UTF16 codec problems Message-ID: <9ac02e81.0203010507.377dba0d@posting.google.com> Is it possible that the fileinput module is not Unicode compatible? Because I have a little endian 16-bit Unicode file and have trouble reading it in. Decoding it with the UTF16 LE decoder gives me a 'truncated data' error. This is because the string ends with '0x0a' and '0x0a00'. The string is read in using the fileinput module, which apparently call C stdio getc(), which read a byte and not a 16-bit Unicode character. Oddly, this problem doesn't occur for every line. Is there a solution for this, apart from rewriting a number of modules myself? Is there any documentation on which Python modules are Unicode-aware or not? Oh, and how does one handle big endian / little endian Unicode when the UTF16 decoders look for BOMs at the start of each string, but I only have on at the start of the file? There seems to be no way for me to tell it which endianness I have, apart from circumventing the codec and calling the right version myself. Thanks, Jurie Horneman From daniels at mindspring.com Fri Mar 1 01:05:12 2002 From: daniels at mindspring.com (Alan Daniels) Date: 28 Feb 2002 22:05:12 -0800 Subject: Status of PEP's? References: Message-ID: <5d283efe.0202282205.7049ff32@posting.google.com> [snippety doo dah, snippety ay...] "Delaney, Timothy" wrote in message news:... > > The two lines... > > for i in 5: print i > > for i in 5, 6: print i > > ...would behave differently under the proposal. > > They behave differently now. One is a syntax error, the other isn't. Well duh, that's my point. It *should* be an error. "for i in 5" has no natural meaning, and grafting one onto it just to save having to type "xrange" would be, in my opinion, a detriment to the language. > For the record (I've said this before), I like the idea of integers being > iterable (and I'm not a set theory wonk). That's fine if you like the idea. I don't. The only validations I've seen for it are obscure references to set theory, or the vague notion that it looks neat since it would make Python read more like Haskell (or insert whatever favorite research langugage here). I have yet to see any meaningful explanation on how it fixes some gap in Python, or improves it other than saving the need to type the word "xrange". While I'm at it, two problems with it that I haven't yet seen addressed: 1) If you have a class that defines both __int__ and __getitem__ methods, and iterate over an instance of it, which method "wins" comes iteration time? The usual, or the "for i in 5" trick? Maybe this is covered in PEP 276. I've read through it once when it was first introduced and didn't see any mention on how this would be handled. I'd read it through again, but it's late and frankly reading it makes my skin crawl. 2) Anyone new to the language will wonder exactly why it is that they can iterate over ints, strings, tuples, lists, dictionaries, files, generators, and indeed, any class instance that implements an iterable interface... ...but not floats. Hey, if "for i in 5" means something, then obviously "for i in 5.0" should mean something too, right? That's what a newbie will think, and what good reason answer will anyone be able to give them? > ...an integer will not be an iterator. An integer will be > iterable... Again, my point. As I've come to think of it, the whole point of "iterating" is that the programmer is walking through a collection: A tuple is a collection, naturally. So is a list. A string is, umm, a collection of characters (Cough). A file is a collection of lines, mostly, if you squint at it right. A dictionary is a collection of keys, where each key maps to a value. An class instance can be a collection, as long as it acts like one. I can NEVER bring myself to see an integer as a collection, not outside of a lecture on number theory, anyway. Sorry to rant, but this is the only idea for Python I've seen in a VERY long time, since the 1.5.2 days, where rather than capturing my interest and giving me something to contemplate, just strikes me as ugly, and stays ugly no matter how long I look at it. From opengeometry at yahoo.ca Wed Mar 13 12:31:00 2002 From: opengeometry at yahoo.ca (William Park) Date: Wed, 13 Mar 2002 12:31:00 -0500 Subject: Question about scientific calculations in Python In-Reply-To: ; from jason@jorendorff.com on Tue, Mar 12, 2002 at 11:36:05PM -0600 References: Message-ID: <20020313123100.A1034@node0.opengeometry.ca> On Tue, Mar 12, 2002 at 11:36:05PM -0600, Jason Orendorff wrote: > I benchmarked it; results: > > plain Python: 8.557 sec > optimized Python: 2.325 sec > Numeric Python: 0.753 sec > > This is for 1000 numbers in both s_vector and r_vector. But, did you factor in development time? Even with 10sec runtime, you can run it 8640 times in a day. -- William Park, Open Geometry Consulting, 8 CPU cluster, NAS, (Slackware) Linux, Python, LaTeX, Vim, Mutt, Tin From nas at python.ca Sun Mar 17 15:13:43 2002 From: nas at python.ca (Neil Schemenauer) Date: Sun, 17 Mar 2002 12:13:43 -0800 Subject: How-to : Running profile from inside an class on the class' own methods ?? In-Reply-To: ; from thomas@weholt.org on Sun, Mar 17, 2002 at 07:52:41PM +0000 References: Message-ID: <20020317121343.B18548@glacier.arctrix.com> Look at the runcall() method on the Profile class. Neil From fgeiger at datec.at Sun Mar 10 11:51:03 2002 From: fgeiger at datec.at (F. GEIGER) Date: Sun, 10 Mar 2002 17:51:03 +0100 Subject: HTML -> XML: Where's HtmlBuilder()? Message-ID: It's Sunday evening and I seem to have lost the forest for the trees. Guess I need a break and, better yet, some hints... Anyway: I'd like to process a bunch of HTML pages using XSLT. To do so they need to be "more XML like" (
    instead of
    etc.). I remembered an article from Dr. D. Mertz (Charming Python #2, July 2000), where HtmlBuilder() is used for this. But exec'ing 'from xml.dom.html_builder import HtmlBuilder' yields: >>> from xml.dom.html_builder import HtmlBuilder Traceback (most recent call last): File "", line 1, in ? ImportError: No module named html_builder >>> I've installed PyXML 0.6.6 and 4Suite 0.11, so I thought I were equipped for such tasks. A search over my Python inst dir brought this to light: C:\Programme\Python21\xmldoc\demo\dom\html2html Its contents are similar to the snippets in Mertz's article, i.e. HtmlBuilder is used as well: # Construct an HtmlBuilder object and feed the data to it b = HtmlBuilder() b.feed(HTML_DATA) # Get the newly-constructed document object doc = b.document # Output it as HTML print "============" print "HTML version" w = HtmlWriter() w.write(b.document) # Output it as XML print "\n===========" print "XML version" print doc.toxml() So several questions come to my mind: Is HtmlBuilder() deprecated? Which module was it replaced with? What else could I use to convert HTML to XML? Do I need additional modules for this? Or am I already prepared w/o knowing it? Or am I completely wrong? If so, how is this done in a "stat-of-the-art-manner"? Many thanks in advance and best regards Franz GEIGER P.S.: For those who are curious - the big picture: I'm writing several modules to process a bunch of HTML files into a site. A NavBuilder takes a site structure definition (XML format), builds the navigation tree for each page and merges it into it. A Linker resolves especially formatted ref's to other pages into real HTML ref's. An Execer executes Python code snippets it finds in the pages (like PMZ etc. does it). A Shaper applies an XSL file to the HTML pages to make them all look equally formatted (this is where I am stuck now). (Yes, I could achieve this with CSS on the client side, but I don't want to.). Then it includes them into a template file, containing stuff, which is equal for all pages (logos etc.) (Yes, I could achieve this with frames, but I don't want to.) Then all pages are ftp'ed to a web server. All these modules are gathered by a wxPython GUI. So one can load a site, edit some XML and XSL files, press a button to process and transfer it. From phr-n2002a at nightsong.com Thu Mar 7 15:04:29 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 07 Mar 2002 12:04:29 -0800 Subject: [GERMAN] "ziegenproblem" References: Message-ID: <7x3czc87qq.fsf@ruckus.brouhaha.com> stefan antoni writes: > sorry that i won't be able to explain this in english, i don't know the > name of this problem in english, and the website which is about this > problem is also in german. Usually we call it the "Monty Hall problem". Monty Hall was the host of a TV game show where he actually played that game (put a prize behind one of three doors, etc). > i want to write this basic code in python: > http://www.google.de/search?q=cache:Uugc3CH9SOQC:home.spektracom.de/ellrich/Ziegen.htm+ziegenproblem+basic+programm&hl=de > > i am still going to school, and we talked about this problem in a math > lesson. since i haven't got a basic-interpreter, i'd like to translate > this code into python, but i don't understand the code. > > anybody who knows basic and python as well? Yes, but you don't really need a computer program to solve the problem. Just play the game a few times with a friend. Pretend that you are Monty, and put three cards on the table representing doors, and put a coin under one of the cards representing the prize. Have your friend choose a card. Then turn over one of the cards with no coin underneath and ask your friend if he wants to switch to the other card, and tell him to always switch. Once you do this a few times, you will understand the paradox. From sholden at holdenweb.com Wed Mar 27 12:05:20 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 27 Mar 2002 12:05:20 -0500 Subject: Importing PYC References: Message-ID: "Franck Abella" wrote ... > Hi, > > I download a pyc libray and i have a problem to import it. The name of the > library is "LibDates.pyc" ( powerfull dates functions) . I can't use > "import LibDates.pyc" or "import LibDates" even if i put LibDates.pyc in the > python path library. > > How can i import it and use their functions ?? > You don't say what error message you receive. One likely source of problems is that the .pyc file format is dependent on the Python version, so you cannot simply use a Python 1.5.2 .pyc with Python 2.1, for example. When the source is available and the directory is writable, Python will silently recompile modules whose .pyc files come from the wrong version. In your case that can't happen because you have no source. Hope this helps. regards Steve From helmut.zeisel at aon.at Fri Mar 8 03:57:45 2002 From: helmut.zeisel at aon.at (Helmut Zeisel) Date: 8 Mar 2002 00:57:45 -0800 Subject: SWIG: operator const char*() const Message-ID: I have a class, say myString, with an operator const char*() const for which I want to create Python shadow classes (swig -c++ -shadow -python) class myString { public: const char* operator() const; ... }; Using this code, I get the warning: "Can't wrap operator const char* unless renamed to a valid identifier." So I tried to rename: %rename(c_str) myString::operator const char*() const; This gives the error message "Syntax error in input" What is the correct syntax to rename? Helmut From mickey at tm.informatik.uni-frankfurt.de Sat Mar 2 13:03:51 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 2 Mar 2002 20:03:51 +0200 Subject: Possible to fake object type? References: <3c80e76b@nntp.server.uni-frankfurt.de> <3c80fb6d@nntp.server.uni-frankfurt.de> Message-ID: <3c812217@nntp.server.uni-frankfurt.de> > why not something like that?: > > def __getattr__(self, name): > try: > return self.__dict__[name] > except NameError: > return getattr(gtk.HandleBox, name) This is basically the same as I have now. But the thing is: __getattr__ only gets called when the attribute _doesn't_ exist, which is not very helpful, 'cause they would exist in the baseclass, which is the reason why I can't simply derive from gtk.HandleBox. I want to have a class which sends all calls to one of its attributes but at the same time is derived (or even better _only_ has the same [fake] type, which my original subject header implied) from something, which unfortunately has a bundle of the same methods. Yours, :M: From chris.gonnerman at newcenturycomputers.net Fri Mar 29 08:57:08 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 29 Mar 2002 07:57:08 -0600 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> <0_Zo8.16784$Ou.11910@atlpnn01.usenetserver.com> Message-ID: <005401c1d729$b3cef3c0$0101010a@local> ----- Original Message ----- From: "Steve Holden" > "John Machin" wrote ... > > > I think that I'm proposing indicating the default by having a keyword > > argument ("default")on the new-in-2.2 constructor ("dict"); what do > > you think that I meant? > > I knew what you meant, I was simply pointing out that dictionaries' literal > representations could notr specify a default value, which (I supposed) might > lead to VBScript-like horrors where all dictionaries (collections, in > VBScript) must be created by explicit addition. > > However, Bength Richers suggestion: > > > empty_dict_with_default = {:default} > > with_one_key_value_pair = {:default, key:value} > > > > A little tweak in the grammar might do it? > > might well suffice, and wouldn't require huge changes to the grammar. But do we REALLY need it? Another new semantic feature, another altered basic behavior. Python is so cool because it is compact (linguistically) and easy to grasp. Each new use of punctuation makes it more complex and Perl-like. Writing a class to simulate a dictionary with default value is simple, and left as an exercise for the reader :-) Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From amichail at cse.unsw.edu.au Wed Mar 27 01:13:23 2002 From: amichail at cse.unsw.edu.au (Amir Michail) Date: 26 Mar 2002 22:13:23 -0800 Subject: instrumenting Python code Message-ID: <1010a26.0203262213.4a0d4b11@posting.google.com> Hi, I was wondering if there is an easy way to instrument Python code so that I can collect information about a particular execution. In particular, I am interested in collecting the following info: * functions called in execution * which function called what other function (the call graph) * the values of local/global variables It seems I can get all this from the debugger module though it doesn't appear to have been designed to be used from another program. The profiler module only gives the first item above. Any recommendations? Amir From geoff at gerrietts.net Sun Mar 10 18:01:48 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Sun, 10 Mar 2002 15:01:48 -0800 Subject: Standalone Win32 wxPython apps? In-Reply-To: References: <3C8ADDD3.E3ACC1EB@engcorp.com> <3C8AEE09.5B2431FD@engcorp.com> <1a9n8us1629mrvei40hdkuuerc1j6p318m@4ax.com> Message-ID: <20020310230148.GL8360@isis.gerrietts.net> Quoting Grant Edwards (grante at visi.com): > In article <1a9n8us1629mrvei40hdkuuerc1j6p318m at 4ax.com>, Courageous wrote: > > I would think that for an isolated app, .so's would slow down > load times. With a statically linked program all you do is a > single memmap() call (well, ignoring a few details). With > .so's you've actually got to resolve all of the symbols and do > the linking step (not required for statically linked images). > > Since you've got the same number of bytes to swap in off disk, > that should be a wash. I can't speak for the windows world, but in the Linux world, .so's end up saving some time because the dynamic linker doesn't actually move things into the program's address space until needed -- it does this on a page-by-page basis. Consequently, less start-time latency at a slight cost when you use the feature. My data comes from: http://www.suse.de/~bastian/Export/linking.txt A worthwhile read, though it probably should be filed under "dark sorcery". --G. -- Geoff Gerrietts "Whenever people agree with me I always feel I must be wrong." --Oscar Wilde From r.salz at verizon.net Wed Mar 20 23:38:13 2002 From: r.salz at verizon.net (Rich Salz) Date: Thu, 21 Mar 2002 04:38:13 GMT Subject: #define equivalents and config files References: Message-ID: <3C9963BD.1040304@verizon.net> > Is there a pythonic way of doing something similiar to Cs #define? >... are globals the only way to go? You can at least make them class attributes class constants: pi = 3.14159 e = 2.71828 adding your own setattr can serve to make them read-only. /r$ From peter at engcorp.com Sun Mar 31 01:31:41 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 31 Mar 2002 01:31:41 -0500 Subject: seek() References: Message-ID: <3CA6AD4D.C552BDDA@engcorp.com> Zutroi Zatatakowski wrote: > > Is there a kind of seek() function that does the same thing but except > of bytes, it seeks for a string? Basically, I want the 5 next bytes > after a certain string in a file. Example: > Foo:36.50 > The data I want (36.50) is located on a web page and since the content > of that page always change, I can't get it with seek() because the bytes > always change too. I've checked in STRING and RE modules but I can't > find a function that checks in a file/webpage, they all need input from > a string. Well, that's the basic key to writing software: use components that already exist to build up a more sophisticated solution. In this case, if you have a method of finding a string in a string (which you have already found), and you have a method of getting a string from a file or webpage, you can clearly put the two together to solve your overall problem. Getting a string from the data in a file is rather simple, and if you want to get a string from a web page you should look at the urllib module. -Peter From kalle at gnupung.net Mon Mar 4 18:15:46 2002 From: kalle at gnupung.net (Kalle Svensson) Date: Tue, 5 Mar 2002 00:15:46 +0100 Subject: Super newbie question D: In-Reply-To: References: Message-ID: <20020304231546.GA1032@sandra.lysator.liu.se> [Joseph Youssef] > how do I generate a random number in Python, I used to know but I forgot :'( Look at the module random. http://python.org/doc/current/lib/module-random.html Peace, Kalle -- Kalle Svensson (kalle at gnupung.net) - Laziness, impatience, hubris: Pick two! English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] From acockburn at aol.com Thu Mar 28 20:01:21 2002 From: acockburn at aol.com (Alistair Cockburn) Date: 28 Mar 2002 17:01:21 -0800 Subject: Python & Poetry References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> <7396d2b2.0203271554.5a564e1b@posting.google.com> Message-ID: d_blade8 at hotmail.com (Lemniscate) wrote in message news:<7396d2b2.0203271554.5a564e1b at posting.google.com>... > Incidently, this is related to why, historically, some > poets looked down at prose as a mode of expression (poets, they > argued, convey ideas, thought, emotion while prose writers had to be > concerned with conveying the plot). It's all about what ideas we are > trying to convey... Right. I write poetry reasonably well, and talk reasonably well, but don't feel at all comfortable with fiction. For me, the diffence between a poem and a story is that the poem *touches* someone where they already are, and a story *moves* someone to a new space. At least, I don't understand any poem that I don't already understand (ditto from my poems), whereas I have been moved to new understandings from reading prose. (also interesting, I can move people to new understandings through discussion, because I can see they expressions, but don't feel I can move them to new understandings in text). Alistair From berenikeloos at gmx.de Wed Mar 20 14:48:50 2002 From: berenikeloos at gmx.de (Berenike Loos) Date: Wed, 20 Mar 2002 20:48:50 +0100 Subject: How to delete/mainpulate global variables ?? Message-ID: <000801c1d048$4435e510$bf7ba8c0@kitty> Hi I am using two function in my program. The first one reads out some text of an TK entry field and puts it into a global variable. The other function has to read out the global variable and has to print out the text. Now the global variable should be deleted, so if I call the second function again without calling the first, NO text will be displayed. thx a lot -------------- next part -------------- An HTML attachment was scrubbed... URL: From logiplexsoftware at earthlink.net Wed Mar 6 20:36:46 2002 From: logiplexsoftware at earthlink.net (Cliff Wells) Date: Wed, 6 Mar 2002 17:36:46 -0800 Subject: Threading help? In-Reply-To: <3C86BD6F.9D258DA7@engcorp.com> References: <3C867E68.B4C3FED2@accessforall.nl> <20020306132612.4a5d756a.logiplexsoftware@earthlink.net> <3C86BD6F.9D258DA7@engcorp.com> Message-ID: <20020306173646.5fa074f3.logiplexsoftware@earthlink.net> On Wed, 06 Mar 2002 20:07:59 -0500 Peter Hansen wrote: > Cliff Wells wrote: > > > > On Wed, 6 Mar 2002 13:26:12 -0800 > > Cliff Wells wrote: > > > > > The approach I would take, based upon the information given, is to have > > > thread A retrieve the data every .1s (using time.sleep), when the data > > is > > > retrieved, put it on a Queue and go back to sleep. Thread B blocks on > > the > > > Queue until data is available. When data becomes available, B processes > > > that data and place it on a second Queue for thread C (thread C handling > > > HTTP requests) to deal with. > > > > Hm. Okay, I had to reconsider this. Clearly if the processing is slower > > than .1s and data is being added to it every .1s, the Queue is going to > > endlessly grow as more data is added to it. If this is the case, it might > > make sense to have more than one consumer thread (B) doing the processing. > > I might be missing something, but I don't see how adding another thread > (with a slight extra overhead associated with it) would actually increase > performance for what I infer is CPU-bound processing in thread B. > Threads don't add performance capacity, they remove it! (Or is B blocking > on something like a socket, thus slowing it down?) Yes, I thought of this, but I believe that this would give the net effect of increasing thread priority for the B threads (since they will get more CPU time as a whole vs threads A and C). But maybe a better approach would be this: if processing time is greater than .1s and we don't care about out-of-date data (big assumption, but not unreasonable), then use the Queue between A and B and simply have B empty the Queue on every iteration, processing only the newest data. This would keep the Queue to a reasonable size at the cost of dropping data. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From phr-n2002a at nightsong.com Sat Mar 9 07:27:04 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 09 Mar 2002 04:27:04 -0800 Subject: should i learn it first ? References: Message-ID: <7xpu2ex6xz.fsf@ruckus.brouhaha.com> "Qiang.JL" writes: > I am a student who have learned perl,java and other like data structure > stuff. Now i want to take some further step to learn one or two languages to > improve my language view. There are two languages are on the list: python > and C++ > I have heard a lot ppl talk about C/C++,saying it's the must language to > learn for a programmer.and i indeed feel so. but C/C++ is hard and may need > to take longer time to learn and get the concept.also, Python seems a good > language and easier to learn. > I think some of you may come cross this, so let me ask you these questions C++ is complicated, and in order to really understand it you have to understand the problems it tries to solve, which are the organizational problems that software projects get into when a lot of programmers are working on the same program. C is simpler, and different in feeling. It's more like a high level assembler. > do i need to learn C/C++ to be a good programmer? No. Both are very useful, especially if you need to write programs that run fast. For most things, you can write in C and not worry about C++ unless you join a big project that uses it. There are some specific things like writing Windows COM objects that are easier in C++ than in C. That's separate from needing to learn something to be a good programmer. To be a good programmer I think you need a sense of what the machine is doing, so you should learn a low level language, but if you're just doing it for the sake of learning, you may as well go all the way and learn to program in assembly language. There used to be a saying that assembly language programming is good for the soul. That doesn't mean you should actually try to develop complex programs in assembler and make them useful--you should just get some experience with it as an exercise, to understand how computer's instruction set works and have a sense of what a compiler does. Once you've done that, C will seem very straightforward and logical to you. > which one is better to start with ? ( I'm not a program beginner so python > being a beginner programmer maybe not be applied here) > > How many language do you think one should _master_? I think one or two is > enough.learning others are letting you to learn the language concept and > structure etc certainly helpful. If you're an experienced programmer in other languages, you can learn basically everything about Python in a few weeks. C++ takes longer but again, it's just a computer language that some people designed. It's not like a spoken language which evolves over thousands of years. The thing is, to really understand C++, you have to spend time working on multi-programmer projects. If you only program by yourself, some parts of C++ will never make sense to you. From jeff at ccvcorp.com Fri Mar 29 18:11:58 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 29 Mar 2002 15:11:58 -0800 Subject: Python+wxWindows as Visual Basic replacement? References: Message-ID: In article , rs at onsitetech.com says... > Hey all, > > Anyone have any experience using Pythonas an alternative to VB for Windows > database client apps? It looks like all the pieces are in place - > wxWindows, py2exe, a Python ADO library... > > Python per se isn't the issue - what I'm not sure about is what the > development and deployment experience is like, when using these parts, taken > together. Well, I don't have any direct experience with writing database clients, nor with using the full VB development environment, but from what I have gathered... Pure GUI development in VB is likely to be a bit easier, because the VB environment is (I have heard) quite polished, and allows you to do an awful lot with simple 'painting'. There are some graphical designers for wxPython (notably wxDesigner and Boa Constructor), but I don't think that either is up to the level of VB's. Of course, you *do* get all the advantages of working in Python over working in VB. If you're doing any significant amount of processing of the data within your client, I'd think that this advantage would outweigh VB's graphical designer's benefits. As for py2exe, my personal feeling is that it's usefulness is limited unless you're likely to distribute it to a significant number of workstations, and those workstations cannot be expected to use Python for any other purpose. In my own situation, I'm unlikely to distribute any of the software that I'm working on to more than half a dozen machines, and on several of those I'm likely to want to use Python for a number of projects. As a result, it's not difficult for me to ensure that Python is functioning on all my target machines, and I can distribute code as distutils packages, which saves having a separate interpreter for every application I'm creating. Whether py2exe is worth the effort for you, will depend on your specific circumstances -- if you're wanting to put no more than one or two Python applications on a relatively large number of machines, or simply have little/no control over the machines it should run on, then py2exe would be a lot more useful. Hope this helps... -- Jeff Shannon Technician/Programmer Credit International From shalehperry at attbi.com Wed Mar 6 16:21:35 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 06 Mar 2002 13:21:35 -0800 (PST) Subject: The language vs. the environment In-Reply-To: <15494.34706.724985.628479@beluga.mojam.com> Message-ID: > > If you're looking for something to munch on, here are some suggestions, not > all of which require that you write code: > > * breathe some life into the catalog-sig: > http://www.python.org/sigs/catalog-sig/ > > * find a Python bug without a proposed fix and write one (there are > currently between 250 and 300 open bug reports): > http://sourceforge.net/tracker/?group_id=5470&atid=105470 > > * document an undocumented module from the standard library: > http://www.python.org/doc/current/lib/undoc.html > > * write a HOWTO (another of Andrew's little sideline projects!) about > your little niche of Python expertise: > http://py-howto.sourceforge.net/ > help release more python modules so perl mongers will quite wagging CPAN in front of our faces. From Chris.Barker at noaa.gov Thu Mar 7 13:09:28 2002 From: Chris.Barker at noaa.gov (Chris Barker) Date: Thu, 07 Mar 2002 10:09:28 -0800 Subject: Web scripting with Python (My 2nd post!) References: <40c3f5da.0203061114.18f7fea6@posting.google.com> <40c3f5da.0203070720.6ca52e4@posting.google.com> Message-ID: <3C87ACD8.CEAC724E@noaa.gov> Julio Nobrega wrote: >IMHO they are not much user friendly, or community oriented > enough for *my needs* (not to start a flame, please! ;-) Maybe you want something like a wiki? Check out: http://moin.sourceforge.net/ -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From michael at stroeder.com Fri Mar 8 08:38:05 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 08 Mar 2002 14:38:05 +0100 Subject: [ANN] istring 1.0.1 released; announce list created References: Message-ID: <3C88BEBD.20901@stroeder.com> Steven D. Arnold wrote: > > 4. Standard library -- If anyone wishes to take the steps to include > it in the standard library, including any PEPs that may be needed in > addition to 215, you have my blessing and I'll provide support. The > current license is LGPL-like, with the intent of ensuring changes are > open-source without infecting projects that use it. I will make > istring available under the Python license if that is the only > obstacle keeping it from inclusion in the standard library. I have to admit that I'm scared of having to deal with yet another special char $ which would need quoting. Since the istring approach does not add any more value to Python the developers in favor of this should use the istring module. But it should not be added to standard Python. Ciao, Michael. From brian at sweetapp.com Mon Mar 25 15:29:37 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 25 Mar 2002 12:29:37 -0800 Subject: reading in ints from binary files In-Reply-To: Message-ID: <015301c1d43b$c8eba550$445d4540@Dell2> Bill wrote: > However, is there an easier way of doing this? I currently do something > like: > > f=open('file', 'rb') > s = f.readline() > l = list(s[0:-1]) > l.reverse() > a = array.array('h', ''.join(l)) > > There's gotta be an easier way. I'm not really sure what problem you are trying to solve but this might help: f = open('file', 'rb') my_list = array('h', f.read()).tolist() # my_list is now a list of Python integers, which you can manipulate as # usual The use of readline seems crazy to me; it will cause problems if your integers happen to contain the byte 0x0a. Cheers, Brian From mmillikan at vfa.com Wed Mar 6 17:23:11 2002 From: mmillikan at vfa.com (mmillikan at vfa.com) Date: 06 Mar 2002 17:23:11 -0500 Subject: Nested scopes: design or implementation? References: <3czdq05v.fsf@vfa.com> Message-ID: "logistix" writes: > Okay, now I'm confused. > > I was perfectly happy with Teddy Reedy's explaination that def is an > expression and not a declaration. > > But if I'm following you, the embedded attribute function isn't being > recompiled to bytecode each time function() is called. If the code object > is only getting created once, then why are the defaults getting > recalculated? > > -- > - > > wrote in message news:3czdq05v.fsf at vfa.com... > > Note that the object is shared by each of the inner > > objects: > > > > text = "random text" > > def function(): > > def attribute( bindNow = text): > > print bindNow > > function.attribute = attribute > > > > Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 > > Type "copyright", "credits" or "license" for more information. > > > > >>> function() > > >>> function.attribute() > > random text > > >>> function.attribute > > > > >>> function.attribute.func_code > > > > [snip] > > >>> text = 'new random text' > > >>> function() > > >>> function.attribute > > > > >>> function.attribute.func_code > > > > > > Mark Millikan In the example above notice that the function.attribute object is recreated each time the outer definition is called -- it has a different address. However: >>> import pprint >>> pprint.pprint(dir(function.attribute)) ['__dict__', '__doc__', '__name__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> function.attribute.func_defaults ('random text',) >>> text = "new random text" >>> function() >>> function.attribute.func_defaults ('new random text',) The func_code object is shared, but the function object is not. Each of the function objects gets a separate func_defaults object. Some of the state (the func_code object at least, is shared but some is not). HTH Mark Millikan From mhammond at skippinet.com.au Tue Mar 19 17:05:31 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 19 Mar 2002 22:05:31 GMT Subject: Chewing international (unicode) filenames on windows? References: Message-ID: <3C97B638.9040702@skippinet.com.au> Martin v. Loewis wrote: > Subclassing may not be the right solution - perhaps it is better to > admit that ntmodule.c really should be different from > posixmodule.c. What do you think? I am inclined to agree that us pretending they are the same module hasn't really saved us much over the years. So I would have no objections. Mark. From sab at NOSPAM.freeuk.com Sat Mar 23 11:15:30 2002 From: sab at NOSPAM.freeuk.com (G. Willoughby) Date: Sat, 23 Mar 2002 16:15:30 -0000 Subject: IOstreams/pipes, newbie question, capturing console info form another script? Message-ID: Hi, I'm a bit of a newbie when it comes to streams and such so has anybody any help with this? i have a Tkinter program that when run and you click a certain button it calls an 'os.system()' command which starts up another non-gui python script thus: [snip] os.system("python mapper.py -settings mappergui.ini -scale %s -out latest_render.jpg -zone %s" % (self.imageSize, self.currentZone)) [/snip] now i was wondering because this 'mapper.py' script and an included 'zone.py' writes alot of info to the console using 'sys.stdout.write()' can i intercept this using my first Tkinter prgram so i can display this info in another freshly created window. basically i am writing a gui for a cmdline script! if so has anyone got any examples of code for me to look at that would be great! Thanks G. Willoughby From mhammond at skippinet.com.au Thu Mar 28 22:04:41 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Fri, 29 Mar 2002 03:04:41 GMT Subject: Sendkeys without Scripting Host References: Message-ID: <3CA3D9E9.8080907@skippinet.com.au> Harald Schneider wrote: > Hi, > > is there a possibility to use sendkeys() without scripting host installed? > Are there any > extentions available for python? Later versions of win32api have win32api.keybd_event() The documentation for this is pretty sparse: keybd_event(bVk, bScan, dwFlags, dwExtraInfo) Simulate a keyboard event Parameters bVk : BYTE Virtual-key code bScan : BYTE Hardware scan code dwFlags=0 : DWORD Flags specifying various function options dwExtraInfo=0 : DWORD Additional data associated with keystroke For more info, check out the function at msdn.microsoft.com Mark. From cdonicz at cri-inc.com Tue Mar 19 18:13:50 2002 From: cdonicz at cri-inc.com (Corey Donicz) Date: 19 Mar 2002 15:13:50 -0800 Subject: Python Embedding / Import Woes References: Message-ID: Here's a quick follow up post from me to me (and anyone else who might have taken the time to answer this). I was erroneously linking against the python21_d.dll, and the failing imports were of .pyd's which needed to be debug version .pyd's. Doh! -Corey From s.ernst at web.de Fri Mar 15 08:13:28 2002 From: s.ernst at web.de (Sascha Ernst) Date: Fri, 15 Mar 2002 14:13:28 +0100 Subject: further infos References: Message-ID: forget this posting, sorry! "Sascha Ernst" schrieb im Newsbeitrag news:a6srv3$tbo$00$1 at news.t-online.com... > 1. "command not found" is the error message. how can I get more detailed > infos? > 2. the dev tools are ok, I compiled Ruby some days ago successfully > > regards, sascha > > > From logstx at bellatlantic.net Sat Mar 2 14:58:52 2002 From: logstx at bellatlantic.net (logistix) Date: Sat, 02 Mar 2002 19:58:52 GMT Subject: Can't seem to get it right: Win NT registry save and load References: Message-ID: <0aag8.8540$va.1091@nwrddc02.gnilink.net> What exactly are you trying to accomplish? RegLoadKey and RegSaveKey don't necessarily have the best names. They are designed to load and save entire registry hives (such as the ntuser.dat located under each user profile). RegLoadKey binds to the registry and RegSaveKey saves the hive (generally for backup purposes). If you bind a hive to the registry and make changes to various keys with RegSetKey, RegSetValue, etc and then Unload it, the changes will be saved. Some problems you might experience with RegSaveKey: -You can't save a file inplace. Loading a user's ntuser.dat file, making changes and saving won't work because ntuser.dat will be locked when you try to save the file. Furthermore, you don't need to "save" the reg entry to persist your changes. -You need "backup" privledges on the registry hive, which generally means you need to be an administrator. This is done for security reasons. For example, one easy way to break into an NT box (assuming you have physical access) is to run a repair operation on the system after you've replaced the backup registry files with an admin account/password that you know. Outside of python, you might want to play with the tool Reg.exe and regedt32.exe to get a better handle for how things work. Reg.exe got moved from the NT4.0 Resource Kit CD to the W2K Support tools (that can be found on the install CD under the "Support" subdirectory) Have fun (and don't go to crazy with the registry on a production box. I just fried mine!) -- - "Matthias Janes" wrote in message news:d7d5ebdf.0203010908.113324ea at posting.google.com... > Hi I would like in a python script to save a Win NT Registry entry to > a file and load it later - > but it's seems I can't get it right. > > win32api.RegSaveKey > RegSaveKey(key, filename, sa) > > I could not realy figure out the 3 part (sa ) > > get always a error about the security rights. > > after I saved it how could I load it again? > > Any Help would be real nice. > > Matthias Janes From mkelly2002NOSPAM at earthlink.net Wed Mar 13 14:25:19 2002 From: mkelly2002NOSPAM at earthlink.net (Michael Kelly) Date: Wed, 13 Mar 2002 19:25:19 GMT Subject: Why Don't Scripts Run ? References: <3C8F9C59.F9408D47@mcn.net> Message-ID: <1p9v8u4vo4dqpccjsom40gtjlgtaiedve8@4ax.com> On Wed, 13 Mar 2002 18:37:00 GMT, jrc wrote: >Hi - I'm a reasonably experienced programmer. I work in >Windows (ME). Thinking to give Python a try, I downloaded >v22 and installed. At first, it looks good, but then, I discover >it seems impossible to get any scripts to run in the command >prompt, using any available documentation whatever. I even >have Chris Fehily's book - essentially none of his examples >work with scripts from command prompt; yet this is a 2002 >book . (?!!) Hi. If you don't have any Python 2.2 dependencies or just want to try Python out you might find it less frustrating to download ActivePython 2.1. For me(using Win98 2nd Ed.) even the Windows Scripting Host worked out of the box. I've even been using my COM servers on Win98 using ActivePython with no problems at all. At least on my system the ActivePython .msi file installed with no glitches and everything worked as expected. -- "Only choice is an oxymoron." -- From msx at crs4.it Thu Mar 14 07:35:53 2002 From: msx at crs4.it (Federico Caboni) Date: Thu, 14 Mar 2002 13:35:53 +0100 Subject: Good book on Python? References: Message-ID: On 14-03-2002 12:26, in article Pine.GSO.4.43.0203141117120.6137-100000 at muir, "Antonis C Koutalos" wrote: > > Hi there, > I would greatly appreciate information about a good book on python. I > have been programming C for a few years, but I know next to nothing about > python. Therefore, I would appreciate a book that describes the basics of > python as well as the more advanced features of the language. > > Thank you in advance! > > -A. > Hi, There are a lot of books about Python nowadays (and, yes,that's GOOD). I found "Python Essential Reference" by New Riders a very useful book (that is, if you want a brief but deep explanation of the language, Provided that you had previous programming experience with other Languages..) but, AFAIK, it's still based on Python 1.5.2. I recently bought "Programming Python" by O'Really, and I have to admit That I don't know if I like it. It's a very "strange" book, very diifferent from the more famous "Programming Perl". In my opinion it's more like a big cookbook. And...it assumes you already know the language. Maybe it can be useful if you already read Python Essential Reference or Learning Python. I hope you find this useful. Bye, ____ ____ ____ _ _ ____ _ _ ____ / ___)| __ \/ ___)/ /| | / ___)| \| |/ ___) Federico Caboni (msx at crs4.it) | (___ | /\___ \\__ | * \___ \| |\___ \ Software & Network Solutions \____)|_|\_\(____/ |_| (____/|_|\_|(____/ Phone: +39 070 2796 368 CRS4, Center for Adv. Studies, Research and Development in Sardinia From greg at cosc.canterbury.ac.nz Wed Mar 6 22:09:47 2002 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 07 Mar 2002 16:09:47 +1300 Subject: PEP 284, Integer for-loops References: Message-ID: <3C86D9FB.9D05A34F@cosc.canterbury.ac.nz> "Delaney, Timothy" wrote: > > without being a general solution (no step ... To me, the lack of a step is a *feature*, not a bug! Steps other than 1 in a range are confusing when you don't land exactly on the endpoints. Which endpoint do you miss? Do you even hit either of them? And it's even worse when the step is negative. Do the endpoints swap over? Does the closed/open status of the endpoints swap over? Do you miss the opposite endpoint if the step isn't -1? Etc. So, I see *considerable* benefit from eliminating this degree of freedom from the range generation itself, and making the programmer be explicit on how to map a step-1 range onto something else if needed. Perhaps this comment could be added to the PEP? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand To get my email address, please visit my web page: http://www.cosc.canterbury.ac.nz/~greg From mcherm at destiny.com Fri Mar 29 13:50:53 2002 From: mcherm at destiny.com (Michael Chermside) Date: Fri, 29 Mar 2002 13:50:53 -0500 Subject: problems with circular references Message-ID: <3CA4B78D.7000202@destiny.com> [Jim wants self-contained modules that define error codes and error messages] [Handling an error requires a MessageCatalog module, which imports ALL the modules to build an error message list.] [Susan suggests that the classes register themselves with the MessageCatalog instead of being imported by it.] I think Susan's solution is an excellent one. MessageCatalog shouldn't have (hard-coded) knowledge of what other modules there are, because it is intended to be generic. So have all the OTHER modules register their errors with the MessageCatalog during their import. Of course, not all of the modules get imported as this is a CGI application, but the fact that some error code which was generated must indicate that the module which defines it already got imported (since it was running!). So while the MessageCatalog may not be *complete*, it will certainly have all errors which could have occurred. -- Michael Chermside From dale at riverhall.NOTHANKS.co.uk Sat Mar 30 08:58:34 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 30 Mar 2002 13:58:34 +0000 Subject: Data type ideas References: Message-ID: <6vgbaugf53ph7l96dg8mrchrn894mmbkg4@4ax.com> I can think of half a dozen ways to approach this but the best solution is will depend on: How many people? How many groups? Maximum number of people to a group (approx)? (These determine the best data structures to use.) How often do you need to run this? (This determines how much attention to pay to effeciency.) -- Dale Strickland-Clark Riverhall Systems Ltd From nick at nick8325.freeserve.co.uk Mon Mar 18 14:51:05 2002 From: nick at nick8325.freeserve.co.uk (Nick) Date: Mon, 18 Mar 2002 19:51:05 -0000 Subject: Adding static typing to Python References: <0DFA7478F1E5D311B90900508B1208CF565714@ausmail02.mis.gtech.com> Message-ID: "Brendan Hahn" wrote in message news:bhahn-ya02408000R0403021410080001 at news.corp.hp.com... > Courageous wrote: > >One of the things I like about C sharp is their use of attributes, > >where you can define getters and setters on an attribute, but > >otherwise the attribute is simply used as if it were a public one. > > Eiffel does this. It was one of the first things to make me say "Cool!" > when I started looking into it. > > bhahn at transoft.mmangle.net <-- unmangle address to reply Object Pascal does that as well. From peter at engcorp.com Fri Mar 29 15:10:15 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 15:10:15 -0500 Subject: Newbie: List of instances? References: <3CA4C09B.D9D15464@bellsouth.net> Message-ID: <3CA4CA27.F00B91BA@engcorp.com> Jeff Layton wrote: > > a = [] > a[0] = Bob( 'localhost' ) > IndexError: list assignment index out of range Please always cut and paste the actual traceback into the message so we can see what the interpreter really says. (In this case it's okay though.) You can't assign to the first entry because the list is empty. You need to append to the list, to let it grow as needed, sort of like you tried here: > I also tried it this way, > > a = [] > a.append = Bob('localhost') That won't work, because append is a method so you have to pass the argument in brackets: a.append(Bob('localhost')) > and I get the error message: > > a[0] = Bob( 'localhost' ) > IndexError: list assignment index out of range That's not the error message you would get from the a.append attempt you did. That would have said this: >>> a.append = Bob('localhost') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object attribute 'append' is read-only So always cut-and-paste errors into emails... -Peter From bernie at 3captus.com Wed Mar 13 19:26:17 2002 From: bernie at 3captus.com (Bernard Yue) Date: Thu, 14 Mar 2002 00:26:17 GMT Subject: possible string.strip memory leakage References: <3C8FEDFB.666F1187@3captus.com> Message-ID: <3C8FEE9E.158C175D@3captus.com> Bernard Yue wrote: > Mike Brenner wrote: > > > There might be a memory leak in string.strip. > > > > I wrote a python function to strip blanks off the left and right of a string. When I discovered string.strip, I replaced the call to my version with string.split, and I got a large memory leakage. When I put the call back to calling my python function, the memory leakage went away. > > Did happen to me. So we need your Python version and OS you are running. > My mistake. Didn't happen to me (not did happened as stated above) Bernie From stephen at xemacs.org Mon Mar 4 11:36:29 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 05 Mar 2002 01:36:29 +0900 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87sn7g2stu.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Huaiyu" == Huaiyu Zhu writes: >> [1] Ie, Python language or character text. It might be >> convenient to have an octet-string primitive data type, in >> which you could put EUC-encoded Japanese or Java byte codes. Huaiyu> What's the difference between this and a raw string (a Huaiyu> byte sequence) that you can translate into any other Huaiyu> encoding? None, in representation.[1] However, it would not be a string in the sense you know it in Python: you can't concatenate it, you can't iterate over it, all you can do is read it, write it, access octets (which are not characters), or turn it into something else that you can do something with. Consider: does it make sense to concatenate a string of Java byte codes with a string of English text? Footnotes: [1] It might make sense to have a special representation for it in source as a subset of the Unicode "private space". But that's going way afield. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From cjw at sympatico.ca Sat Mar 9 16:57:56 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 09 Mar 2002 16:57:56 -0500 Subject: range Failure? Message-ID: <3C8A8564.E2F005AA@sympatico.ca> An HTML attachment was scrubbed... URL: From jason at jorendorff.com Mon Mar 4 00:26:07 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Sun, 3 Mar 2002 23:26:07 -0600 Subject: How can I use a foreign language char in Swing In-Reply-To: Message-ID: > I installed J2SDK 1.4.0 several days ago. I need to get some strings from > database which stored in GB2312 encode method, and display it > using Swing. I > got correct result in Windows2000(Use China as default region and > GB2312 as > encode method.) While I??run it on Windows(English Edition), all I can see > is ?????. > > What should I do? I think ResourceBoundle can't help me. Is there > any other > method can help me? (grin) It seems you're on the wrong newsgroup for this. I'm not sure exactly what's happening. Here are two possibilities. 1. Missing Fonts. Seems unlikely. But if this is the problem, it's easy to fix. :) 2. Encodings. Perhaps this is happening: the database innocently sends you some bytes, and Java must convert those bytes into a String. To do this, it must guess which encoding is appropriate. Java makes the best guess it can: your operating system's default encoding. Sometimes this is wrong, as you've discovered. In this case, you can usually fix the problem by telling Java which encoding to use. It all depends on where you're getting the string. Try this: when you run the program, specify -Dfile.encoding=gb2312 as an option to java. This might or might not work. I'm not sure all JVMs support the file.encoding property. It doesn't seem to be very well documented. It would be better to get the raw bytes out of the database (in a byte[] array) and convert them to String by yourself, thus: String correctString = new String(bytes, "gb2312"); Several Java standard library classes allow you to specify which encoding to use: String, InputStreamReader, and OutputStreamWriter, for example. You should specify the encoding whenever possible! This helps avoid the kind of bug you're currently struggling with. But perhaps both of my guesses are wrong. In any case, good luck! ## Jason Orendorff http://www.jorendorff.com/ From robin at jessikat.fsnet.co.uk Fri Mar 22 11:49:24 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 22 Mar 2002 16:49:24 +0000 Subject: how do i get RGB from HEX? References: Message-ID: In article , G. Willoughby writes >Hi, > i have been trying to do this for to long now, i know there is an easy >way, please somebody put me out of my misery! i need to get the RGB value of >a HEX number (eg, #DCDCDC). can anyone help? > >thanks, > >G. Willoughby > > split into pairs after stripping the # >>> def rgb(h): ... n = eval('0x'+h[1:]) ... return (n>>16)&0xff, (n>>8)&0xff, n&0xff ... >>> rgb('#DCDC0a') (220, 220, 220) >>> rgb('#DCDC0a') (220, 220, 10) >>> I'm sure there's probably some better way, but the above works. -- Robin Becker From cliechti at gmx.net Thu Mar 28 21:08:14 2002 From: cliechti at gmx.net (Chris Liechti) Date: 29 Mar 2002 03:08:14 +0100 Subject: chat server References: Message-ID: Henning Peters wrote in news:B8C97068.C30E%pete at dexterslab.de: > hi pythonists, > > i am planning to write a small chat server that uses select() in > python. multiple clients should be able to connect and chat wih each > other - like on a normal chatserver, just asynchronous... > > my current problem is, that i have no clue how to implement the > communication between the sockets (a chat message should be > directed to all other connected clients). just maintain a list of client sockets. when you recveive data from one distribute it to the others in a for loop over the list. its possible to add the server socket to the "possible readers" list of select so that you can accept new connections without problems. done that been there - but i won't spoil your fun by sending my code ;-) unless you relay want. > is this possible to implement with select() or should it be better to > use the good old fork() each time, a client connects and implement > interprocess communication via pipelines or shared memory?! There is also a threading module, i don't think you realy want separate processes. but it works fine with select. > btw: does anybody knows a good documentation about select() and related > themes - i've already read > http://www.nightmare.com/medusa/programming.html. you may be interested in this too: http://py-howto.sourceforge.net/sockets/sockets.html > bye, > henning peters > > -- Chris From geoff at gerrietts.net Thu Mar 7 13:47:23 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 7 Mar 2002 10:47:23 -0800 Subject: CP4E was Re: Deitel and Deitel Book... In-Reply-To: References: <31575A892FF6D1118F5800600846864DCBCD8B@intrepid> Message-ID: <20020307184723.GB29379@isis.gerrietts.net> Quoting Roman Suzi (rnd at onego.ru): > On Thu, 7 Mar 2002, Simon Brunning wrote: > > > > From: Geoff Gerrietts [SMTP:geoff at gerrietts.net] > > > For the space of around three years, a child is immersed almost > > > constantly, from waking to sleep, and even sometimes while asleep, in > > > language. For those first three years, the child is almost completely > > > incapable of making him or herself understood. > > Are you sure? My daughter makes herself understood by all available > means. She built her own dictionary which we, parents, learned. > What is interesting, she uses (internally) a hash table to > convert from our language to her almost instantly... I think I've answered this complaint with the original post several times already, so I'm not going to do it again. As a nutshell, I'll say that the range concepts a child is capable of expressing at this age is much smaller than the range of concepts a child experiences -- barely one percent of the feelings you see flashing across the child's face make it into language, spoken or gestured. That qualifies to me as "almost completely incapable of making him or herself understood." > I do not remember who told me this, but it seems that students > better learn from poorly constructed lectures than perfect ones. > Because, they need to be _active_ in constructing their own system > rather than _passively_ "eat" readymaid knowledge frames. This is an interesting point, and might be wrapped back into our developing idea of a pedagogy. Building in defects might not be the best idea, because that's likely to lead to criticism and even dismissal by those who recognize the errors. But building in problems that expect the student to engage the material and fill in the blanks, that's something of an admirable goal. Thanks, --G. -- Geoff Gerrietts "Democracy is a form of government that substitutes geoff at gerrietts dot net election by the incompetant many for appointment http://www.gerrietts.net/ by the corrupt few." --George Bernard Shaw From h_schneider at marketmix.com Thu Mar 28 11:06:46 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Thu, 28 Mar 2002 17:06:46 +0100 Subject: Sendkeys without Scripting Host Message-ID: Hi, is there a possibility to use sendkeys() without scripting host installed? Are there any extentions available for python? Thanks for your answers! Harald From cliechti at gmx.net Mon Mar 18 16:21:54 2002 From: cliechti at gmx.net (Chris Liechti) Date: 18 Mar 2002 22:21:54 +0100 Subject: Help Required References: Message-ID: surajsub at netscape.net (Surajsub) wrote in news:cf4a8ef1.0203180955.55313155 at posting.google.com: > Chris Liechti wrote in message > news:... >> surajsub at netscape.net (Surajsub) wrote in >> news:cf4a8ef1.0203151724.440b67ac at posting.google.com: > Ok here is the code..I just need a set of uid's and other similar > parameters which i need to feed to ldap.these are just a dummy set > of values. > ============================================================= > #!/usr/local/bin/python > import string > > MIN=0 > MAX=25 > UID="UID" > val="" > for x in range(MIN,MAX,1): 1 is the default step, you don't need to write it explicit. > if( x == 0 ): > x=str(x) > val=UID,x+',' > st=string.join(val,"") > st=string.strip(st) > print st, > elif(x > 0 ): > x=str(x) > val='UID'+x+',', > st=string.replace(string.join(val,""),' ','') > print st, > ========================================================== > > The output that this script produces is > > UID0, UID1, UID2, UID3, UID4, UID5, UID6, UID7, UID8, UID9, UID10, > UID11, UID12, UID13, UID14, UID15, UID16, UID17, UID18, UID19, UID20, > UID21, UID22, UID23, UID24, > > > Notice the spaces between the , and the UID > ============================================ > I need to get rid of these spaces.How do i do it.. > > Thanks > that's because you use "print x," the coma does it... either use sys.stdout.write() or prepeare the entire string and print it later i.e. store all your ids and join the list afetwards. uids = [] for x in range(MIN,MAX): uids.append("UID%d" % x) print ','.join(uids) or with map & lambda: print ','.join(map(lambda x, "UID%d", range(MIN,MAX))) -- Chris From zihong at earthlink.net Sat Mar 9 15:40:55 2002 From: zihong at earthlink.net (Zihong Lu) Date: Sat, 09 Mar 2002 20:40:55 GMT Subject: win32 extension: rare PythonService problem Message-ID: I have run into a rare case, wonder if it happened to anyone before. I use the win32 extension PythonService to write a windows service for our project. The service runs fine on most NT, win2k machines. Recently our customers reported that for some PCs, the command "python MyService.py start" returned as usual, no traceback, but the service did not start at all. When I looked into it, I found that the constructor __init__ of the top class MyService(derived from win32serviceutil.ServiceFramework) did not get called at all, not to mention the function SvcDoRun() was not called. So it excluded the possibility that our application functions had problem. The environments are: Python version: 2.1.1 win32 extension: win32all-145.exe from http://starship.python.net/crew/mhammond/win32/Downloads.html OS: NT (with service pack 6), win2k (with service pack 2) hardware: Intel celeron, 128 MB ram. (I am not sure if they are related, but I did see 2 celeron machines ran into this problem, put them here just in case) Can someone please tell me what went wrong in these cases? Thanks in advance. -Zihong From com-nospam at ccraig.org Wed Mar 13 12:53:50 2002 From: com-nospam at ccraig.org (Christopher A. Craig) Date: 13 Mar 2002 12:53:50 -0500 Subject: Why I think range is a wart. In-Reply-To: References: Message-ID: Gon?alo Rodrigues writes: > For starters, range (and xrange) is a perfectly sensible, reasonable and > useful built-in. But the biggest use I make of it is in iterating through > a list, e.g. as in > > for index in range(len(mylist)): > > > and in the body I need to make use of the indexes. I am not > sufficiently qualified to say if this is Pythonic or not, but I find > myself doing this quite often. I don't understand how range is a reasonable and useful built-in if this use is not. If you have a list [2, 3, 5, 7, 11] and you want to iterate through it you don't need range: for item in list: If, on the other hand, you want to iterate though the indicies of said list rather than the items themselves you need to come up with some way to generate a zero based list of integers up to one less than the size of the list (i.e. a list of indicies). When you create this list you aren't doubling information that the list already has. A list does not contain a list of indicies into itself. The list knows its elements, in order, and how many elements it has. From this you can generate a list of indicies, but there are no 'keys' stored in a list object like there are in a dictionary. To go from the information that is stored in the list (an ordered list of elements, and the size of said list) to the information you need to iterate through indicies (an ordered sequence of indicies valid for the given list) you need to take the length of the list (N), and create a new list of N integers from 0 to N-1. 'range(len(mylist))' says precisely that. I don't see how this is the least bit kludgey. .keys() and .items() methods on lists seem odd to me. That is inforamtion that the list does not contain. Sure it can easily be generated given information the list does contain, but why can't the programmer generate it himself from the same information? -- Christopher A. Craig Is Peal Better Than Python? No, no. Quicker, easier, more seductive. From jcromwell at ciena.com Sat Mar 16 12:29:53 2002 From: jcromwell at ciena.com (Cromwell, Jeremy) Date: Sat, 16 Mar 2002 09:29:53 -0800 Subject: Help Required Message-ID: Like the others, I'd like to see the code, but I'll take a shot at your problem. I'm guessing that your problem is printing. Here's an example I created using the interpreter that might help. >>> uid1 = 'user1' >>> uid2 = 'user2' >>> uid3 = 'user3' >>> print uid1,uid2,uid3 user1 user2 user3 >>> print uid1, uid2, uid3 user1 user2 user3 >>> print uid1 , uid2 , uid3 user1 user2 user3 >>> print uid1+uid2+uid3 user1user2user3 >>> print "%s,%s,%s" % (uid1,uid2,uid3) user1,user2,user3 >>> print "%s%s%s" % (uid1,uid2,uid3) user1user2user3 >>> print "%s, %s, %s" % (uid1,uid2,uid3) user1, user2, user3 >>> print ",".join((uid1,uid2,uid3)) user1,user2,user3 >>> print ", ".join((uid1,uid2,uid3)) user1, user2, user3 >>> print "".join((uid1,uid2,uid3)) user1user2user3 >>> ids = uid1,uid2,uid3 >>> print ids ('user1', 'user2', 'user3') >>> type(ids) >>> ids = uid1+uid2+uid3 >>> print ids user1user2user3 >>> type(ids) >>> ids = "%s, %s, %s" % (uid1,uid2,uid3) >>> print ids user1, user2, user3 >>> type(ids) >>> ids = ",".join((uid1,uid2,uid3)) >>> print ids user1,user2,user3 >>> type(ids) Hope this helps. -Jeremy Cromwell -----Original Message----- From: surajsub at netscape.net [mailto:surajsub at netscape.net] Sent: Friday, March 15, 2002 5:25 PM To: python-list at python.org Subject: Help Required Hi, I am a newbie to Python and am pretty fascinated by it power and speed.I am however puzzled in trying to write this script. The script builds a list of userids to be fed to ldap and it is supposed to be uid1,uid2,uid3....and so on.( Notice there is no space) However when i am trying to create the uid list it gives uid1, uid2, uid3,...and so on. how do i get rid of this leading space if u would call it.. string.lstrip does not work either. what am i doing wrong? TIA Suraj -- http://mail.python.org/mailman/listinfo/python-list From prouleau at impathnetworks.com Tue Mar 12 13:08:30 2002 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Tue, 12 Mar 2002 13:08:30 -0500 Subject: Can we use print to print to more than sys.stdout? Message-ID: <3C8E441E.4D64C8DA@impathnetworks.com> #1) Is it possible to change print behavior to make it print to several streams? I know it is possible to change the stream where print prints by changing the value of sys.stdout, like this: import sys f = open('somefile', 'w') sys.stdout = f print 'whatever to that file' f.close() #then restore stdout sys.stdout = sys.__stdout__ But is it possible, for example, to make it print both to stdout *and* some file? #2) Is it also possible to define an object that would behave like a file and that would do the printing itself to wherever required? Thanks! Pierre Rouleau From anton at vredegoor.doge.nl Thu Mar 14 05:40:57 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 14 Mar 2002 11:40:57 +0100 Subject: Is Python an object based programming langauge? References: Message-ID: On 14 Mar 2002 01:55:03 GMT, bokr at oz.net (Bengt Richter) wrote: >Sorry, but that is not true of Delphi. Did you ever work Delphi from >the command line? You can easily write console apps that do not use GUI windows: >--- > [17:10] V:\Dwk\bare>type bare.dpr > program bare; > {$APPTYPE CONSOLE} > uses sysutils; > begin > Writeln('Hello World ;-)') > end. >From the Delphi IV docs of a similar (console program): Aside from its simplicity, this example differs in several important ways from programs that you are likely to write with Delphi. First, it is a console application. Delphi is typically used to write Windows applications with graphical interfaces; hence, in a Delphi application you would not ordinarily call Writeln. Moreover, the entire example program (save for Writeln) is in a single file. In a Delphi application, the program heading?the first line of the example?would be placed in a separate project file that would not contain any of the actual application logic, other than a few calls to methods defined in unit files. Well, please don't add to the confusion about Delphi's capabilities ;-) >You could put someone off that might like it ;-) Well I like Delphi myself and I don't want to put anyone off! However I just wanted to state that its very unnatural in Delphi to write a console app. For example open the IDE and click file-new- and then try to click on something that starts a new console application -). I do not want to criticize Delphi, I do want to state that object oriented programming can be so tightly coupled to GUI style program design that it can give the (false) impression that GUI style program design and OOP are unavoidably connected. Anton. From cyberlync at yahoo.com Sat Mar 30 18:06:03 2002 From: cyberlync at yahoo.com (Eric Merritt) Date: Sat, 30 Mar 2002 15:06:03 -0800 (PST) Subject: C-API, Tuple return value refcounts In-Reply-To: Message-ID: <20020330230603.83615.qmail@web13004.mail.yahoo.com> Hello All, I have searched the archives fairly well and not found an answer to this question, so I thought I would post it to the list. I believe that this question stems, to some extent, from a lack of understanding concerning the reference counting system, so please keep that in mind when you answer. I am using the C-API to interface with a library function. Its a fairly simple interface in that it makes a call and returns a PyTuple to the calling process. It make no use of borrowed references. My question is this; When I return the new tuple type, 1) Do I need to increment the reference count before I return it (Keeping in mind that the tuple type is not reference out side of this function, it is simply a return value). 2) Do the PyObject values that make up the tuple type need their reference counts incremented?. In the above case I do not believe that they need to be incremented. Because according to the documentation the reference counts are incremented automatically when the PyObjects are created using the built in api functions. This, of course, creates another couple of questions. 1) Do I need to decref the tuple before it is returned? 2) Do I need to decref the objects comprising the tuple? I truly hope this question is not considered list clutter I have done my best to research the answers before I posted, but I am uncomfortable with my current understanding in this regard. Thank you, Eric __________________________________________________ Do You Yahoo!? Yahoo! Greetings - send holiday greetings for Easter, Passover http://greetings.yahoo.com/ From aahz at pythoncraft.com Tue Mar 26 10:05:19 2002 From: aahz at pythoncraft.com (Aahz) Date: 26 Mar 2002 10:05:19 -0500 Subject: Optimizations (was Re: reduce vs. for loop) References: Message-ID: In article , wrote: > >Just out curiosity, >why is fact2 a bit faster than fact1? > >def fact1(n): > return reduce (operator.mul, range(1L,n + 1)) > >def fact2(n): > result = n * 1L > for i in range(1 , n): > result *= i > return result Try this: def fact3(n): mul = operator.mul return reduce(mul, range(1L, n+1) ) But pay attention to my .sig below..... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From gh_pythonlist at gmx.de Wed Mar 13 19:16:56 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Thu, 14 Mar 2002 01:16:56 +0100 Subject: Has Mark Hammond attained pariah status yet? In-Reply-To: <3C8FF468.408183B2@engcorp.com> References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> <3C8F1D74.10802@mxm.dk> <20020313092857.4765dd0d.logiplexsoftware@earthlink.net> <3C8FF468.408183B2@engcorp.com> Message-ID: <20020314001655.GA652@lilith.hqd-internal> Le 13/03/02 ? 19:52, Peter Hansen ?crivit: > Gerhard H?ring wrote: > > > > There are plenty of free C compilers for Windows: mingw, Borland, > > lcc-win32. lcc-win32 even comes with an IDE. > > > > If you dig long enough on the Microsoft site, you can (at least you > > could at one time) even download a commandline version of the MS > > compiler. > > As best I recall, that version is wholly unsuitable for real production > use. I believe it is the version without optimization (not the > "professional" edition) and the code it produces, when last I looked, > is _significantly_ larger and slower than the real version. > > Okay for hacking, not for shipping. You're of course right. Has anybody tried their .NET SDK, yet. Does it contain a usable commandline version of VC++7? Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 8.8 ?C Wind: 2.9 m/s From skip at pobox.com Fri Mar 8 08:03:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 8 Mar 2002 07:03:18 -0600 Subject: PEP Parade In-Reply-To: References: Message-ID: <15496.46742.14715.837893@12-248-41-177.client.attbi.com> Roman> Just one comment about Roman> PEP 270 - uniq method for list objects Roman> maybe adding dict <-> list conversion functions will make this Roman> automatically? Nothing new is necessary since 2.2 was released: >>> mylist = [1,2,3,5,6,6,9,9,1,2,3,4] >>> mydict = dict(zip(mylist,mylist)) >>> mydict {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 9: 9} >>> mydict.values() [1, 2, 3, 4, 5, 6, 9] -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From sjmachin at lexicon.net Sat Mar 23 16:20:11 2002 From: sjmachin at lexicon.net (John Machin) Date: 23 Mar 2002 13:20:11 -0800 Subject: simple question References: <2UVm8.30655$J54.1855090@news1.west.cox.net> Message-ID: "Terry Reedy" wrote in message news:... > "Christopher Palmer" wrote in message > news:mailman.1016868517.25439.python-list at python.org... > > > Let's say I have a variable called a > > Actually, you have a name 'a'. > > > and a contains an integer, say 4522 > > and the name is bound to an int, conventionally written 4522. > > > and I want 4, 5, 2, and 2 to be items in a list instead of an > integer... > > Do you want the list to contain 4 ints (answer given by Johann as: > map(int, str(a)) > ) or 4 digits: > ''.split(str(a)) > ? > > Terry J. Reedy I see no 4 digits here. Following are some results of actually RUNNING some code at the Python command line (version 2.2, Win32): OP's sample input: >>> a = 4522 Your suggestion: >>> ''.split(str(a)) [''] What you probably meant: >>> str(a).split('') Traceback (most recent call last): File "", line 1, in ? ValueError: empty separator One possible working solution: >>> list(str(a)) ['4', '5', '2', '2'] From tismer at tismer.com Tue Mar 5 04:26:30 2002 From: tismer at tismer.com (Christian Tismer) Date: Tue, 05 Mar 2002 10:26:30 +0100 Subject: Stackless Platform Independence? References: <3C829AA2.1B21E205@arakne.com> <3C838150.97A86F52@arakne.com> <7xzo1om5wt.fsf@ruckus.brouhaha.com> Message-ID: <3C848F46.7000804@tismer.com> Paul Rubin wrote: > Christian Tismer writes: > >>Makes pretty much sense to me. >>Stackless can provide light-weight threads to all platforms. >>There is no need to use OS threads unless you need it >>for I/O. >> > > Do you think it's feasible to modify Python to use non-blocking i/o > everywhere, and then simulate blocking in Stackless? I.e. when a > microthread does an i/o operation, Python would start the operation > asynchronously, and the Stackless microthread scheduler would block > the microthread til the i/o operation actually completes (detected > using select or SIGIO). This is roughly how I understood Frederic's idea. -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Kaunstr. 26 : *Starship* http://starship.python.net/ 14163 Berlin : PGP key -> http://wwwkeys.pgp.net/ PGP Fingerprint E182 71C7 1A9D 66E9 9D15 D3CC D4D7 93E2 1FAE F6DF where do you want to jump today? http://www.stackless.com/ From bokr at oz.net Wed Mar 13 16:55:11 2002 From: bokr at oz.net (Bengt Richter) Date: 13 Mar 2002 21:55:11 GMT Subject: RFC PEP candidate: q''quoted ? References: Message-ID: On Tue, 12 Mar 2002 18:24:40 -0500, "Clark C . Evans" wrote: >On Sun, Mar 03, 2002 at 09:50:58AM +0000, Bengt Richter wrote: >| Problem: How to put quotes around an arbitrary program text? > >I would suggest that this is done via indentation, like >YAML. With indentation you don't need to have an end >delimiter. > Unless you want the option of excluding the last EOL. For line-oriented stuff it would be nice though, especially for doc string readability. Actually a blank leading line is not bad when you print a big doc string anyway... Thanks for making me aware of YAML. Regards, Bengt Richter From sjmachin at lexicon.net Wed Mar 6 22:07:57 2002 From: sjmachin at lexicon.net (John Machin) Date: 6 Mar 2002 19:07:57 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: "Bjorn Pettersen" wrote in message news:... > > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > Subject: PEP 284, Integer for-loops > > Thanks for writing the PEP. > > I see this as a general proposal for a range syntax, and I disagree with > it because: > > - it doesn't handle the general range issues, i.e. step value, > and if we had to add yet another syntax to get general ranges > it would be too confusing. Agreed. Let's generalize the existing syntax. Existing: for in : Proposal: For a splendid blast from the past, let's take a leaf out of ALGOL 60's book. for in : where the elements of can be of 3 different kinds: (1) (2) ::= [step ] until (3) ::= while Lets you do things like for k in 0,1,2, 5 step 5 until 25, k * 2 while k <=1024: > > - I would like range objects to be first class, ie. I would want > to be able to pass ranges to functions, return them from > functions, and do all the other things one can do with first > class objects. I don't understand this. range and xrange *are* first-class objects. You can do all of those things. > > - It doesn't make the general case trivial, i.e. > for 0 <= i < len(mySequence) is not much better than > for i in range(len(mySequence) and is more verbose than > for i in len(mySequence). > for i in 0, i+1 while i < len(mySequence): for i in 0 until len(mySequence) - 1: Hmmm, ... maybe not. From sdm7g at Virginia.EDU Fri Mar 1 13:44:31 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Fri, 1 Mar 2002 13:44:31 -0500 (EST) Subject: Swapping out sys.stdout globally In-Reply-To: <15487.41982.968248.121857@12-248-41-177.client.attbi.com> Message-ID: On Fri, 1 Mar 2002, Skip Montanaro wrote: > > Kevin> sys.stdout = NewFile() > Kevin> sys.stderr = NewFile() > > Kevin> However, I have some logging routines in a separate package that > Kevin> already have their own references to sys.stdout and sys.stderr > Kevin> which are unaffected by this. > > Sounds like they use something like > > from sys import stdout,stderr > > The best solution there would be for those packages to import sys in the > usual fashion: > > import sys > > and refer to sys.stdout & sys.stderr. > Skip's advice is sound. However, if there's some reason you can't do that, if you're on unix then you can use posix.close, posix.open & posix.dup2 to redirect the posix file underneath the python file object. Something like: new_file = open( file, 'w' ) fd = sys.stdout.fileno() os.close(fd) os.dup2( new_file.fileno(), fd ) Don't use sys.stdout.close(), because it will mark the Python file object as closed. os.close() closes the real os file but doesn't mark the python file object as closed. -- Steve Majewski From jkraska at san.rr.com Fri Mar 29 00:46:19 2002 From: jkraska at san.rr.com (Courageous) Date: Fri, 29 Mar 2002 05:46:19 GMT Subject: Python & Poetry References: <5515F24370BCB753.DA7CF91464346EF6.E3A577CFA6882D82@lp.airnews.net> <3CA123ED.805A2B72@cosc.canterbury.ac.nz> <7396d2b2.0203271554.5a564e1b@posting.google.com> Message-ID: <5908au87qfhc7git6mlf7uhq8qnmk829ro@4ax.com> > The greatest compliment I've ever been paid, was when someone said of my > code: "I picked it up, and I knew what it did". As a youth, one of my great professional prides was writing 100,000 lines of code in a year. Older and wiser now, I now pride myself on having once reduced someone else's 35,000 line program to about 6,000 lines. To this day, however, I'm not sure if anyone quite knows what I did. :) C// From outros at kyky.zzn.com Mon Mar 4 11:09:43 2002 From: outros at kyky.zzn.com (Bordeaux Buffet) Date: Mon, 4 Mar 2002 13:09:43 -0300 Subject: Não Compre... Alugue! Message-ID: An HTML attachment was scrubbed... URL: From tejarex at yahoo.com Wed Mar 27 17:15:48 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Wed, 27 Mar 2002 22:15:48 GMT Subject: problems with circular references References: Message-ID: "jimh" wrote in message news:a7tbd4$qc7$1 at web1.cup.hp.com... > I am working on python code that consist of quite a few files (about 50; > each file contains one class). All errors returned by functions are numeric > and are defined in the individual files. There is a MessageCatalog.py class > which will map these numbers into strings. This MessageCatalog.py has to > import all of the 50 other files to have access to their error numbers. So > far, so good - no problems yet. > > Here is the problem: Most of these 50 classes need to use the MessageCatalog > themselves. This means, of course, that classA imports MessageCatalog which > imports classA. This doesn't work very well. > > Does anyone have ideas on how to deal with this situation? I would probably follow the standard Python idiom of using exceptions instead of numeric error codes, and look at standard library modules for precedents. Terry J. Reedy From logstx at bellatlantic.net Sat Mar 9 16:35:18 2002 From: logstx at bellatlantic.net (logistix) Date: Sat, 09 Mar 2002 21:35:18 GMT Subject: [ANN] UNBABTIZED - The language References: <3c8a4042.46048234@news.t-online.de> Message-ID: So I take it you're a fan of bf as well? http://home.wxs.nl/~faase009/Ha_bf_inter.html From pedronis at bluewin.ch Tue Mar 12 16:23:33 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Tue, 12 Mar 2002 22:23:33 +0100 Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: <3c8e74d9$1_3@news.bluewin.ch> Martin v. Loewis wrote in message m3adtdbjbz.fsf at mira.informatik.hu-berlin.de... > "Samuele Pedroni" writes: > > > And what datapoints we acquire through the article? > > I think the article states a number of facts properly: > properly? YMMV. You have restated and read them properly . regards. From mmillikan at vfa.com Wed Mar 6 08:46:20 2002 From: mmillikan at vfa.com (mmillikan at vfa.com) Date: 06 Mar 2002 08:46:20 -0500 Subject: Nested scopes: design or implementation? References: Message-ID: <3czdq05v.fsf@vfa.com> Note that the object is shared by each of the inner objects: text = "random text" def function(): def attribute( bindNow = text): print bindNow function.attribute = attribute Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> function() >>> function.attribute() random text >>> function.attribute >>> function.attribute.func_code >>> function() >>> function.attribute.func_code >>> text = 'new random text' >>> function() >>> function.attribute >>> function.attribute.func_code Mark Millikan From sholden at holdenweb.com Fri Mar 29 12:18:54 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 29 Mar 2002 12:18:54 -0500 Subject: Default arg for dict() (was Re: Sorting distionary by value) References: <3CA295CC.9682E2DB@engcorp.com> <0_Zo8.16784$Ou.11910@atlpnn01.usenetserver.com> Message-ID: "Chris Gonnerman" wrote in message news:mailman.1017410389.28258.python-list at python.org... > ----- Original Message ----- > From: "Steve Holden" [...] > > > > However, Bength Richers suggestion: > > > > > empty_dict_with_default = {:default} > > > with_one_key_value_pair = {:default, key:value} > > > > > > A little tweak in the grammar might do it? > > > > might well suffice, and wouldn't require huge changes to the grammar. > > But do we REALLY need it? Another new semantic feature, another altered > basic behavior. Python is so cool because it is compact (linguistically) > and easy to grasp. Each new use of punctuation makes it more complex and > Perl-like. > Well, I'm against many changes to the language precisely because of the code-breakage they induce. In this particular case, however, it appears to me that the change is totally backwards-compatible because a dictionary literal constructor with no default value stays the same, so no code breakage would result. > Writing a class to simulate a dictionary with default value is simple, > and left as an exercise for the reader :-) I agree it's possible. Of course, we could even write a Python interpreter in Python if we wanted to. Then there'd be no need for the interpreter either... vanishing-up-my-own-orifice-ly y'rs - steve From borcis at geneva-link.ch Sat Mar 23 07:51:13 2002 From: borcis at geneva-link.ch (Boris^2) Date: Sat, 23 Mar 2002 13:51:13 +0100 Subject: New SIG on logic/CLP programming in Python References: Message-ID: <3C9C7A41.9F84992E@geneva-link.ch> Nicolas Chauvat wrote: > > Now, what if you need logical programming? Use pyprolog. And copy > your data back-and-forth from prolog-space to python space. Or look > at Mozart/Oz. Yeah, it's all there too: procedure, functions, objects, > concurrency, logic, constraint-propagation, even distribution and > security. > > Right, but the syntax is... difficult. Rather. And makes one wonder if the way to go would not be to compile python source syntax to the Oz or Erlang VM... while adding to it something in the way Screamer adds to Common Lisp. (Erlang has a nice syntax, BTW). Another thing I am missing in python is Prolog-type metaprogramming and/or lisp-type macro; first step would be S-expressions; the closest python provides are the syntax trees from the parser module, but... well, they really don't provide a similar facility. Now what about defining a two-way translation to a syntax Lisp or Scheme systems could read as S-expressions that could then be intelligently manipulated by lisp-technology macros ? > I am looking for interested people to form a Logic-SIG or CLP-SIG. Count me in, especially for useless commenting :) Regards, Boris Borcic -- Python >>> filter(lambda W : W not in "ILLITERATE","BULLSHIT") From eppstein at ics.uci.edu Wed Mar 6 18:35:06 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 15:35:06 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , Steve Lamb wrote: > I fail to see how it is is greader readability or understanding when the > current method is both. I diagree that the current method has both, or either. I don't know about you, but I find "for x in range(n-1,-1,-1)" to be a difficult to read and difficult to understand way of obfuscating a simple loop over the numbers 0 to n-1 in reverse order. I think "for n > x >= 0" would be much simpler. From gcordova at hebmex.com Thu Mar 28 17:44:48 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Thu, 28 Mar 2002 16:44:48 -0600 Subject: mutliple search and replace Message-ID: <19650FF08A99D511B19E00B0D0F0632301D689F7@SRM201002> > > hey Gustavo, > > actually i wished to do the replacement in one sweep and > occuring in any > order.. to avoid problems.. is it easy? > > cheers > Hmmm... it becomes a bit more complicated. Say, you have this huge string: >>> HugeString = """ ... lotsa text ...""" And, your dictionary with search items and replacements: >>> ReplacementsDict = { "find":"replace", ... } So, you need to find *any* key, so you can use a regexp: >>> import re >>> rxFindKey = re.compile("|".join(ReplacementsDict.keys()), re.S) To do all the replacements. just do a loop: >>> match = rxFindKey.search(HugeString) >>> while match: ... found = match.group(0) ... HugeString = HugeString.replace(found, ReplacementsDict[found]) ... match = rxFindKey.search(HugeString) So, after the loop, you've got all that done. Good luck! -gustavo From claird at starbase.neosoft.com Wed Mar 20 10:03:34 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 20 Mar 2002 09:03:34 -0600 Subject: Java and Python for embedded applications (was: Java and Python) References: <3C96DBB4.6040109@pobox.com> <3C981961.9F5E5383@engcorp.com> <3C982EDA.2050408@pobox.com> <3C9836B8.150B4DA@engcorp.com> Message-ID: <7F4A1C2050937632.B0420410CEF7D39A.B15EB10EEC873652@lp.airnews.net> In article <3C9836B8.150B4DA at engcorp.com>, Peter Hansen wrote: . [lots of other entirely reasonable stuff] . . >If by "embedded" you mean truly embedded systems, with >microcontrollers in dedicated-purpose systems and generally >limited user interfaces, Python is somewhat less suitable >than Java, since there are the KVM and similar Java variants >focussed specifically in this area. Python is in use in >some PC104-based embedded systems (that's what we use it >for in the embedded area) and has also been ported (in >early forms) to the Palm Pilot, for example. The language >itself is perhaps slightly less effective for embedded >systems in some respects, because it is higher level than >Java. If your constraint is performance and code size, >Java might be better (but then, C might be much much >better...) whereas if development time and cost is the >constraint, Python may well be the winner. (This is . . . I'm unconvinced about even the mild Java-is-smaller-and-faster claim. While I don't keep up with embedded Java now, there certainly have been times in the recent past when its start-of-the-art has been ... disappointing in these regards. Python was competitive, and sometimes better. If you like Python's productivity, but put a premium on performance and code size, several alternative languages might give more satis- faction. I expect to be presenting Lua in this context over the next few months. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From hughett at mercur.uphs.upenn.edu Wed Mar 13 10:19:15 2002 From: hughett at mercur.uphs.upenn.edu (Paul Hughett) Date: 13 Mar 2002 15:19:15 GMT Subject: Question about scientific calculations in Python References: Message-ID: Martin Kaufmann wrote: : On 12 Mar 2002 19:25:50 GMT, Paul Hughett : wrote: :> http://www.uphs.upenn.edu/bbl/bblimage : Thanks, I had a look at the [bblimage] webpage. It really looks interesting : to me. But the basic calculations really faster than the one in SciPy or : Scientific Python? The calculations in bblimage are probably about as fast as you can make them without dropping into assembly and hand-tweaking for a particular architecture. I haven't looked much at SciPy, and don't know how much effort they've put into performance and how the speed compares. :>It really depends on how many diffraction patterns you need to do. It :>doesn't make sense to spent two months learning C to save even 99% of :>a ten-hour computation that you're going to do only once. (Unless :>your real purpose is to learn C.) On the other hand. if you have to :>do a few hundred patterns, then it might be a good investment of time. : I will have to do it several times I guess... So 99% improvement in : speed would really be nice. I choose 99% above to make the point that even huge improvements don't matter much for a job you're running only once. A 10x improvement would be more typical for a Python-to-C conversion. : How do you glue C and Python together? Do you use any of the wrappers : (SWIG, weave etc.) or do you do it the hard way? I just didn't : understand the whole story about these PyObjects. I did it the hard way, because that lets me modify to Python interface to take advantage of Python's features and be cleaner and easier to use than the C interface. :>One general comment: The performance killer in many applications like :>this is doing the innermost loop in the interpreted language (Python, :>Matlab, etc). If you can recast your algorithm as operations on :>arrays rather than individual numbers, and your language does the :>implicit loops over the elements efficiently, you typically get 10x or :>so improvements in speed. : Do you mean the array calculation of NumPy? Yes. The loop over elements in NumPy is done in C (as far as I know) rather than in Python, so you get that 10x speedup I mentioned above. \begin{heresy} Have you considered doing this in Matlab, or its open-source clone Octave? Based on what little I know of your problem, it would seem quite well suited, since it already has efficient arrays, complex numbers, and FFTs embedded in a scripting language. \end{heresey} Paul Hughett From gerhard at bigfoot.de Fri Mar 15 16:09:01 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 15 Mar 2002 21:09:01 GMT Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: John Roth wrote in comp.lang.python: > Putting something into the start menu is dead easy. No, it isn't, unless you're only targetting one particular localization of one particular flavour of Windows. > Just put a link to the appropriate file into "c:Windows/Start > Menu/Programs" No. Frankly, such "installers" suck ***. There are appropriate Windows API functions and registry keys to determine to directory to install the start menu items in. > Putting an icon on the desktop is a bit more difficult. AFIK, that > has to go into the registry, Depends. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fredrik at pythonware.com Wed Mar 13 03:21:30 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 13 Mar 2002 08:21:30 GMT Subject: zlib vulnerabilities and python References: Message-ID: Robin Becker wrote: > Does the recent zlib double free vulnerability > > http://news.com.com/2100-1001-857008.html > > impact zlib.pyd? only if the guys implementing your C library decided to inter- pret "undefined behaviour" as "force the operating system to run code designed to take over the computer". dunno about MSVC; the CRT documentation only says that things like this may "cause errors". From philh at comuno.freeserve.co.uk Mon Mar 11 15:04:58 2002 From: philh at comuno.freeserve.co.uk (phil hunt) Date: Mon, 11 Mar 2002 20:04:58 +0000 Subject: Python on Windows soon forbidden by Micro$oft? References: <3C8C7C92.9C10A0B2@earthlink.net> <3C8C82D3.CA4220CA@earthlink.net> <3C8CAA83.9EBBC03E@engcorp.com> <924j8.19297$N7.4387774@ruti.visi.com> Message-ID: On Mon, 11 Mar 2002 15:28:05 GMT, Grant Edwards wrote: >In article <3C8CAA83.9EBBC03E at engcorp.com>, Peter Hansen wrote: >> Tim Hammerquist wrote: >> >>> Didn't you know? Microsoft invented Open Source! ;) >> >> No, that was Al Gore! > >Ya know, I've actually read the transcript of that interview. >He never claimed to have invented the Internet, only to have >been responsible for funding it. Of course Gore didn't invent the Internet. Everyone knows Microsoft did that. They also invented the web browser, the symbolic link, and robust multi-tasking operating systems. -- <"><"><"> Philip Hunt <"><"><"> "I would guess that he really believes whatever is politically advantageous for him to believe." -- Alison Brooks, referring to Michael Portillo, on soc.history.what-if From selectfincon at yahoo.com Sat Mar 16 13:55:21 2002 From: selectfincon at yahoo.com (Jim) Date: 16 Mar 2002 10:55:21 -0800 Subject: python shell References: Message-ID: Thanks Gerhard, I set the compatiblity to win 98 in the properties. Now the shell exits properly. Although at some point it would be nice to have this work under win xp mode without the compatiblity fix. Rgds, Jim Gerhard H?ring wrote in message news:... > * Jim [2002-03-14 18:51 -0800]: > > When I try to exit the python shell under windows XP > > it hangs. Is there some trick to this? > > Does this only happen if you start python from the start menu, but not when you > start it from a command prompt? If the answer to this question is yes, then you > can edit the shortcut to python.exe in the start menu. There should be a > checkbox "keep terminal window open after application has finished" or some > such. > > HTH, > > Gerhard From pan-newsreader at thomas-guettler.de Tue Mar 26 16:42:55 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Tue, 26 Mar 2002 22:42:55 +0100 Subject: xml config file to python object Message-ID: Hi! What is the easiest way to parse a xml config file to a python object. I would like to parse 2 sun moon to this: obj={'myconfig': [ { 'foo' : '2' } { 'bar' : ['sun', 'moon']} ] } I did it this weekend with a sax parser. Is there a way to pickle (serialize) any python object to xml and back? After using the sax parser I asked myself why not use a python file for the configuration? It is much easier. thomas From nospam at nospam.com Tue Mar 19 20:43:33 2002 From: nospam at nospam.com (Nigel-Fi) Date: Tue, 19 Mar 2002 20:43:33 -0500 Subject: Passing command line arguments when debugging with IDLE Message-ID: A newbe question from someone more familiar with devstudio type environments... I have a python program which takes command line arguments and i'd like to debug it with IDLE but I cant see how to specify them when I open the py file or run it within IDLE. thanks and regards, From vinay_sajip at yahoo.co.uk Wed Mar 20 20:54:53 2002 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 20 Mar 2002 17:54:53 -0800 Subject: ANN: Logging Module v0.4 released Message-ID: <2e37dc1.0203201754.50a15e80@posting.google.com> A new version of the proposed Python standard logging module (as per PEP 282) has been released. You can get all the information from http://www.red-dove.com/python_logging.html There is a download link at the top of that page, and there is quite a lot of new stuff including syslog and NT event log support, support for user defined levels and more! As always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Cheers Vinay Sajip Red Dove Consultants Ltd. Changes since the last version: ================================= Added level filtering for handlers. Return root logger if no name specified in getLogger. Added distutils setup.py script. Added formatter initialization in Handler.__init__. Tidied up docstrings. Added removeHandler to Logger. Added removeFilter to Logger and Handler. logrecv.py modified to keep connection alive until client closes it. SocketHandler modified to not reset connection after each logging event. Added shutdown function which closes open sockets, etc. Renamed DEFAULT_LOGGING_PORT->DEFAULT_TCP_LOGGING_PORT. Added DEFAULT_UDP_LOGGING_PORT. Added log_test4.py (example of arbitrary levels). Added addLevelName, changed behaviour of getLevelName. Fixed bugs in DatagramHandler. Added SMTPHandler implementation. Added log_test5.py to test SMTPHandler. Added SysLogHandler (contribution from Nicolas Untz based on Sam Rushing's syslog.py). Modified log_test1.py to add a SysLogHandler. Added rollover functionality to FileHandler. Added NTEventLogHandler (based on Win32 extensions). Added MemoryHandler implementation. Added log_test7.py to test MemoryHandler. Added log_test8.py to test FileHandler rollover. Added logException method to Logger. Added formatException method to Formatter. Added log_test6.py to test NTEventHandler and logException. Numerous internal method renamings (sorry - but better to do this now, rather than when we enter beta status). From krissepu at vip.fi Thu Mar 14 06:34:12 2002 From: krissepu at vip.fi (pekka niiranen) Date: Thu, 14 Mar 2002 11:34:12 GMT Subject: Hexadecimal bytes to integers Message-ID: <3C908ADF.7040009@vip.fi> How can I convert messages below to list of bytes: message = 0x01040000000271 or message = 0104000000A271 to m = [0,1,0,4,0,0,0,0,0,0,0,0,'A',2,7,1] so that I can calculate: a = 255 for byte in m: t = a ^ byte -pekka- From cce at clarkevans.com Wed Mar 13 15:34:00 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Wed, 13 Mar 2002 15:34:00 -0500 Subject: [].keys() and [].items() (Was: Why I think range is a wart) In-Reply-To: <873cz44ea8.fsf@bunty.ruud.org>; from *@spam.ruud.org on Wed, Mar 13, 2002 at 11:34:55AM -0500 References: <873cz44ea8.fsf@bunty.ruud.org> Message-ID: <20020313153400.A6229@doublegemini.com> On Wed, Mar 13, 2002 at 11:34:55AM -0500, ruud de rooij wrote: | perhaps lists should support .keys() and .items() for those operations | (analogous to dictionaries). Very nice idea. This is PEP worthy. It is nice beacuse it does not introduce anything new; a list can easily be viewed as a mapping having a positive integer domain. This is simple, consistent, and quite elegant. Best, Clark From aahzpy at panix.com Sat Mar 23 02:24:22 2002 From: aahzpy at panix.com (Aahz) Date: 23 Mar 2002 02:24:22 -0500 Subject: import * considered harmful (was Re: circular imports (don't yell!)) References: Message-ID: In article , Sean 'Shaleh' Perry wrote: > >in his defense, the gui libs often expect you have done a from X import *. >otherwise your commands are fiendishly long and ugly. > >win = gui.create_window(gui.top_level, gui.foo, gui.bar) So do this instead: from X import create_window, top_level, foo, bar Trust me, you really prefer this. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From arthur.siegel at rsmi.com Sat Mar 16 22:53:22 2002 From: arthur.siegel at rsmi.com (arthur.siegel at rsmi.com) Date: Sat, 16 Mar 2002 22:53:22 -0500 Subject: return type question - operator oveloading Message-ID: But >>> complex(4,5)*7 (28+35j) >>> 7*complex(4,5) (28+35j) >>> complex(4,5)+7 (11+5j) >>> 7+complex(4,5) (11+5j) And >>> int(4).__add__(complex(3,4)) NotImplemented >>> int(4).__mul__(complex(3,4)) NotImplemented >>> complex(3,4).__add__(4) NotImplemented >>> complex(3,4).__mul__(4) NotImplemented Not sure what it really means at a deeper level, but it does seem the implementation on multiply and add for complex with int *is* fully symetrical. still ? Art >>arthur.siegel at rsmi.com wrote in >>news:mailman.1016322689.22392.python-list at python.org: >> But: >> >> print type(7 + Complex(5,4)) >>> chirs- >yes i get the same results (py 2.2). art >> Multiple choice: >> That the result at But is a surprise to me because I am missing: >> 1)Something obvious about __radd__ or general classic syntax >> 2)Something related to new style classes >> 3)Other chris - >i vote for "3) Other". i think the integer class defines __add__ for >complex numbers but not __mul__ for complex numbers. thus when adding >"7+Complex(5,4)" your __radd__ is never called cause the int class >indles it. From brian at zope.com Fri Mar 1 13:54:30 2002 From: brian at zope.com (Brian Lloyd) Date: Fri, 1 Mar 2002 13:54:30 -0500 Subject: Embedding Python in C#... Message-ID: > >has this been done? > > Not that I know of. > > >is it even possible? > > I am pretty sure, yes. (Sorry I'm a little behind on this...) Yep - and it's pretty easy (though I'm not totally done yet) :) It looks something like: PythonInterpreter python = new PythonInterpreter(); PyModule sys = python.ImportModule("sys"); PyList list = (PyList)sys.GetAttr("path"); Console.WriteLine("Sys.path is: {0}", list.ToString()); Console.WriteLine("Item 0 is: {0}", list[0].ToString()); > >if it has where can i obtain information on doing so? If you're interested in playing with it in-progress, let me know. Brian Lloyd brian at zope.com Software Engineer 540.361.1716 Zope Corporation http://www.zope.com From grante at visi.com Tue Mar 19 10:44:28 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 19 Mar 2002 15:44:28 GMT Subject: socket programming References: Message-ID: In article , Shimmie wrote: >> > Anybody know where can i find a good (beginner) tutorial >> > about Socket Programming using Python ? > Here is a neat little UDP example: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52302 That is a nice example of UDP usage. In my experience, when a beginner says he wants to do "socket programming" he invariable means TCP/IP, so I just wanted to make sure our beginner friend knows there's a difference. -- Grant Edwards grante Yow! You must be a CUB at SCOUT!! Have you made your visi.com MONEY-DROP today?? From darnold02 at sprynet.com Mon Mar 25 18:51:36 2002 From: darnold02 at sprynet.com (Don Arnold) Date: Mon, 25 Mar 2002 17:51:36 -0600 Subject: How to get a key from dictionary? References: <3C9FAFCC.20062.91741D@localhost> Message-ID: <009501c1d458$0a5a86c0$3425fea9@0016314730> >>> targetval = 2 >>> dict = {'aa':1, 'bb':2, 'cc': 3, 'dd': 1} >>> targetval = 2 >>> for key in dict.keys(): if dict[key] == targetval: print "found", targetval, "at key", key found 2 at key bb >>> targetval = 1 >>> for key in dict.keys(): if dict[key] == targetval: print "found", targetval, "at key", key found 1 at key aa found 1 at key dd ----- Original Message ----- From: "A" To: ; ; ; Sent: Monday, March 25, 2002 4:16 PM Subject: How to get a key from dictionary? > Hi, > Is there a possibility to get, from a dictionary, a key according to a > value ? > For example > I have a dictionary > > dict={'aa':1,'bb':2} > > and > dict['aa'] > is 1 > > But how can I for value 1 find out key? (That is here 'aa') > > Thank you for help > Ladislav > > > _______________________________________________ > ActivePython mailing list > ActivePython at listserv.ActiveState.com > To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs From jeff at ccvcorp.com Mon Mar 4 14:50:27 2002 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 04 Mar 2002 11:50:27 -0800 Subject: Windows GUI - which way? References: <3C7EC855.5844B19F@engcorp.com> Message-ID: <3C83D003.411FEE3F@ccvcorp.com> Spencer Ernest Doidge wrote: > I want to maintain and use a library of Python scripts. I want to invoke > any script from this library by using a GUI app. The script itself would > have no GUI features. It would be sending and receiving serial port > messages. (This is like the script I am already running.) > .... > If I write the GUI app all in Python, is it a simple matter to, say, load > and run the script in its own thread, and have it be responsive to a > signal from the main thread telling it to abort? The answers to your question depend on whether you intend to design the library scripts specifically for this purpose, or if you're intending to use "off-the-shelf" scripts from elsewhere. If you're able to modify the scripts to work with your GUI framework, then all of these things are (fairly) easily possible. If you want to be able to run *any* script, then things become more difficult. In order to abort the script thread, the script needs to check for a condition and terminate itself -- you can't kill a thread from outside. If you don't control the script, then you have no way to ensure that it will do this, of course. You *can* do this by running the script in a separate process, though -- it's a more expensive solution, but you can kill the process if you need to. Output is no problem in either case -- for threads, simply write your output to a Queue, and have your GUI read the queue and update a window. For arbitrary scripts, you can use popen(), or more likely popen2() or popen3(), which gives you out-of-process execution and a handle to that script's stdout. A progress bar would be no problem for the first case, either -- like Peter said, just have the script post notices to the GUI when you need to update the progress bar. I can't think of any practical way to do this for arbitrary scripts, though, because you have no way of knowing how long they will run, or what stage they are at. Jeff Shannon Technician/Programmer Credit International From jcromwell at ciena.com Sat Mar 2 19:53:10 2002 From: jcromwell at ciena.com (Cromwell, Jeremy) Date: Sat, 2 Mar 2002 16:53:10 -0800 Subject: PEP 276 -- What else could iter(5) mean? Message-ID: If python was to allow "for i in 5:", is there any other meaning that would be appropriate besides the one detailed in PEP 276? Without trotting out ugly examples, it is cleaner than many of the current features in python. I'm still a relative newbie, but I remember it being a bit jarring to need to use range() just to iterate through numbers. It's so simple to explain and understand, that I doubt that it would be confusing. Here's my clumsy rewording of the tutorial: 4.3 For x in integer, and the range() Function When given an integer rather than a sequence, the for statement iterates over the numbers from 0 up to (but not including) the given number: >>> for i in 3: ... print i, i*3 0, 0 1, 3 2, 6 The given end point is never part of the generated list; for x in 10 iterates through a list of 10 values, exactly the legal indices for items of a sequence of length 10. To iterate over the indices of a sequence, use len() as follows: >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in len(a): ... print i, a[i] ... 0 Mary 1 had 2 a 3 little 4 lamb If you do need to iterate over a more complex sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions. You supply the start and finish and it produces a list from start up to finish, incrementing by one: >>> range(5, 10) [5, 6, 7, 8, 9] It is possible to specify a different increment (even negative; sometimes this is called the `step'): >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] Calling range() with one number produces the same list that a for statement iterates over for that number: >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] --- end tutorial --- I like this proposal and would like to see it adopted. If others like it, they should speak up since about all we hear from are the detractors. Jeremy Cromwell ...now let's see........Hmmm, where's that key? From mats at laplaza.org Sat Mar 2 11:16:23 2002 From: mats at laplaza.org (Mats Wichmann) Date: Sat, 02 Mar 2002 16:16:23 GMT Subject: (OT?) Web-based document review system? References: <3c801a5b.68374897@news.laplaza.org> Message-ID: <3c80f9de.125594084@news.laplaza.org> On Fri, 01 Mar 2002 18:52:42 -0800, Wayne Pierce wrote: : :Mats Wichmann wrote: :> Note: this is not a Python question per se. :> :> I'm looking for a piece of software to aid in reviewing a document :> through the web - click on a paragraph tag, have the comment added :> (highlighted in some way). The wiki style doesn't seem to quite do it, :> as the core document is not protected. I haven't found much in web :> searches, and nothing where the software seems to be free. : :If Wiki allowed for password protection would it fit your requirements? Not really. A Wiki works on the model that everyone is the editor; the model that I need to operate on is a single editor, many reviewers. :Something like Zope's CMF Workflow[2] might also be a good fit....then :there's OpenFlow[3] (also running on Zope :). My understanding of Zope is limited, but it might provide the facilities needed, yes. Here's an implementation that's "almost there": http://www.quicktopic.com/10/D/9hmkxh7US2d.html The thing I want (that I've seen in private in-house implementations) is a view that shows the original document and the comment in a single view, here you have to click to get the comments. I can envision a scheme where a document is broken into objects that can be commented on, and on presentation a document object can be displayed togther with its' associated comment objects. Sound like something Zope could facilitate? Hmmm. Mats Mats Wichmann From angi15945 at hotmail.com Mon Mar 4 14:28:04 2002 From: angi15945 at hotmail.com (angi15945 at hotmail.com) Date: Mon, 4 Mar 2002 20:28:04 +0100 (CET) Subject: where you been Message-ID: <200203041928.g24JS4c27970@main.sgk.com.pl> --------------------------------------------------------------------------- : Hey, I am a 19/f with a webcam my name is angie! If you're interested in meeting myself or other people of all races, ages, of the same or opposite sex and want to watch them on their webcams for free, then you need to try this! It's called it's a dating program designed for people who are sick of the same old bar scene & want to meet new people! It's simple, all you do is signup & start looking! The best part is...it's ALL 100% free for you! ~Enjoy!
    FREE WEBCAM DATING! IF you would like to be removed from this reply with the message "remove" thanks. --------------------------------------------------------------------------- From martin at v.loewis.de Mon Mar 18 16:52:13 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Mar 2002 22:52:13 +0100 Subject: A question about generators References: <858z8pg7h8.fsf@moriarity.grauel.com> Message-ID: rjk at grauel.com (Richard J. Kuhns) writes: > while 1: > inkey = raw_input('Well? ') > # there are also several variants like 'generate_exact_matches' > for i in generate_appox_matches(inkey): > if this_is_interesting(i): > do_work(i) > break > > There's an assumption that if we find anything with the comparable > generate_exact_matches(), they're all interesting. It seems to me that a plain computation of a list of approx_matches might be appropriate: you do need all of them in the algorithm, so that would be a bad thing to do only if the approx_matches exceed your available memory. I'd write something like def generate_appox_matches(inkey): result = [] for line in open(filename): if appoximately_matches(line, inkey): result.append(line) return result Look Ma, no generators! Regards, Martin From kingprad at mail.com Sat Mar 9 00:23:08 2002 From: kingprad at mail.com (Carl) Date: Fri, 8 Mar 2002 23:23:08 -0600 Subject: instantiating a class Message-ID: <3c899c2d@news.cc.umr.edu> I'm an intermediate-level python programmer and use classes all the time, but a weird problem is frustrating me. In my main program: import lj_connect blah blah code talkserver = lj_connect.lj_connect(userinfo) the start of lj_connect.py is this: class lj_connect: def __init__(self,basic_data): self.uinfo = basic_data I'm getting an AttributeError saying module lj_connect has no attribute lj_connect. Originally the lj_connect code was in the same file as the main program until I moved it for readability's sake. Can anyone see a problem? Thank so much! Carl From mwh at python.net Wed Mar 20 06:39:56 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 20 Mar 2002 11:39:56 GMT Subject: Binary generation with distutils? (Freeze, py2exe, etc.) References: Message-ID: Fernando P?rez writes: > Magnus Lie Hetland wrote: > > > > > - Magnus (who also is a bit baffled as to why distutils doesn't > > include?an?"uninstall"?command,?such?as?the?one?implemented?by > > Thomas?Heller.) > > Amen. It's incredibly annoying to have to tell users that a simple python > setup.py install does the trick as far as splattering files all over their > system, but that there's no reasonable way of undoing the process easily. http://www.python.org/patches/ :) > I realize how busy the core team is, but I truly hope that in the > future someone finds time to give distutils a serious revamp. It's > sorely needed, and it's IMHO a key piece of the python puzzle as a > solid, wide-availability, cross-platform language. People only complain that, e.g. "distutils doesn't do uninstall" or "distutils doesn't do binary packages for platform X" because it does the things it does so very well. It is never going to be perfect, because by definition it has to cope with all kinds of horrible cross-platform nastiness, insane shell quoting, etc. Even in it's current state, the distutils package is an amazing piece of work. I think people forget this sometimes. Cheers, M. -- > I'm a little confused. That's because you're Australian! So all the blood flows to your head, away from the organ most normal guys think with. -- Mark Hammond & Tim Peters, comp.lang.python From gargravarr at whoever.com Wed Mar 20 16:08:59 2002 From: gargravarr at whoever.com (gargravarr at whoever.com) Date: Wed, 20 Mar 2002 21:08:59 GMT Subject: Unicode problem References: <3c98f206.24909027@news.tiscali.no> Message-ID: <3c98faad.27124282@news.tiscali.no> >if you don't tell Python what 8-bit encoding you want >to use for a Unicode string, Python will assume ASCII. How do I tell Python what 8-bit encoding I want to use ? Can I tell Python so I don't have to use encode? From ralph at inputplus.demon.co.uk Tue Mar 19 19:19:15 2002 From: ralph at inputplus.demon.co.uk (Ralph Corderoy) Date: 20 Mar 2002 00:19:15 GMT Subject: Python-2.2.1c1 Build Problems on Linux and AIX. References: Message-ID: Hi Skip, > > With Python-2.2.1c1, I find `make test' fails on my old version of > > Linux/x86 and it fails to build on an also old version of AIX. > > Should I go straight to SourceForge and fill in bug forms or do > > people tend to discuss the problems here first? > > > > I can see the problem with the AIX build. Linux SIGSEGVs in > > test_calendar on a call to strftime. > > The strftime call in calendar.py is a bit abusive, so it's not > entirely surprising to me that you're seeing problems. This test > succeeds for me on my Mandrake system. Can you run the > test_calendar.py script manually and submit a SF bug report (assign > it to "montanaro")? A debugger traceback would be helpful as well. I've found this in README. On some Linux systems (those that are not yet using glibc 6), test_strftime fails due to a non-standard implementation of strftime() in the C library. Please ignore this, or upgrade to glibc version 6. I guess that applies to me. local$ ldd python libdl.so.2 => /lib/libdl.so.2 (0x40004000) libpthread.so.0 => /lib/libpthread.so.0 (0x40007000) libutil.so.1 => /lib/libutil.so.1 (0x40014000) libm.so.6 => /lib/libm.so.6 (0x40018000) libc.so.6 => /lib/libc.so.6 (0x40031000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x00000000) local$ rpm -qf /lib/libc.so.6 glibc-2.0.7-29 > Does the AIX version of strftime support %a, %A, %b and %B formats? I expect so. But the AIX problem is in building python so I don't get as far as `make test'. Cheers, Ralph. From paul at boddie.net Fri Mar 29 09:55:54 2002 From: paul at boddie.net (Paul Boddie) Date: 29 Mar 2002 06:55:54 -0800 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> <7xk7s7mpiy.fsf@ruckus.brouhaha.com> Message-ID: <23891c90.0203290655.25bbcab9@posting.google.com> Jon Ribbens wrote in message news:... > [HTML in Python code] > > ... and 'jonpy' avoids the issue entirely by neither embedding Python > in HTML or HTML in Python. Its templating system embeds *no code of > any sort* in the HTML and this turns out to be completely super ;-). > See http://jonpy.sourceforge.net/wt-examples.html#templatecode for > examples. It's actually quite reminiscent of the earliest versions of DTML, in fact, where comments are used to mark the structure of the "model" as opposed to the special tags which were introduced in DTML later on. > This is especially useful when you have different people generating > the HTML and the code (as it almost always the case). The designer is > much less likely to mangle the 'significant' parts of the HTML files, > and even if they do, it's a matter of seconds to fix. Zope Page Templates takes the other "under the radar" approach, of course, using special attributes which HTML editors usually don't want to touch. I suppose only testing of what different editors do with attributes and comments can determine whether special attributes or comments are best to avoid "destructive editing" when HTML files are redesigned. I agree with Jon that the ability to divide work into separate activities of page design and application development is very important, especially in situations where designs may change rapidly over time. Indeed, any help in partitioning workloads is essential for many kinds of applications; otherwise the software developers end up not only doing their own work, but also intensively managing the changes made by designers, potentially resulting in "workflow bottlenecks" around developers while designers wait impatiently for the application to take on its new look. > Additionally, when the customer says "actually, we don't like the style of > the site, we want it changed" and you get sent a whole bunch of new code-less > HTML files, with a PHP-style code-in-HTML you pretty much have to > reimplement the entire site from scratch, whereas with this system you > just add back in the section markers and the code (which was in > separate files anyway) does not usually need to be changed at all. I think that while some applications probably do need a lot of control over their own presentation, demanding a programmatic approach to output generation, in many applications once the problem of generating output in a maintainable way has been resolved, the most common subsequent problem is handling the input from users and finding a way to reduce the maintenance on this activity as well. In the Python community, there is obviously an intense interest in templating, but I haven't seen more than a handful of validation packages, and I can imagine that few of them actually integrate satisfactorily with template packages. Paul From tim.one at comcast.net Mon Mar 4 03:41:07 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 04 Mar 2002 03:41:07 -0500 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? In-Reply-To: <000001c1c202$7996be90$1001a8c0@NICKLEBY> Message-ID: A lot of this speculation should have been cut short by my first msg. Yes, something changed in 2.2; follow the referenced link: http://sf.net/tracker/?group_id=5470&atid=105470&func=detail&aid=496104 For the rest of it, it looks like the "1e-200**2 raises OverflowError" glitch is unique to platforms using glibc. What isn't clear is whether it's dependent on which version of glibc, or on whether Python is linked with -lieee, or both. Unfortunately, the C standard (neither one) isn't a lick of help here -- error reporting from C math functions is a x-platform crapshoot. Can someone who sees this problem confirm or deny that they link with -lieee? If they see this problem and don't link with -lieee, also please try linking with -lieee and see whether the problem goes away then. On boxes with this problem, I'm also curious what import math print math.pow(1e-200, 2.0) does under 2.1. One probably-relevant thing that changed between 2.1 and 2.2 is that float**int calls the platform pow(float, int) in 2.2. 2.1 did it with repeated multiplication instead, but screwed up endcases. An example under 2.1: >>> x = -1. >>> import sys >>> x**(-sys.maxint-1L) Traceback (most recent call last): File "", line 1, in ? ValueError: negative number cannot be raised to a fractional power >>> The same thing under 2.2 returns 1.0, provided your platform pow() isn't braindead. Repeated multiplication is also less accurate than a decent-quality pow(). From martin at v.loewis.de Fri Mar 29 17:23:10 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 29 Mar 2002 23:23:10 +0100 Subject: Problem with Tkinter References: Message-ID: "Cyr" writes: > Python has been installed on another station in a common directory and > Tkinter works great on the other station. But the Tk library isn't in a > common directory. On this station (srv0023), I only have Tcl/Tk 8.0 (and no > library in the directories mentioned in the error message). Is there any way > I can configure python so that it would use Tk 8.0 library on the station > but continue to use Tk 8.3 on the other station ? It is possible, but difficult. You need to compile _tkinter.so twice, once linking it with Tk 8.0, and once linking it with Tk 8.3. That requires that you have both versions installed on the build station, including header files for both versions. > In fact, I wonder how I can change the path search for the Tk > library within python. You need to edit Modules/Setup to direct make to a specific Tkinter location. In doing so, you must uncomment the *shared* line in Setup, since it will otherwise build _tkinter directly into the Python executable. HTH, Martin From jimd at vega.starshine.org Wed Mar 27 07:24:01 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 27 Mar 2002 12:24:01 GMT Subject: Python, CGI and PGP References: <3c9fbf57@peer1.news.newnet.co.uk> <3ca0b0f9@peer1.news.newnet.co.uk> Message-ID: In article <3ca0b0f9 at peer1.news.newnet.co.uk>, Phil Edwards wrote: >Jim Dennis wrote: ... > Thanks, Jim, this is definitely one for the "little black book". When I see > things like this, I'm reminded just why I love UNIX so much... >> If you are reasonably persistent and a little clever you should be able > Oh, that leaves me out, then :-) > Managed to figure it all out with the help of the wrapper stuff above. It > turns out that both 'os.system' and 'commands.getoutput' (which I had > tried) trash so much of the execution environment that there's hardly > anything left for the binary to wprk with. I'd suspect that the web server is probably cleaning most of the environment out. I wouldn't immediately suspect Python of doing it (though I haven't looked through its code nor run an strace on it). A quick test from an interactive Python session (calling os.system("bash") and also os.system("sh")) shows that they have almost the same environment that I have from before Python was loaded. (The only discrepancies were SHLVL, which is to be expected, and in the LINES and COLUMNS values, which appeared in my sub-shells but not in the parent of my Python process. LINES and COLUMNS are set by bash for curses support --- but their omission should be innocuous for our purposes here. The web server, on the other hand, is well advised to execute CGIs in a "clean room" environment. It probably uses one of the flavors of exec*() that passes a pointer to a new environment to the system and thence to the child process. You might be able to modify your Apache (or other httpd / web server) configuration to retain more of your environment. > I'm left with the following code in my CGI app: > cmd = 'export PGPPATH=/var/www/.pgp; /usr/local/bin/pgp -z windsurf -sta > -f - ' > print 'content-type: text/html\n\n' > pw,pr = os.popen2(cmd) > pw.write(tdata) > pw.close() > junk = pr.read() > print string.replace(junk, '\n', '
    \n') > Thanks for your help! It's a shame there isn't a scheme for sending > beer/pizza vouchers over the 'net... You could send that to the Samba team in Canberra, Australia. I learned part of that trick from Tridge (Andre Tridgell, the creator of Samba). They used to have an account with the local pizza shop. I suppose you could follow the link on their web site (http://www.samba.org/ ) to buy mugs or T-shirts. I've actually been considering creating a Paypal account for receiving payments from my remote consulting customers. However, I'd never charge for answers to USENET. I just consider the effort I put into my answers here to be a small token of gratitude for the many answers I've received *from* netnews. Despite all the flamers, trolls, and spam I've found that netnews is the fastest way for me to learn a new technical subject. Although I'll read any manuals I can find (I've got about a dozen Python books at this point) and I'll even take the odd class if I can find the time (they usually don't fit into my schedule, and they usually go WAY TOO SLOW) and I go to user group meetings (too often in a formal presentation style rather than a "workshop" gathering). Despite all these alternative approaches I find that the USENET netnews medium affords the most practical way for me to learn. I do well when posed with lots of diverse questions around a subject and given the instant gratification of many answers (some wrong!). The game I play with myself, is that I try to guess the answer to each puzzle and I try to critique each proposed answer. As I find that I can guess the "right" answers more often then not, I move from lurker mode to active participant. That forces me to actually write and test my examples, which forces me to look up reference material on specific functions, which helps me gain practical proficiency. (I've been studying Python for about six months now). Anyway, glad I could help. From db3l at fitlinxx.com Fri Mar 15 12:34:09 2002 From: db3l at fitlinxx.com (David Bolen) Date: 15 Mar 2002 12:34:09 -0500 Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> Message-ID: grante at visi.com (Grant Edwards) writes: > That is true under Win32 -- Just one of the problems when using > an OS where the networking was pasted on (badly) as an > afterthought. > > Under Unix, select works on all file descriptors (sockets, > pipes, serial ports, etc.). That demonstrates the _right_ way > to paste on networking as an afterthought. Of course, to be fair, it's not really networking that was pasted on badly but rather the socket interface. If you're using native Win32 operations on native Win32 file handles, you can perform asynchronous I/O and wait for completion on just about all the native kernel objects - and even mix in other signaling objects simultaneously. And winsock does provide a way to tie socket I/O into the same event system. In Unix, select just happens to be a more generic function, whereas in Windows it was grafted on as part of the socket library. But that's more a portability issue than a comment on Windows internals. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From gcordova at hebmex.com Fri Mar 1 16:32:48 2002 From: gcordova at hebmex.com (Gustavo Cordova) Date: Fri, 1 Mar 2002 15:32:48 -0600 Subject: Code Review!! (or bash!) Message-ID: <19650FF08A99D511B19E00B0D0F06323060B2B@SRM201002> Howdy y'alls. "Once upon a time in a Python List far far away...", some one bitterly asked why python doesn't include an XML parser, since it relied on expat to do it's XML parsing for it. And that got me thinking... so, since I usually get a bit bored for an hour or so during lunchtime, I wrote a tiny, toy XML parser with a few helper classes. Emphasis on tiny toy. Before I let it out into the wild, I'd like to know what you all people think about this toy. I know, there's xml.dom stuff, and xml.sax stuff, but I can't seem to wrap my brain around it, so I just started writing this out of curiosity, and now it's starting to feel useful. But "useful" is so subjective, isn't it. :-) Mind you, it only works for 8-bit chars, so there's a limitation. So, here it is. -- Gustavo C?rdova Avila gcordova at sismex.com 8351-3861 | 8351-3862 -------------- next part -------------- A non-text attachment was scrubbed... Name: miniXML3.py Type: application/octet-stream Size: 19606 bytes Desc: not available URL: From wealthychef at mac.com Thu Mar 14 22:34:42 2002 From: wealthychef at mac.com (wealthychef) Date: 14 Mar 2002 19:34:42 -0800 Subject: readline() blocks after select() says there's data?? Message-ID: <2b57f654.0203141934.391d1bcc@posting.google.com> Hi, I'm pretty clueless about sockets, but here's my problem. Please help! I have a process (actually a 'make') which takes a long time to complete and periodically spits out lines of information. I want to keep an eye on it, echo what it says as it says it, and report its status when done. So I wrote a function called "WaitForCommand", which in turn periodically calls CheckForOutput() to see if there's anything to get. My code is below. The relevant lines are the following: selectables = [theProcess.childerr, theProcess.fromchild] (input, output, exc) = select.select([],selectables, selectables) if output: for theOutput in output: if theOutput == theProcess.childerr: eoutput = theProcess.childerr.readline(bufsize) print eoutput elif theOutput == theProcess.fromchild: stdoutput = theProcess.fromchild.readline(bufsize) print stdoutput It blocks forever waiting for theProcess.childerr.readline(bufsize) to return. I expect it to block waiting for select.select(); that would not be a problem. The problem is that select is claiming there's stuff to be read, then when I try to read it, it's not there! How can that be? I don't want to block forever waiting for childerr when fromchild has something for me; that's why I am using select, to be able to see what's ready, right? I don't get it. ****************************************************** Here is the full code if that's useful. Please trim this out of your replies if not needed. This message is heinously long as it is. def CheckForOutput(theProcess, selectables, bufsize, NoStdErr, Verbose): while 1: (input, output, exc) = ([],[],[]) (input, output, exc) = select.select([],selectables,selectables) if output: for theOutput in output: if theOutput == theProcess.childerr: eoutput = theProcess.childerr.readline(bufsize) print eoutput elif theOutput == theProcess.fromchild: stdoutput = theProcess.fromchild.readline(bufsize) print stdoutput if exc: pollNum = theProcess.poll() if pollNum != -1: print "process closed" break raise ("WaitForCommand-- Unknown Error from process pipe.") if not output and not exc: break return def WaitForCommand(iCommand, NoStdErr=None, RaiseExceptionOnErr=None, Verbose=None, bufsize=-1): theProcess = popen2.Popen3(iCommand,capturestderr=1, bufsize=bufsize) selectables = [theProcess.childerr, theProcess.fromchild] while 1: CheckForOutput(theProcess, selectables, bufsize, NoStdErr, Verbose) returnCode = theProcess.poll() if returnCode != -1: CheckForOutput(theProcess, selectables, bufsize, NoStdErr, Verbose) if returnCode and RaiseExceptionOnErr: raise 'Error: return code is ' + str(returnCode) if Verbose: print 'return code is ', returnCode break return From trentm at ActiveState.com Mon Mar 4 14:20:00 2002 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 4 Mar 2002 11:20:00 -0800 Subject: PEP 282: A Logging System -- comments please In-Reply-To: ; from aahz@panix.com on Fri, Mar 01, 2002 at 08:02:31PM -0800 References: Message-ID: <20020304112000.E9696@ActiveState.com> > Trent Mick wrote: > > > >Simple Example > > > > This shows a very simple example of how the logging package can be > > used to generate simple logging output on stdout. > [Aahz Maruch wrote] > Tim will whine about Win9x, but I suggest that stderr be the default. I have no problem with stderr being the default. Perhaps having to make a single configuration call to switch the default output stream back to sys.stdout would not be too much of a burden for Win9x users that want to redirect output from their program. Trent -- Trent Mick TrentM at ActiveState.com From fgeiger at datec.at Mon Mar 18 04:45:36 2002 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 18 Mar 2002 10:45:36 +0100 Subject: PIL: Want to convert images into HSL format Message-ID: PIL can supply me with RGB data of an image. Does anybody know, how I can PIL have to transform this into the HSL (aka HSI) model? I'm new to image processing, but if I understand the chapter Introducint PIL -> Concepts -> Mode right, HSL is not mentioned there. Well, I have to admit, the only two color modes of the mentioned ones I understand are RGB and CMYK. Any idea? Cheers Franz GEIGER From guido at python.org Sat Mar 30 13:10:28 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 18:10:28 GMT Subject: PEP 285: Adding a bool type References: Message-ID: <3CA6008B.C76E9BD2@python.org> [me] > > Tim must be missing something. The obvious way to turn a bool b into > > an int is int(b). Having to import the obscure 'operator' module for > > this purpose is backwards. (IMO there's almost *never* a reason to > > import that module anyway.) [Ralph] > I thought Tim was trying to map a range of integer values onto just 0 > and 1 as ints, not False and True, where as you're suggesting he just > wants to get an int from a boolean. I think he has an expression like > day_of_month, e.g. 30, and wants a 0 or 1 from it. I should've said int(bool(x)) for any expression x. When I wrote int(b) I meant b to be a value that was already a bool. --Guido van Rossum (home page: http://www.python.org/~guido/) From gimbo at ftech.net Mon Mar 11 12:44:34 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Mon, 11 Mar 2002 17:44:34 +0000 Subject: lambda question In-Reply-To: <20020311182933.B1084@zephyr> References: <29A97D00F387D411AC7900902770E148044AAFEB@lcoeexc01.coelce.net> <20020311182933.B1084@zephyr> Message-ID: <20020311174434.GG12733@andy.tynant.ftech.net> Of course, the other reason why it doesn't "work" (at least for me), is that it's indented with tabs rather than 4 spaces. ;-) Now, I'll repeat that wink, just to be absolutely clear. ;-) Actually, seriously, I'd also note that 'list' is not a good choice of variable name, since it obscures the list() builtin. -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From robin at jessikat.fsnet.co.uk Sat Mar 23 17:13:59 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 23 Mar 2002 22:13:59 +0000 Subject: how do i get RGB from HEX? References: Message-ID: In article , Bengt Richter writes ...... >> >>>>> def rgb(h): >>... n = eval('0x'+h[1:]) >>... return (n>>16)&0xff, (n>>8)&0xff, n&0xff >>... >>>>> rgb('#DCDC0a') > ,-^^ > | > ??? > | > vvv >>(220, 220, 220) ...... yes that was me editing in pythonwin -- Robin Becker From mcleanc at cpsc.ucalgary.ca__no_spam__ Fri Mar 22 13:47:06 2002 From: mcleanc at cpsc.ucalgary.ca__no_spam__ (Craig McLean) Date: Fri, 22 Mar 2002 11:47:06 -0700 Subject: Namespace Qualification Question Message-ID: <3C9B7C2A.20708@cpsc.ucalgary.ca__no_spam__> I've been messing around with python namespaces and I've run into something that I haven't been able to answer. Is there a module assosciated with the file you started the interpreter with, and if there is what is it's name? For instance > python qux.py I would have thought that there would be a qux module, and that it's name would be stored in the __name__ builtin. If I was using the interpreter interactively would that change things? From s.ernst at web.de Fri Mar 15 04:10:21 2002 From: s.ernst at web.de (Sascha Ernst) Date: Fri, 15 Mar 2002 10:10:21 +0100 Subject: problems with compiling python on osx Message-ID: hello, I've downloaded the newest python sources and tried to run ./configure. I'm within the right directory, the shell is located correctly, all read/write/execute-rights are set, but even as a root I get the error-message "command not found!". is there anything I forgot? regards, sascha From phr-n2002a at nightsong.com Sun Mar 3 03:57:28 2002 From: phr-n2002a at nightsong.com (Paul Rubin) Date: 03 Mar 2002 00:57:28 -0800 Subject: Rotor in Jython? References: Message-ID: <7xlmdaf2pz.fsf@ruckus.brouhaha.com> writes: > > writes: > > > Put another way: sorting by key length, AES beats rotors hands down. > > > Sorting by computational cost, rotors always win because you can just make > > > the keys longer (without having to reimplement your crypto). > > > > Longer keys are only relevant if breaking the cipher requires searching > > for the key. > > Heheh... that's essentially what cryptanalysis is - finding the key since > in most cases the algorithm itself is known. If you're referring to > non-brute force key searches, then key length is relevent there as well > (unless the algorithm itself is flawed). Yes, that's the point. AES appears to be very attack resistant. Compared to AES, rotors have a pretty sorry history of falling to cryptanalysis. There's no reason to think brute force is the best way to solve a rotor cipher. From evebill8 at hotmail.com Sun Mar 17 12:32:44 2002 From: evebill8 at hotmail.com (Billy Ng) Date: Sun, 17 Mar 2002 17:32:44 GMT Subject: sunstring Message-ID: <0r4l8.22204$P4.1955815@newsread2.prod.itd.earthlink.net> Would anybody tell me how to do substring in python? Thanks in advance! Billy Ng From cfelling at iae.nl Fri Mar 1 16:25:19 2002 From: cfelling at iae.nl (Carel Fellinger) Date: 1 Mar 2002 22:25:19 +0100 Subject: PEP 276 (was Re: Status of PEP's?) References: Message-ID: James_Althoff at i2.com wrote: ... > [Carel Fellinger] >> you being such a heavy weight that I fear ... > Well, thanks (I think ), but I can assure you that I hold no special You think right, which could have be infered from *me* calling you a heavy weight, might you have known me:) ... > [Carel Fellinger] >> Not only newbie unfriedly, you need a firm grasp of modern set >> based number theory to appreciate it, it seems. > As fond as we all surely are of the neat mathematical underpinnings > suggested here and before, I believe that most programmers -- regardless of > skill level (and pedigree in the field of mathematics) -- would be able to > understand -- and certainly easily remember the second time -- that > iterating on n means taking each of 0,1,2, ..., n-1 in turn; this without > having to think about -- much less have "a firm grasp of" -- number theory > (modern, set-based, or otherwise ). At least if one has enough > background to understand "iteration" to begin with. I admit I will be able to remember this, know how and when to use it and all that. And certainly programmers in general will be able to handle it, hey some of them even handle APL (or so they believe). But even after that nice math lesson I still don't *understand* it, you iterate over a sequence and I have a hard time seeing an integer as a sequence. Same for a length. And I believe many would have the same problem. Besides, I don't see the huge advantage of this compared to `range(integer)' or `indici(sequenceORmapping)'. Unfortunately the whole subject has moved from a `preference' via `lack of knowledge' to a matter of `believe', so not much of a chance to resolve it:) > Let's try that again. > Q: What does it mean to iterate a number n? A: I wouldn't know. O wait you mean that awfull hack, yea I know, pretend an integer is a sequence... > I certainly acknowledge the feelings of those who don't like the suggested > idiom. At the same time, claims of its alleged *great difficulty* seem > overblown. It's not difficult to use once it's been explained, it's difficult to understand no matter how often it gets explained. > [Carel Fellinger] >> So please explain why you think it natural to loop over a number. > The "rational" section of PEP 276 talks about iterating through the indices > of an indexed collection. These, as we know, are related to the length (an > integer) of the indexed collection. far fatched isn't it? What about a function that accepts as argument such a collection and then generates the indici? Much easier to explain, to understand, to adopt. But admitted, it takes a little extra typing. Seriously I would like you to add something in your PEP that addresses this simple alternative and explain why you favour yours. True, `i in range(len(sequence))' doesn't look very pleasing, but `i in indici(sequence)' does. And as an added bonus it's very similar to `(i, item) in indexed(sequence)'. > [Carel Fellinger] >> here in your PEP you make it look like some minority >> of nitwits objected > I don't remember writing anything about nitwits. But that does remind me I'm sorry. Those are my words, and my words only. I was a bit itchy that day, would have formulated it differently now. But I do think that dismissing our point as a matter of preference misses our point. > [Remco Gerlich] >> Compare: >> >> for i in 6: print i >> for i in 6,7: print i >> for i in 6,7,8: print i >> >> You wouldn't think the first line does something different, would you? > [Emile van Sebille] >> Is that really any different from what we have now: >> >> for i in "Spam": print i >> for i in "Spam","and": print i >> for i in "Spam","and", "Eggs": print i > [Andy Gimblett] >> Yes, it really is. "Spam" is a sequence, whereas 6 isn't. > I agree with Emile on this one. To me this means you actually see and int as a sequence then. A string is a sequence, a sequence of chars. I still fail to understand how the same applies to integers. > Two different results. One needs to understand how and why. Sometimes one > wants to treat a string as a unit, other times as a sequence. It's useful > and convenient to be able to do both. I agree, but can't relate this to integers. looking forward to your views on meta programming though -- groetjes, carel From clpy at snakefarm.org Fri Mar 15 18:14:10 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Sat, 16 Mar 2002 00:14:10 +0100 Subject: locale module broken? Message-ID: <3C928042.BA50A5B3@snakefarm.org> Hi there, while playing around with Greg Lindstrom's "Pretty integers" (see his posting), my Python 2.2 got stuck here: >>> import locale >>> locale.setlocale(locale.LC_ALL, "fr_FR") 'fr_FR' >>> locale.format("%.1f", 12345.5, 1) It runs forever. This is on RedHat 6.2 and Debian Potato. Any hints? Note that I didn't "./configure --without-french". :-) cg. -- Why settle for snake oil if you can have the whole snake? http://python.org/ From eppstein at ics.uci.edu Wed Mar 6 21:06:38 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 06 Mar 2002 18:06:38 -0800 Subject: PEP 284, Integer for-loops References: Message-ID: In article , James_Althoff at i2.com wrote: > A lot of thought and work has been put into the syntax part of the > proposal. I think some more thought and work might be required on the > semantics. Well, it would be a problem if the semantics need to get hairy to support the syntax. To continue quoting from Tim, "If the implementation is hard to explain, it's a bad idea." So I think I would prefer to only handle built-in integer types for now. I guess the PEP should state that more explicitly? Thanks for your other comments, I'll keep them in mind. From guido at python.org Sat Mar 30 13:29:29 2002 From: guido at python.org (Guido van Rossum) Date: Sat, 30 Mar 2002 13:29:29 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type In-Reply-To: Your message of "30 Mar 2002 11:04:13 EST." References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> <014f01c1d7f3$fe9aff00$0202a8c0@boostconsulting.com> <200203301423.g2UENn701717@pcp742651pcs.reston01.va.comcast.net> Message-ID: <200203301829.g2UITUw02158@pcp742651pcs.reston01.va.comcast.net> > Guido> Another argument for deriving bool from int: implementation > Guido> inheritance. A bool must behave just like an int, and this is > Guido> most easily accomplished this way: the bool type doesn't have > Guido> implementations for most operations: it inherits them from the > Guido> int type, which find a bool acceptable where an int is > Guido> required. [ARK] > Liskov substitutibility would seem to suggest deriving int from bool, > not the other way around. That is: If I have a program that uses bool > values, I can change it so that it uses int values without affecting > the behavior of the program. The reverse is not true. > > I wonder if this is the circle-ellipse problem over again? Probably. We're inheriting implemetation. --Guido van Rossum (home page: http://www.python.org/~guido/) From dale at riverhall.NOTHANKS.co.uk Thu Mar 21 08:35:24 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Thu, 21 Mar 2002 13:35:24 +0000 Subject: How to install pychecker? References: Message-ID: <7boj9u477fofip4l7hdh2fcri1cgo7tv0s@4ax.com> Thanks for the replies. Now installed. -- Dale Strickland-Clark Riverhall Systems Ltd From op73418 at mail.telepac.pt Sun Mar 31 20:17:03 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 01 Apr 2002 02:17:03 +0100 Subject: __name__ on new-style classes Message-ID: One can change the name of a classic class but not of a new-style one (see below for example). Is this a bug or a feature, and if the latter is there any reason for the change? >>> class Test(int): ... pass ... >>> Test >>> Test.__name__ 'Test' >>> Test.__name__ = "Weirdo" Traceback (most recent call last): File "", line 1, in ? TypeError: attribute '__name__' of 'type' objects is not writable >>> class Test: ... pass ... >>> Test.__name__ 'Test' >>> Test.__name__ = "Weirdo" >>> Test.__name__ 'Weirdo' From akuchlin at ute.mems-exchange.org Tue Mar 12 13:37:33 2002 From: akuchlin at ute.mems-exchange.org (A.M. Kuchling) Date: 12 Mar 2002 18:37:33 GMT Subject: Has Mark Hammond attained pariah status yet? References: <3c8e0911_1@news.bluewin.ch> <3c8e2b9b$1_4@news.bluewin.ch> Message-ID: In article <3c8e2b9b$1_4 at news.bluewin.ch>, Samuele Pedroni wrote: > And what datapoints we acquire through > the article? Well, nothing much, which is all I'd expect from something so brief in a general publication. Hopefully Mark will clarify at some point. There does seem to be an increasing trend to vaporware announcements about language unification, though. Witness Parrot, Mono, and SmallScript [1], all of which talk about having support for many languages including Python, but none of which have actually tried to build that support or work with the Python community to build it. [1] http://groups.google.com/groups?selm=bq%25F6.22782%24Jh5.22352484%40news1.rdc1.sfba.home.com&output=gplain --amk (www.amk.ca) UTF-8 has a certain purity in that it equally annoys every nation, and is nobody's default encoding. -- Andy Robinson, 10 Apr 2000 From geoff at gerrietts.net Thu Mar 7 14:59:46 2002 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 7 Mar 2002 11:59:46 -0800 Subject: Python and computer graphics In-Reply-To: <3C87B078.2050806@student.kun.nl> References: <3C8785EA.5010509@student.kun.nl> <1015517388.720858@news.commspeed.net> <3C87B078.2050806@student.kun.nl> Message-ID: <20020307195946.GF29379@isis.gerrietts.net> Quoting husam (h.jehadalwan at student.kun.nl): > > I was wondering whether it is possible to create graphics objects > without the use of a external module. Imagin that you build an > application and want to let other people use it. People have to install > python, then > the extra module. The chance that my program finds its way to clients > screens is not so big. Anything's possible, but it's a lot of work, probably work you don't really want to do. Most of the freely-available packages are creatures whose redistribution is allowed. That means you could include the library in your app's package, and install it as part of the install. Or don't install it -- just build a little place for it in your app's installation and import it from there. PIL in particular is very accomodating about this; I've seen it used both globally installed and within a local source tree and it functions either way. --G. -- Geoff Gerrietts "Don't get suckered in by the comments-- they can be terribly misleading. www.gerrietts.net/geoff/ Debug only code." --Dave Storer From dortmann at lsil.com Thu Mar 14 14:18:33 2002 From: dortmann at lsil.com (Daniel Ortmann) Date: 14 Mar 2002 13:18:33 -0600 Subject: python name spaces References: <3C8C45F2.E0F6D9EC@earthlink.net> Message-ID: Just van Rossum writes: > In article , > Daniel Ortmann wrote: > > (I posted since I saw no PEP addressing these issues.) > Have you looked at PEP 227? > http://python.sourceforge.net/peps/pep-0227.html Thank you for the clue. PEP 227 has much content and will require careful reading. One thing which might aid clarity is a concise set of Scheme examples, showing the Python behavior through Scheme comparison. -- Daniel Ortmann, LSI Logic 3425 40th Av NW, Suite 200, Rochester, MN 55901 dortmann at lsil.com / 507.529.3887 (w) / 535.3887 (int) ortmann at isl.net / 507.288.7732 (h) From BPettersen at NAREX.com Thu Mar 7 14:50:35 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Thu, 7 Mar 2002 12:50:35 -0700 Subject: Integers class...? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192215155@admin56.narex.com> > From: Magnus Lie Hetland [mailto:mlh at vier.idi.ntnu.no] > > With all this talk about iteration etc. I just thought I'd > chuck in another idea. It is similar to several earlier ideas > (and may even have been proposed in exactly this form before > -- I just haven't seen it, or at least can't remember it). > > One of the interval syntaxes (e.g. for for-loops) I'd like is > something like [0, 2 .. 10], similar to Haskell. [snip] As was mentioned the last time this proposal came up, it doesn't deal well with half open intervals, i.e.: for i in [0, 1, ... len(mySeq)-1]: is prone to off-by-one errors. By itself though I think it fits in the "cute" category , so feel free to write up a PEP suggesting the change... -- bjorn From laytonjb at bellsouth.net Fri Mar 29 14:29:31 2002 From: laytonjb at bellsouth.net (Jeff Layton) Date: Fri, 29 Mar 2002 14:29:31 -0500 Subject: Newbie: List of instances? Message-ID: <3CA4C09B.D9D15464@bellsouth.net> Hello, I'm still learning Python and I'm playing around with some code that creates a class. I've mastered that stage already. However, what I want to do is create multiple instances of the class and put them into a list. If the class is called Bob, then I want to do something like, a = [] a[0] = Bob('input1') and so on. Everytime I try something like this I get the following error message: a[0] = Bob( 'localhost' ) IndexError: list assignment index out of range I also tried it this way, a = [] a.append = Bob('localhost') and I get the error message: a[0] = Bob( 'localhost' ) IndexError: list assignment index out of range Can anyone shed some light into how I do this? Or is there a better way? TIA, Jeff From huaiyu at gauss.almadan.ibm.com Mon Mar 4 18:06:49 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Mon, 4 Mar 2002 23:06:49 +0000 (UTC) Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: I wrote: > >Produces >1e+200 inf 34 Numerical result out of range 34 >1e-200 0 34 Numerical result out of range 34 Ah! Now I understand what Tim and others are talking about. If I link the C program with -lieee, I get 1e+200 inf 0 Success 34 1e-200 0 0 Success 34 So my question now is: What do I do to tell Python to compile with -lieee? In the source tree there are several places that mention this, but none of which looks like meant for hand editing. The lines in ./pyconfig.h /* Define if you have the ieee library (-lieee). */ /* #undef HAVE_LIBIEEE */ looks like it. But since it's already commented out, does that mean HAVE_LIBIEEE is already defined? Huaiyu From stephen at xemacs.org Fri Mar 1 06:34:59 2002 From: stephen at xemacs.org (Stephen J. Turnbull) Date: 01 Mar 2002 20:34:59 +0900 Subject: PEP 263 comments References: <87g03lhm3p.fsf@tleepslib.sk.tsukuba.ac.jp> <87pu2oeqq9.fsf@tleepslib.sk.tsukuba.ac.jp> Message-ID: <87u1s0bjx8.fsf@tleepslib.sk.tsukuba.ac.jp> >>>>> "Martin" == Martin v Loewis writes: Martin> "Stephen J. Turnbull" writes: >> IMO, the Python source code parser should never see any text >> data[1] that is not UTF-8 encoded. If you want to submit >> Python programs to the parser that are not UTF-8 encoded, then >> it is your responsibility as the programmer to make sure they >> get translated into UTF-8 (eg, by the preprocessing hook) >> before the interpreter proper ever sees them. Martin> That would cause surprises to users. They have a source Martin> program that says Martin> # -*- coding: koi8-r -*- Martin> print "some cyrillic text" Martin> This currently works fine on their system; the text comes Martin> out on the terminal just right. Now, Python would convert Martin> this text silently to UTF-8 behind their backs, and the Martin> terminal would show just garbage. No, it shows "Error: non-UTF-8 data detected in string." Conversion only takes place if a preprocessing hook function is defined, and the same environment that provides an appropriate preprocessing hook will also arrange to make sure that program I/O is done in KOI8-R, too. But I take your point. It will take time to develop such environments. In the interim, it will cause users who are currently depending on undefined behavior pain. You _can_ say "no" now, while things are undefined. Or you can change the language definition to promise support. If you do that, you are unlikely to be able to get rid of that support for decades, as legacy software will depend on it. Martin> How to print it is then another issue; you'll have to Martin> figure out the encoding of the terminal - that is Martin> feasible in most cases. Why open up that Pandora's box? Push it out into user space. Support them as much as you want to with libraries, give up when it gets too hard (it will!). My experience is that users will not thank you for anything less than perfect support for all coding systems yesterday, if the language definition promises any support at all. If the language definition says "UTF-8 or die", they will thank you for the nice codecs you provide to ease the transition. >> [1] Ie, Python language or character text. It might be >> convenient to have an octet-string primitive data type, in >> which you could put EUC-encoded Japanese or Java byte codes. Martin> The traditional "string" type is, in fact, a byte string Martin> type. Many people use it still for character strings, Maybe you don't need a third type. I see it as a matter of a transition strategy, to allow you to generate exactly the error I suggest above. -- Institute of Policy and Planning Sciences http://turnbull.sk.tsukuba.ac.jp University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN Don't ask how you can "do" free software business; ask what your business can "do for" free software. From sjmachin at lexicon.net Sat Mar 16 20:01:22 2002 From: sjmachin at lexicon.net (John Machin) Date: 16 Mar 2002 17:01:22 -0800 Subject: Enhanced information from common exceptions Message-ID: An example: >>> alist = [4,3,2,1] >>> alist[42] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range >>> Suppose this was actually in a script somewhere. IMO, it would be much more useful for Python developers of all levels were the message to be something like: IndexError: list index 42 not in range(4) Often this extra info would lead to problem recognition & resolution without the need for an extra step (print statement or debugger). Perhaps if people cared to nominate their "favourite" high-frequency-low-information exception message(s), together with suggested changes, we could put together a nanoPEP on this topic -- or simply just propose a few patches. From jimd at vega.starshine.org Tue Mar 26 03:20:12 2002 From: jimd at vega.starshine.org (Jim Dennis) Date: 26 Mar 2002 08:20:12 GMT Subject: How to get a key from dictionary? References: <3C9FAFCC.20062.91741D@localhost> Message-ID: In article , Don Arnold wrote: >> Hi, >> Is there a possibility to get, from a dictionary, a key according to a >> value ? >> For example >> I have a dictionary >> dict={'aa':1,'bb':2} >> and >> dict['aa'] >> is 1 You could create your own class which maintained *two* dictionaries. For every insertion into the main dictionary you'd insert an entry into the self.valuedex dictionary. You could have an instance flag determine whether to allow non-unique values. If you allow non-unique values then each key in the "valuedex" or "reverse_index" would be a list (of the keys where this value is stored). If you require unique values (as well as unique keys) then you can raise a suitable exception when you detect a violation of this policy (maybe you'd create a "ValueConstraintException" as a subclass of KeyError or something like that). You might need another instance flag to handle any attempt to use lists (or other mutable objects) as values to assign into your "doubly indexed" dictionary. For simple flat lists it might be reasonable to generate a tuple as the key for the reverse mapping (valuedex). Any you'll have to decide what sort of exception to raise for situations where you can't think of a suitable hashable representation of the value being added to the dictionary. It would even be possible to implement this with lazy evaluation of the reverse mapping. Thus you'd leave the reverse mapping (valuedex) empty until an attempt to search it was made. Then you'd generate it. Upon subsequent reverse searches you might check the dictionary first, return if found, and only re-generate/update the reverse mapping when necessary. (Intuitively I suspect that this would only make sense when "unique value" constraints were in place; and possibly it would defer the checking for invalid (mutable/non-hashable) values until it was unrecoverable; until it might be non-sensical to trap those exceptions). Anyway, those are your choices: If you want fast and efficient access to the "keys" from the "values" then you need to index those as well (most readily done by maintaining a reverse mapping dictionary). This entails some of the same constraints on your values that you should already expect from your keys (uniqueness and hashability/immutability). If you don't need the reverse access to be as fast or efficient then you can simply iterate over the items list; either breaking on the first match (if you expect your values to be unique, or if you only want a single match) or looping through the whole list of items and building a list of return values. A simple list comprehension method for getting all of the keys for a give value is: matches = [ x for x,y in d.items() if y ... ] ... where d is the dictionary, and ... is replaced with some comparison or conditional. I could wrap that pattern in a function: def searchvalues(d,f) return [ x for x,y in d.items() if f(y) ] ... though the invocation might be a bit non-intuitive since it would require that the user construct some sort of function, possibly a lambda function which would only take one argument and return a boolean on it. This hides the condition being tested in a remote bit of code. If I had a real need for this I might come up with a way to pass additional arguments to searchvalues (kind of like the os.path.walk() function). In practice my comparison function might be a closure, though the scoping for that might become a bit of a nightmare. From fperez528 at yahoo.com Sat Mar 2 06:11:04 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 02 Mar 2002 11:11:04 +0000 Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: Fernando Pereira wrote: > It's not Python 2.2 itself: > > % python > Python 2.2 (#1, Feb 10 2002, 13:29:43) > [GCC 2.95.2 19991024 (release)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> 1e-200**2 > 0.0 Ok, some more details to try and find who the culprit is: [~]> uname -a Linux maqroll 2.4.8-26mdk #1 Sun Sep 23 17:06:39 CEST 2001 i686 unknown [~]> gcc -v Reading specs from /usr/lib/gcc-lib/i586-mandrake-linux-gnu/2.96/specs gcc version 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk) [~]> python Python 2.2 (#1, Jan 17 2002, 21:03:58) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.71mdk)] on linux-i386 Type "help", "copyright", "credits" or "license" for more information. >>> 1e-200**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: (34, 'Numerical result out of range') This python2.2 was built by myself on a Mandrake 8.1 box (which comes with 2.1 by default). So it probably is a gcc/glib bug of some sort, but I don't really know where. Cheers, f. From skip at pobox.com Tue Mar 26 06:26:42 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 26 Mar 2002 05:26:42 -0600 Subject: Indentation problem In-Reply-To: <7ieli7an7s.fsf@enark.csis.hku.hk> References: <7isn6o9fld.fsf@enark.csis.hku.hk> <7ieli7an7s.fsf@enark.csis.hku.hk> Message-ID: <15520.23282.195124.192641@12-248-41-177.client.attbi.com> Isaac> This is somewhat close to what I say, but a little bit off: it Isaac> won't reindent to the correct tab width. E.g., if you have the Isaac> following Isaac> def f(a): Isaac> print("Trying " + a) Isaac> if (a <= 0): Isaac> return 1 Isaac> else Isaac> return a * f(a-1) Isaac> print("Done") Isaac> and you try to use the C-c > command, you end up with Isaac> def f(a): Isaac> print("Trying " + a) Isaac> if (a <= 0): Isaac> return 1 Isaac> else Isaac> return a * f(a-1) Isaac> print("Done") Isaac> It still works, but it doesn't look nice. What I want is a real Isaac> reindentation which understand how Python reads indentation, Isaac> making it Isaac> def f(a): Isaac> print("Trying " + a) Isaac> if (a <= 0): Isaac> return 1 Isaac> else Isaac> return a * f(a-1) Isaac> print("Done") Now that I understand better... You are asking to transform one syntactically correct piece of Python into another. Starting from your first example you can't get to your third example without some human input on the correct nesting. C-c > gets you to a functionally correct state (your second chunk of code would presumably not generate a NameError and would emit the desired output). For small bits of code, you can just reindent the over-indented lines with the TAB key. For larger chunks of code you can use the reindent.py program in the Tools/scripts directory of the Python distribution to adjust the amount of indentation so it is uniform. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From ykingma at accessforall.nl Mon Mar 4 13:55:20 2002 From: ykingma at accessforall.nl (Ype Kingma) Date: Mon, 04 Mar 2002 19:55:20 +0100 Subject: Text Search Engine that works with Python References: Message-ID: <3C83C312.756378F8@accessforall.nl> Doug Farrell wrote: > > Hi all, > > I'm wondering if anyone knows of a text search engine that works with > Python? What I'm looking for specifically is something that will compress > the text and still allow searches and retrievals that can be exact matches > or proximity based. The text I want to compress and search is huge (70 megs) > and should compress down to half, not including any index files that might > be required by the search engine. Anyone know of anything like this or any > ideas? In case you can use Jython as your Python implementation, have a look at Lucene http://jakarta.apache.org/lucene/docs/index.html . You'll have to do the compression yourself, but you can store any field with a document, including one that is filtered through a zip outputstream from the standard java libraries. You might consider storing only a reference to a file containing the compressed text of your documents. Lucene searches very fast. For 500 Mb of indexes in 15 lucene dbs, typical query time is less than a second for all databases together on a 400Mhz machine. Typical index size is around one third of original text. The 15 dbs are my own choice, lucene could easily handle everything in a single db. Apart from exact matches and proximity you can also use prefix terms and required terms. Lucene is optimized to retrieve only the best matches to a query, but you can also use it's API in boolean mode. Recommended, especially together with the lucene-users list. Ype From db3l at fitlinxx.com Wed Mar 20 18:07:00 2002 From: db3l at fitlinxx.com (David Bolen) Date: 20 Mar 2002 18:07:00 -0500 Subject: Java and Python References: Message-ID: Michael Chermside writes: > Jan Dries writes: > >> May I ask you what the scale for your webapp was? (Because MySQL is > >> related to small to mid-size web applications). Is it the same case with > >> Python? > > > > FWIW, a recent benchmark test in Eweek showed MySQL to be comparable to > > Oracle 9i with respect to both performance and scalability. > > See http://www.eweek.com/article/0,3658,s=708&a=23115,00.asp > > And please not that this benchmark used MySQL in *transaction* mode, > same as Oracle. When used without transactions it's even faster. I must > say, I was quite surprised... I thought Oracle was further ahead. True, but the transaction driver was carefully chosen to only apply to a subset of the tables, so I'm not sure if it would have been the same if all tables were transactioned. Very respectable, nevertheless. -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From sab at NOSPAM.freeuk.com Sat Mar 9 15:36:33 2002 From: sab at NOSPAM.freeuk.com (G. Willoughby) Date: Sat, 9 Mar 2002 20:36:33 -0000 Subject: Gurus, I wonder if you can take a look at this source code? Win32... Message-ID: Hi, I have started writing a text editor for Win32 platforms and i wonder if anyone has a few minutes spare just to take a look at the source code and give me a little constructive critisism? I have been learning python on and off for about a year as my first (real) language (well not including a year with javascript) and i would like to hear if i am heading in the right direction. I have choosen a text editor as a project 'cos it could be as large and feature filled as i wanted, a good execise i thought. the thing i struggle with a little is knowing when and where to use classes and if i am using them right? anyway your time would be greatly apprieciated for any views u have. You can find it here (15.4kb): http://www.garyw.uklinux.net/Larchv1.0a.zip Thanks G. Willoughby P.S. remember i am still working on it, lots of funtionallity remains to be added! :) From johnroth at ameritech.net Fri Mar 15 09:13:44 2002 From: johnroth at ameritech.net (John Roth) Date: Fri, 15 Mar 2002 09:13:44 -0500 Subject: Windows Installation References: <7gdk8.277$ID.1679@news.hananet.net> Message-ID: "Jonathan Gardner" wrote in message news:7gdk8.277$ID.1679 at news.hananet.net... > I have a free software program (http://sf.net/projects/bttotalcontrol/) and > I am having great difficulty writing an installation script for windows. > > I don't want to use distutils because I am not writing a module - but an > entire distribution with images, data files, and executable programs. I > would like to put icons on the desktop and stuff in the start menu as well. > > I am at a major disadvantage because I don't have access to a windows > machine, and so I can't test anything directly. However, I do have a few > people who actively test for the project at home. > > Anyone have any suggestions on where I should go? Anyone can help me out > here? I took a quick look at your project, and it seems like most of what you want is simply copying files from your package into appropriate directories. Putting something into the start menu is dead easy. Just put a link to the appropriate file into "c:Windows/Start Menu/Programs" Note the blank, and watch your capitalization. Windows is flaky about capitalization. Putting an icon on the desktop is a bit more difficult. AFIK, that has to go into the registry, and hacking the registry is not for the faint of heart, especially if you're doing it remotely. Everything else you said you want to do can be backed out manually, with a little effort. You didn't mention whether you wanted to register a file type so a program gets launched when you double click a file. If so, I'd really recommend getting an installer package - that's midlevel registry sorcery. You might want to check the Vaults to see if there is code you can use. John Roth > > Jonathan > From psage at ncaustin.com Tue Mar 26 14:07:18 2002 From: psage at ncaustin.com (Paul Sage) Date: Tue, 26 Mar 2002 13:07:18 -0600 Subject: TKinter question - A combo box / menu question Message-ID: <03F53405C6ED434A986221919785A6A7106BE7@nca-postal.ncaustin.com> I am trying to build a very simple menu portion of a program. I have the main frame created and the menu box is a widget in that frame. The menu is a straight pull down menu. However, in the "LOAD" part of the menu where I would like to create a pop-up combo box when load is selected from the menu. I have created both working widgets, but every time I execute the program, it pops up the ComboDialogBox. I want this box to be a part of an event, not actually being built. Can anyone help with this? class TopMenuBar: def __init__(self, parent): menu_Bar = Frame(parent, relief=GROOVE, borderwidth =1) menu_Bar.pack(fill=X) FileBtn = self.player_Load_Menu(menu_Bar) ConfigureBtn = self.player_Configure_Menu(menu_Bar) def player_Load_Menu(self, menu_Bar): #Create the first top menu item CmdBtn = Menubutton(menu_Bar, text='Character Selection', underline=0) CmdBtn.pack(side=LEFT) CmdBtn.menu = Menu(CmdBtn, tearoff=0) #Begin creating the items in the first top menu CmdBtn.menu.add_command(label="Load Form", command=self.open_file(menu_Bar)) CmdBtn.menu.add_command(label="Save Form", command=self.save_file) CmdBtn.menu.add_command(label="New Form", command=self.new_file) CmdBtn.menu.add('separator') CmdBtn.menu.add_command(label="Quit", command=self.quit_file) CmdBtn['menu'] = CmdBtn.menu return(CmdBtn) def player_Configure_Menu(self, menu_Bar): #Create the second top menu item CmdBtn = Menubutton(menu_Bar, text='Configure Form', underline=0) CmdBtn.pack(side=LEFT) CmdBtn.menu = Menu(CmdBtn, tearoff=0) #Begin creating the items in the second top menu CmdBtn.menu.add_command(label="Add level", command=self.add_level) CmdBtn.menu.add_command(label="Subtract level", command=self.subtract_level) CmdBtn['menu'] = CmdBtn.menu return(CmdBtn) def open_file(self, parent): #Need the listofcharacters to be a tuple sequence. from char_edit_combo_load import * forms = [] listOfCharacters = tuple(getFiles(forms)) dialog = Pmw.ComboBoxDialog(parent, title = "Character Load", buttons = ('OK', 'Cancel'), defaultbutton = 'OK', combobox_labelpos=N, label_text="Please select a character", scrolledlist_items=listOfCharacters, listbox_width=22) dialog.withdraw() result=dialog.activate() # The function has now opened seen the selection, time to open the file. if result == 'OK': return(readObjectFromFile(dialog.get())) else: return(None) -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Mon Mar 18 18:43:00 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 19 Mar 2002 10:43:00 +1100 Subject: Declare list of large size Message-ID: > From: marduk [mailto:marduk at python.net] > > On Mon, 2002-03-18 at 16:44, Aaron Ginn wrote: > > > > Perhaps I've just glossed over this in the documentation, > but what is > > the simplest way to declare a list of large size? Is there > something > > analogous to the following in C: > > > > int list[100]; > > > > list = [0]*100 But note that this is only safe for immutable elements. You will obtain a reference to the *same* object as each element. This normally bites people when they try to make multi-dimensional arrays ... list = [[0] * 2] * 2 print list list[0][0] = 1 print list [[0, 0], [0, 0]] [[1, 0], [1, 0]] As you can see, the first element of each sub-list has been changed - this is because each sub-list is in fact the same list! Tim Delaney From kennedy.bill.nospam at freeuk.com Thu Mar 7 03:23:45 2002 From: kennedy.bill.nospam at freeuk.com (William Kennedy) Date: Thu, 07 Mar 2002 08:23:45 GMT Subject: NoteTab Lite Message-ID: Does anyone use the NoteTab series of editors for their coding, if so do they have a Python library I can have. Many Thanks in advance --- William Kennedy remove the .nospam from my email address From brueckd at tbye.com Mon Mar 18 10:58:10 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 18 Mar 2002 07:58:10 -0800 (PST) Subject: Converting relative URLs to absolute In-Reply-To: <23891c90.0203180259.26e87496@posting.google.com> Message-ID: On 18 Mar 2002, Paul Boddie wrote: > wrote in message news:... > > > > Rather than add a new module, why not add more functionality to the > > urlparse module in the standard distribution? (what functionality do you > > need beyond what's already there, anyway?) > > I wouldn't want to add a new module - it's most interesting to tidy up > what's already there, adding better "split" functions to urllib (and > urllib2), and adding some "join" functions too. I certainly wouldn't > advocate adding a huge dependency on some other library, even though > some interesting candidates exist. But URL split and join functions already exist in the urlparse module (urlparse, *not* urllib). See urlparse's urlparse, urlunparse, and urljoin functions - what don't they do that you need? They certainly handle the make-relative-URLs-absolute problem. -Dave From eric.brunel at pragmadev.com Mon Mar 18 06:16:55 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 18 Mar 2002 11:16:55 +0000 Subject: Process to process synchronization (unix) References: Message-ID: Gillou wrote: > I have a Zope application and another running process (in python too). > I need to transmit data and signal (hey ! data available, do your job !) > in an asynchronous way from the Zope app (in an external method) to the > python running process (that runs for another user). > The other process waits for the signal, takes given data, does the jobs > and waits further signal (...) > I'm 99.9% newbie in process to process communication. > What packages are helpful for this ? The two means that come to my mind are: - named pipes: quite easy to handle, as they are manipulated just like files. The problems are that named pipes are quite difficult to synchronize if both processes should send data to the other, and that's it's a Unix-only solution. All functions manipulating named pipes are built-ins or in module os. If you choose that, I may also provide a few simple examples. - sockets: a bit trickier to handle, but far more practical for two-way communications and multi-platform. The Python module to handle them is simply socket. There's an example in the library reference (see http://www.python.org/doc/current/lib/socket-example.html). HTH - eric - From tejarex at yahoo.com Fri Mar 15 09:11:39 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Fri, 15 Mar 2002 14:11:39 GMT Subject: Dear Guru, I have added def and it doesnt work Sincerly, F References: Message-ID: "Federico Caboni" wrote in message news:B8B793EA.D35%msx at crs4.it... > BTW... I think that's a proof of Python's beauty. > The statement worked exactly as I espected, and had the same name I > Expected too... > I don't think I could just do the same with C pointers ;) Guessing is fine as long as you make an attempt to correct mistakes by reading basic materials before asking publicly. People are most willing to help those who try to help themselves first by exploring the resources readily available. Terry J. Reedy From gh_pythonlist at gmx.de Fri Mar 15 02:39:11 2002 From: gh_pythonlist at gmx.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: Fri, 15 Mar 2002 08:39:11 +0100 Subject: Dear Guru, I have added def and it doesnt work Sincerly, F In-Reply-To: References: Message-ID: <20020315073910.GA61354@lilith.hqd-internal> * Federico Caboni [2002-03-15 09:09 +0100]: > I discovered "eval" by guessing.... > I thought something like "It would be cool if existed a statement like > that". > I guessed the name too =). > Well...I agree that this is not the right way to learn Python anyway ;) At school we had a programming language called COMAL, which basically Pascal with a more BASIC-like syntax. At the time, I tried to figure out commands we hadn't learnt yet by examining the interpreter executable with a hex editor. My logic was that there must be a list of reserved words somewhere, and bingo, there was 8-) Gerhard -- This sig powered by Python! Au?entemperatur in M?nchen: 7.4 ?C Wind: 2.5 m/s From laytonjb at bellsouth.net Fri Mar 29 15:57:18 2002 From: laytonjb at bellsouth.net (Jeff Layton) Date: Fri, 29 Mar 2002 15:57:18 -0500 Subject: Newbie: List of instances? References: Message-ID: <3CA4D52E.C2067419@bellsouth.net> Susan Williams wrote: > >Hello, > > > > I'm still learning Python and I'm playing around with some > >code that creates a class. I've mastered that stage already. > >However, what I want to do is create multiple instances of > >the class and put them into a list. > > If the class is called Bob, then I want to do something like, > > > > > >a = [] > >a[0] = Bob('input1') > > > >and so on. Everytime I try something like this I get the following > >error message: > > > >a[0] = Bob( 'localhost' ) > >IndexError: list assignment index out of range > > Yeah, that is definitely a "no go". You can't refer to a[0] > because it doesn't exist--a is empty. > > > I also tried it this way, > > > >a = [] > >a.append = Bob('localhost') > > > >and I get the error message: > > > >a[0] = Bob( 'localhost' ) > >IndexError: list assignment index out of range > > This is closer. a itself is an object, and the way you deal > with it, at least for some functions, is thru its methods. > append is a method of the list object, so what you really want > is: > > a.append(Bob('localhost')) This works! If I create a list a that has five elements where are just instances of Bob, can I "call" a method for a specific element of the list? I take I can (Jeff sneaks off to experiment while his wife is napping). Thanks! Jeff > > > > > >TIA, > > > >Jeff > > susan From fperez528 at yahoo.com Fri Mar 15 11:24:11 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 15 Mar 2002 16:24:11 +0000 Subject: multiline raw input References: Message-ID: les ander wrote: > Hi, > i have a program that takes input from the command line > however this input is multi-line and will have a lot of backslashes > I tried using sys.stdin but it ignores the backslashes. > i tried with raw_input but that only takes in the first line > > can some suggest a remedy? > > > > > for example: > i would like to run my program as follows: > >>> myprog.py > Type in some input (type in '.' to end) : > \sum_{i=1}^{n} \frac{\sqrt{2}}{\alpha} \infty > \begin{itemize} > \item this equation says that > \end{itemize} > . Untested (written in the newsposter :). See if it helps: print "Type in some input (type in '.' to end) :" input_list = [] while 1: input = raw_input() if input == '.': break input_list.append(input) # do whatever you want with input_list... ... Writing some sort of interactive LaTeX prompt here ?? Cheers, f. From arthuralbano at hotmail.com Sat Mar 9 10:24:00 2002 From: arthuralbano at hotmail.com (Arthur Albano) Date: Sun, 10 Mar 2002 00:24:00 +0900 Subject: [DB-SIG] Passing Unicode strings to Database Message-ID: >From: Mikhail Astafiev >Reply-To: Mikhail Astafiev >To: db-sig at python.org, python-list at python.org >Subject: [DB-SIG] Passing Unicode strings to Database >Date: Wed, 6 Mar 2002 18:11:17 +0700 > >[Env: Win2k, Python 1.5.2] > >Hi people! > >I have a string in Japanese encoded in UTF8. I need to put it into >database in Unicode form. > >import dbi, odbc >o=odbc.odbc(self.ODBC_name+"/"+self.ODBC_sql_username+"/"+self.ODBC_sql_password) >c=o.cursor() >runes = >UTF82Runes(string.replace(self.pr_table[row]["description"],"'","''")) >operator="""INSERT INTO %s VALUES('%s','%s');"""%(self.ODBC_table, > int(self.pr_table[row]["pr_no"]), > runes.tostring()) >c.execute(operator) # update database > >I'm getting the following error trace: > >Traceback (innermost last): > File "C:\dev\Products\MRATES~1\server.py", line 34, in ? > PR.sync_all() > File "C:\dev\Products\MRATES~1\PRML\code\prml.py", line 2837, in >sync_all > self.__sync_with_sql__(i) > File "C:\dev\Products\MRATES~1\PRML\code\prml.py", line 2797, in >__sync_with_sql__ > c.execute(operator) # update database >TypeError: argument 1: expected string without null bytes, string found > >runes is array.array('H') containing Unicode string. > >Database string field has "ntext" type. How can I overcome this >problem? > >Thanks in advance, >Mick. Mikhail, If the problem is just conversion from UTF-8 to UNICODE, try this: unicode(string_in_utf8_to_be_converted,'UTF-8') It returns a unicode string. Arthur Albano "Just a Weekend Programmer" _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp. From ron at ire.org Thu Mar 7 09:59:18 2002 From: ron at ire.org (ron nixon) Date: 7 Mar 2002 06:59:18 -0800 Subject: very newbie question Message-ID: <61ff32e3.0203070659.28cf5e1c@posting.google.com> I've got a script called snakes saved to my c: drive and I want to run it from IDLE. By when I do file open and run script, I get an invalid syntax message. Likewise if I write the script in IDLE and hit "run script" it get a message saying that says "the buffer for Python Shell is not saved. Please save it first." Soooo. With all that being said. How do I save a script and then get python to execute it from IDLE(and where in the documentation is this?) Thanks in advance From grante at visi.com Tue Mar 12 00:24:30 2002 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Mar 2002 05:24:30 GMT Subject: Raw Ethernet under Win32? Message-ID: Is there any way to do raw Ethernet packets under Win32 Python? It doesn't appear that Winsock supports raw Ethernet (and I know for sure that it's not supported under Win32 by Python's socket module). Is there some other Win32 API way to do it? I've done some googling around and have found a couple libraries that do ICMP, or let you muck about with the TCP and IP headers, but none that appear to let an application do non-IP raw Ethernet frames. -- Grant Edwards grante Yow! If this is the DATING at GAME I want to know your visi.com FAVORITE PLANET! Do I get th' MICROWAVE MOPED? From tim.one at comcast.net Sat Mar 9 15:58:40 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 09 Mar 2002 15:58:40 -0500 Subject: PEP 284, Integer for-loops (code bash?) In-Reply-To: <200203091809.g29I9QtB024853@ratthing-b246.strakt.com> Message-ID: [Laura Creighton] > ... > 2. Haskell, which I mispelt, shame on me, I know better, is a > functional language. > ... > So, what I meant was 'I wish that Guido had used Haskell's syntax > for arithmetic sequences in Python's for loops'. That is as > follows: > > [1..10] => [1,2,3,4,5,6,7,8,9,10] > [1,3..8] => [1,3,5,7] > [1,3..] => [1,3,5,7,9, ... (infinite sequence) > > This is not restricted to numbers, char works great. > ... > I have probably forgotten something, somebody else can add it. Easier to point than to retype: http://aspn.activestate.com/ASPN/Mail/Message/909806 Note a practical difficulty in adopting this to Python (beyond adding 4 new method slots to every type that wants to participate): the frequent Python range(len(seq)) maps to Haskell [0 .. len(seq)-1], and that's begging for off-by-1 errors in real life. Saying that a Python version went "up to but not including" the right endpoint would be an ugliness of a different sort. > 3. Make the time to learn Haskell. It is simply too much fun. Yes it is! Haskell is the most Pythonic of all languages that have nothing in common with Python. Well, they do have one thing in common: they both drive Scheme True Believeers mad . albeit-for-different-reasons-ly y'rs - tim From flognat at flognat.myip.org Sat Mar 2 03:59:50 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Sat, 02 Mar 2002 08:59:50 GMT Subject: What have I missed with the lists?? Flattening two trees.. References: Message-ID: ahh if i do alist=[] blist=[] print a.flatten(alist) print b.flatten(blist) instead, it works as it shouldhmm what have I missed? is the default list to the dig function initialized at first parse, and not runtime as I thought? /Andy | | print a.flatten() | print b.flatten() | | -- | The eye of the beholder rests on the beauty! -- The eye of the beholder rests on the beauty! From cce at clarkevans.com Tue Mar 12 18:24:40 2002 From: cce at clarkevans.com (Clark C . Evans) Date: Tue, 12 Mar 2002 18:24:40 -0500 Subject: RFC PEP candidate: q''quoted ? In-Reply-To: ; from bokr@oz.net on Sun, Mar 03, 2002 at 09:50:58AM +0000 References: Message-ID: <20020312182440.A73129@doublegemini.com> On Sun, Mar 03, 2002 at 09:50:58AM +0000, Bengt Richter wrote: | Problem: How to put quotes around an arbitrary program text? I would suggest that this is done via indentation, like YAML. With indentation you don't need to have an end delimiter. Clark From jcosby at mindspring.com Sun Mar 31 11:56:09 2002 From: jcosby at mindspring.com (Jon Cosby) Date: Sun, 31 Mar 2002 08:56:09 -0800 Subject: List problem References: <3CA7321A.DF13361A@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3CA7321A.DF13361A at engcorp.com... > Jon Cosby wrote: > > > > This is strange. I've added some lines to see where this is failing. > > You can see below the interpreter is not detecting matches, but they > > are there, and it is showing them. There is something in > > word[0] == firstword[i] that's not right or the interpreter isn't > > understanding. What could possibly be wrong with this? > > Well, there's certainly nothing wrong with that, so it must be > something else's understanding that is wrong... > > > for word in words: > > for i in range(lword): > > l.append(word[0] + ":" + firstword[i]) > > if word[0] == firstword[i]: > > cols[i].append(word) > > [...] > > C:\Python21>python projects\wordsquare.py > > Enter first word (enclosed in quotes): "add" > > 502 > > [[], [], []] > > ['A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', > > 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', 'A:a', 'A:d', 'A:d', > > Are you sure you aren't forgetting case-sensitivity? I still > don't really understand your code, but I get a sense from the > above that you are expecting "AWORD" to equal "aword", which > is not the case (no pun intended). > > If this is true, try using word[0].upper() == firstword[i].upper(). > > -Peter Ouch! That's embarassing. Thanks for pointing it out. Jon From aahzpy at panix.com Thu Mar 14 09:46:16 2002 From: aahzpy at panix.com (Aahz) Date: 14 Mar 2002 09:46:16 -0500 Subject: SF vs. Lynx (was Re: zlib vulnerabilities and python) References: <7xr8mnfdke.fsf@ruckus.brouhaha.com> Message-ID: In article <7xr8mnfdke.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >aahzpy at panix.com (Aahz) writes: >> >> OTOH, I still can't submit my stupid bug report AFAICT. Is there anyone >> who uses Lynx to access SF? > >Yes, I do sometimes. Have you ever submitted a bug report using Lynx? If yes, what version are you using? To people who have suggested other text-mode browsers: my experience is that they don't support the vi-like functionality that Lynx does, which makes them difficult to use. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. --Aahz From ak at silmarill.org Tue Mar 26 22:53:12 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Wed, 27 Mar 2002 03:53:12 GMT Subject: list of empty lists References: <3CA11A5B.5000501@bioeng.ucsd.edu> Message-ID: In article <3CA11A5B.5000501 at bioeng.ucsd.edu>, Curtis Jensen wrote: > Is there a easy way to make a list of an arbitray number of empty lists? > > I can do something like: > >>> some_number = 3 > >>> l = [[]] * some_number > >>> l > [[], [], []] > > Unfortunatly this has an unfortunate side affect. Whatever I do to one > of the list gets done to the other lists. ie: > >>> l[0].append(1) > >>> l > [[1], [1], [1]] > > > In this case, what I would like is three independantly empty lists. I > can make a for loop to loop "some_number" of times and append an empty > list at each itteration. Is there a simpler way? > Thanks. > I think loop is the simplest way. > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From scott2237 at yahoo.com Wed Mar 13 23:40:39 2002 From: scott2237 at yahoo.com (googlePoster) Date: Thu, 14 Mar 2002 04:40:39 GMT Subject: trouble testing for existance of variable References: <4bbaa6d6.0203121352.4358f14@posting.google.com> Message-ID: I tried try: ct = vim.exists("colors_name") # doesn't work when not defined except vim.error: curr_color = "none" if ct > 0: curr_color = vim.eval('colors_name') and got AttributeError: 'module' object has no attribute 'exists' apparently 'exists' is supported in vim, but not python's portal to it From peter at engcorp.com Wed Mar 20 23:43:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 20 Mar 2002 23:43:43 -0500 Subject: #define equivalents and config files References: <3C9963BD.1040304@verizon.net> Message-ID: <3C9964FF.46805590@engcorp.com> Rich Salz wrote: > > > Is there a pythonic way of doing something similiar to Cs #define? > >... are globals the only way to go? > > You can at least make them class attributes > class constants: > pi = 3.14159 > e = 2.71828 > adding your own setattr can serve to make them read-only. That wouldn't help when one needed to change the values... ;-) From rjones at ekit-inc.com Wed Mar 27 22:40:53 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 28 Mar 2002 14:40:53 +1100 Subject: RFC: logging module message hub and user interfaces Message-ID: <200203280341.DAA18129@crown.off.ekorp.com> This is a Request For Comments on my proposed message hub and user interface plan at http://mechanicalcat.net/tech/pylogging/. Abstract -------- This document describes a proposed log message hub ("hub") and user interface ("UI") to complement the logging system described in PEP 282 and implemented in the python logging system. The hub and UI would perform the following duties: - accept messages from the logging module via the logging module's handlers (FileHandler, SocketHandler, SyslogHandler, SMTPHandler, NTEventLogHandler, SQLHandler) - redistribution of messages to other targets (just plucking ideas from the ether here) ... all the above Handlers, ElvinHandler, OpenviewHandler, SunViewManagerHandler, JabberHandler, SMSHandler - perform some action on incoming messages, possibly aggregating, dropping or forwarding - have state which would be affected by the actions and may cause new messages to be generated (ie. escalation) - present a display of the messages to a user, either graphically or textually (the most basic of these would resemble the UNIX tail -f) **Note**: it is not the intention of this proposal to implement a monitoring system like EDDIE. Monitoring of systems is performed by other components which generate log messages. It is the intention of this proposal to present those messages to users in meaningful and useful ways. **Note**: it is not the intention of this proposal to add this functionality to the core logging implementation of PEP 282. The implementation of this proposal would form a separate installation of software. Richard From mxp at dynalabs.de Wed Mar 6 08:29:57 2002 From: mxp at dynalabs.de (Michael Piotrowski) Date: Wed, 06 Mar 2002 14:29:57 +0100 Subject: HP-UX 10.2 deprecated? References: <1015292901.342132@cswreg.cos.agilent.com> <1015388069.929994@cswreg.cos.agilent.com> Message-ID: weeks at vitus.scs.agilent.com (Greg Weeks) writes: > Michael Piotrowski (mxp at dynalabs.de) wrote: > : aCC is the C++ compiler; the unbundled ANSI C compiler is cc. But > : since the OP was able to compile Python, I doubt he used the bundled > : compiler--you wouldn't get that far with a K&R compiler, I think. > > In the Makefile, the compiler was "cc -Ae", which is the ANSI > compiler plus extensions. However, in "configure", plain old cc was > used, and that is the K&R compiler in HP-UX 10.2 (but not in HP-UX > 11). This is the compiler that misunderstood the indented compiler > directives. When the ANSI C compiler is installed, cc always calls this compiler, but without -Aa or -Ae it operates in K&R mode on 10.20. To ensure that -Ae is always used, you can either say CC='cc -Ae' ./configure or you can set export CCOPTS=-Ae The CCOPTS environment variable is also very handy for adding additional include paths, etc. for cc. > : My guess is that, like this problem, most problems on HP-UX are in > : configure. 10.20 and threads is, ahem, a bit problematic; the DCE > : threads are _not_ POSIX threads. > > It sounds like I'm lucky that my Python 1.5.2 threads are working on > HP-UX 10.2! I should perhaps just be content with that? That's not what I meant ;-) If a program supports DCE threads, no problem. But if a program thinks you've got POSIX threads while you really only have DCE threads you'll run into trouble. -- Michael Piotrowski, M.A. From gerhard at bigfoot.de Sun Mar 17 13:55:28 2002 From: gerhard at bigfoot.de (Gerhard =?iso-8859-15?Q?H=E4ring?=) Date: 17 Mar 2002 18:55:28 GMT Subject: Gumbie: a GUI Generator for Jython References: <3C94E29F.A48FE107@earthlink.net> Message-ID: Ron Stephens wrote in comp.lang.python: > [...] I think there must be lots of "non programmers" who want to > find an easy way to convert simple command line Python scripts into > simple GUI input-output programs. Python makes writing simple > command line scripts easy enough for part time duffers; but how to > create the gui??? I haven't' checked out easy gui yet, [...] I've never heard of "easy gui", but what you probably mean is anygui. It's designed exactly for simple GUI programs, and it has several backends, including curses, Tk, wxPython, PyQt, Java and others. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0 public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From tim at lesher.ws Mon Mar 11 15:20:50 2002 From: tim at lesher.ws (Tim Lesher) Date: 11 Mar 2002 12:20:50 -0800 Subject: Rule Engine in Python References: Message-ID: lee.ingram at 432one.com (Lee Ingram) wrote in message news:... > I have used Google to scour the web looking for an implementation of a > rules engine using Python. The book Programming Python: Second Edition has an implementation of a rules engine called 'holmes' on its CD. You might want to check that out. -- Tim Lesher tim at lesher.ws From mwh at python.net Sun Mar 3 11:55:02 2002 From: mwh at python.net (Michael Hudson) Date: Sun, 3 Mar 2002 16:55:02 GMT Subject: Useful, robust shell utilities References: Message-ID: "Donn Cave" writes: > Quoth Jonathan Gardner : > | I tried to use the shutil module... and to tell you the truth, it stinks. > | Is there an effort to make a robust, useful shutil module that has the > | equivalent of the unix shell utilities? > > Go ahead. Then keep an eye out on comp.lang.python, and after some > years pass finally someone will mention it: "it stinks", they'll > say, with no particular explanation. To those who've tried to use shutil, no explanation is needed, IMHO. Cheers, M. -- BUGS Never use this function. This function modifies its first argument. The identity of the delimiting character is lost. This function cannot be used on constant strings. -- the glibc manpage for strtok(3) From jason at jorendorff.com Mon Mar 11 03:20:34 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 11 Mar 2002 02:20:34 -0600 Subject: [ANN] UNBABTIZED - The language In-Reply-To: Message-ID: Jonathan Gardner wrote: > I hereby nominate this for a quote-of-the-week. > > "Obviously it's a multithreaded web server." Usually this works, but in this case it's so obscure I can't really find a way to use it... keep up the suggestions, though. ## Jason Orendorff http://www.jorendorff.com/ From thoa0025 at mail.usyd.edu.au Sun Mar 31 08:54:09 2002 From: thoa0025 at mail.usyd.edu.au (Trung Hoang) Date: Sun, 31 Mar 2002 13:54:09 GMT Subject: relational database? References: Message-ID: <5yEp8.5051$hi7.18667@news-server.bigpond.net.au> where can i get this ? cheers "Martin v. Loewis" wrote in message news:m3eli1m2dt.fsf at mira.informatik.hu-berlin.de... > "Trung Hoang" writes: > > > What relational database is easy to setup and use with python? > > Gadfly. It is a pure-Python database, and requires little > administrative interaction. It does not provide good performance, > though... > > Regards, > Martin From ark at research.att.com Sat Mar 30 10:56:15 2002 From: ark at research.att.com (Andrew Koenig) Date: 30 Mar 2002 10:56:15 -0500 Subject: [Python-Dev] PEP 285: Adding a bool type In-Reply-To: <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> References: <200203300539.g2U5dAR17743@pcp742651pcs.reston01.va.comcast.net> <008f01c1d7da$5c32f3d0$0202a8c0@boostconsulting.com> <200203301347.g2UDlYZ01650@pcp742651pcs.reston01.va.comcast.net> Message-ID: >> 6) Should we eventually remove the inheritance relationship >> between Int and Bool? >> I hope so. Bool is-a Int doesn't seem like the right relationship to >> me, unless perhaps we make Int is-a Long... naah, not even then. Guido> Hm. In your favorite language bool is one of the integral types. Guido> Doesn't that imply pretty much the same thing? What it really implies is that arithmetic operations on bool values are permitted and promote to int. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From kwg at renre-europe.com Thu Mar 28 10:58:50 2002 From: kwg at renre-europe.com (Ken Guest) Date: 28 Mar 2002 15:58:50 +0000 Subject: vwait in Python? In-Reply-To: <1017315455.8141.1.camel@lewis> References: <1017315455.8141.1.camel@lewis> Message-ID: <1017331130.486.8.camel@lewis> On Thu, 2002-03-28 at 11:37, Ken Guest wrote: > Anybody know if there's an equivalent to TCL's vwait keyword in Python? So is there no way, short of a 2 line while statement, to have code hang around until the value of some variable has been changed? I have tried using variations of the simple while statement, but they only result in the application hanging (going into an infinite loop no doubt). k. -- Beware the fury of a patient man - John Dryden From cliechti at gmx.net Sat Mar 2 09:16:35 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Mar 2002 15:16:35 +0100 Subject: a simple 'else' decrease speed by 1000 times. References: <3C80BBAC.2060600@student.kun.nl> Message-ID: husam wrote in news:3C80BBAC.2060600 @student.kun.nl: > One else statement decrease speed by 1000 times. Why is that? ... > if prv == n[i][-1]: > n[i].append(new) > print count, '\t', i , '\t',n[i] > count = count +1 > break > else: > n[i].append(0) 'cause your not "break"-ing here? but you do in the "if-then" part... -- Chris From ifls at rz.tu-clausthal.de Tue Mar 19 04:50:47 2002 From: ifls at rz.tu-clausthal.de (Lutz Schroeer) Date: 19 Mar 2002 09:50:47 GMT Subject: Pure python alternative to mx.DateTime? References: <3C97007D.6000605@mxm.dk> Message-ID: Max M wrote: : Lutz Schroeer wrote: : I just looked at it, and it doesn't seem to be dependent on anything in : Zope. Seems to be the solution to my problem :) Wouldn't have found it by myself... Thanks Lutz From sandskyfly at hotmail.com Fri Mar 15 06:14:23 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 15 Mar 2002 03:14:23 -0800 Subject: jython for a large-scale web site? References: <3C90E693.3080600@stroeder.com> Message-ID: Michael Str?der wrote: > Also check out http://pywx.idyll.org/ Thanks for the reference. I've looked into pyWX before when it was still a wee promising little project, it seems to have progressed quite a bit since then, but I think it will be difficult making the case to move to a platform that is still not past the 1.0 beta stage. It's certainly a cool project nonetheless, and definitely worth a serious test. Sandy From jafo-nclug at tummy.com Thu Mar 21 02:28:07 2002 From: jafo-nclug at tummy.com (Sean Reifschneider) Date: Thu, 21 Mar 2002 00:28:07 -0700 Subject: rpm-python question In-Reply-To: <3C8CAEDF.697CEA3F@quasarlabs.com>; from ira@quasarlabs.com on Mon, Mar 11, 2002 at 03:19:27PM +0200 References: <3C8CAEDF.697CEA3F@quasarlabs.com> Message-ID: <20020321002807.E18433@tummy.com> On Mon, Mar 11, 2002 at 03:19:27PM +0200, Ira Voitashevskaya wrote: >I need to use rmp module (rpm-python-4.0.1-0.20). Where can I get >docmentation for it? Ha ha ha... Documentation on Red Hat software. That's a good one... Try getting the source code to rpmlint, which is written in Python, and figure things out from there... It's actually not that hard to figure out by poking around -- that's what I had to do. Sean -- moshez always wanted to invent a compression scheme called "feather", so he could tar and feather his files. Sean Reifschneider, Inimitably Superfluous tummy.com - Linux Consulting since 1995. Qmail, KRUD, Firewalls, Python From work at infomaniak.ch Thu Mar 21 02:45:13 2002 From: work at infomaniak.ch (BRINER Cedric) Date: Thu, 21 Mar 2002 08:45:13 +0100 Subject: eval of a private attribute Message-ID: <3C998F89.66DB1290@infomaniak.ch> hi, I'd like to create a method which will be able to get any attribute of the class. Unfortunately this example is not working: class CObsFile: __user="~briner/big/usr.rdb" __location="~genevay/system/location" def get(self,var): tobeEval ='self.__'+var print 'toBeval: '+tobeEval p=eval(tobeEval) print 'Evaluated: '+p return p p=CObsFile() p.get('user') any idea why From til1li.iili1i1li1_il at email.it Sat Mar 30 03:02:44 2002 From: til1li.iili1i1li1_il at email.it (til1li.iili1i1li1_il at email.it) Date: Sat, 30 Mar 2002 03:02:44 -0500 Subject: When will your website be finished? Message-ID: Get a beautiful, 100% Custom Web site or redesign your existing site. Only $399!* Call now and schedule a walk through with a Web design specialist. 404-806-6124 Includes up to 7 pages (you can add more), plus a Guestbook and a Bulletin Board. Java rollover buttons, Feedback forms, Pushbutton E-Commerce Activation and more. It will be constructed to your taste and specifications in only five days. We do not use templates, our sites are completely custom. *Must host with us for $15.96 a month. You get: 200 Megs, 100 E-mail accounts, Control Panel, Front Page, Graphical Statistics, more! Act now and get one FREE .com domain name! To discuss your Web site, call 404-806-6124 and schedule a call back now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From brueckd at tbye.com Fri Mar 1 14:56:34 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 1 Mar 2002 11:56:34 -0800 (PST) Subject: hotmail In-Reply-To: Message-ID: On 1 Mar 2002, Ed wrote: > im just wondering whether it is possible to access hotmail thru python > so that i have a far quicker way of checking my emails. can telnetlib > do this? If you're on Windows (and have either ActiveState Python or Mark Hammond's win32all extensions) then you can use COM to create a web browser instance and use its DOM interface to navigate. I made a small script to retrieve my address book this way - I'll try to dig it up and post it, but it's pretty easy to do from scratch too. -Dave From skip at pobox.com Thu Mar 14 08:59:42 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 14 Mar 2002 07:59:42 -0600 Subject: Performance problem with filtering In-Reply-To: <20020314045052.GA550@lilith.hqd-internal> References: <20020314040837.GA403@lilith.hqd-internal> <20020314045052.GA550@lilith.hqd-internal> Message-ID: <15504.44238.797183.340103@12-248-41-177.client.attbi.com> gh> def append(self, item): gh> self.count[item] = self.count.get(item, 0) + 1 gh> self.l.append(item) As I mentioned in my post, depending on the elements stored in the list you may have to fiddle with "item" to make it dict-worthy. Whether simply slapping str() around it is sufficient, I don't know. I sort of suspect not, though it may get you closer to something that works for all types. -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From martin at v.loewis.de Tue Mar 5 01:32:14 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Mar 2002 07:32:14 +0100 Subject: HP-UX 10.2 deprecated? References: <1015292901.342132@cswreg.cos.agilent.com> Message-ID: weeks at vitus.scs.agilent.com (Greg Weeks) writes: > Is HP-UX 10.2 deprecated for more recent versions of Python? Not specifically. HP-UX is deprecated :-) Seriously, it is only as good on any platform as Python users care about it being. None of the regular Python contributors has access to HP-UX, so any problem reported and any patch suggested is hearsay. Unfortunately, the patches often tend to break things on systems that the patch authors have no access to. Sometimes, patches must be rejected because they *obviously* break things on other systems, so the problem that the patch submitter wanted to fix remains unfixed. > PS: Here's the problem with the Python 2.2 ./configure for HP-UX 10.2. To > determine if _POSIX_THREADS is defined in unistd.h, it runs the C > preprocessor on a file with the contents: > > #include > #ifdef _POSIX_THREADS > yes > #endif > > Unfortunately, with the C preprocessor invocation used by ./configure, the > indented #ifdef is not recognized, which results in the #ifdef construct > being mindlessly echoed, which is erroneously interpreted as the answer > "yes". This causes _POSIX_THREADS to not be defined in pyconfig.h, > resulting in a bunch of undefined thread-related functions at link time. What C compiler? I doubt that aCC (which is available for 10.20 as well) has this problem; do not use the bundled C compiler for anything. Regards, Martin From tim.one at comcast.net Sat Mar 30 03:01:42 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 30 Mar 2002 03:01:42 -0500 Subject: Where is/What happened to ActivePython (PythonWin) 2.2 ?! In-Reply-To: <3CA39BC1.59873E78@activestate.com> Message-ID: [David Ascher] > I'm not going to discourage anyone from learning about installers, but > let me just warn you that it's a lot of work to make a nice installer. That doesn't matter. What does matter is that, at least for Windows installers, it's insanely boring and frustrating work, and no matter many years you work on it, it still fails on French Windows 2000 or Arabic Windows XP Professional Server Special Edition Service Pack 1 from a Power User but not an Administrator account if the Windows drive isn't C: or K: (there's something about hard consonants I haven't figured out). > Tim already spends a lot of time on installers that I for one would > rather see him spend on things that the rest of us can't do =). Like this! I can't explain it. When I was a kid I always failed at this, but about 10 years ago I tried it on a whim, and it works every time now: I can pat my head with one hand and rub my belly in circles with the other. I can change the direction of rotation without missing a beat, and also switch hands so that the rotating hand becomes the head-patting hand and vice versa. There seem to be very few people who can do this as gracefully as I, let alone look so dignified while doing it. This is also a lot of work, but it's fascinating and rewarding work. > ActivePython's new installer does 'feature selection', so you can choose > to install all, some or none of Mark's code; it also does the PATHEXT > tweaks, we have an integrated CHM file which includes a lot of extra > docs (the what's new, the HOWTOs, etc.). For the record, ActivePython's installers are nicer than mine, and people waiting for PythonLabs to take on MSI technology will most likely die waiting. The only reason to use the PythonLabs installer is if you don't want your disk filled with secret ActiveState spyware. Oops! I think I just started a baseless rumor. If you deny it, that will only increase suspicion. Still, the only real reason I know of to use the PythonLabs installer instead is if you want an installer released under the same stack of 42 friendly licenses as Python itself. > The feature of supporting 'file drops' is one we should definitely look > at adding. It's very mac-ish (that's a compliment! =). I have to get out of the DOS box sometime. Is this one of those deals where you tickle a file with that "mouse" thing, and then a dialog box from an irrelevant program pops up and steals the focus before you can finish what you started? I love stuff like that. most-features-suck-ly y'rs - tim From robin at execulink.com Wed Mar 20 14:16:15 2002 From: robin at execulink.com (robin at execulink.com) Date: Wed, 20 Mar 2002 14:16:15 -0500 Subject: Python embedded like PHP References: <359f85cd.0203191203.2a8e4bd@posting.google.com> Message-ID: I'm not at all fond of mixing up HTML and code. For real-world sites that are not trivially small, this presents a growing maintenance problem. Much better, IMO, to keep all of the python code in modules, where it belongs, and have an simple syntax for mixing the results of executing code in with a web page. That way the HTML people can do their thing, and the coders theirs. My Wasp templating system does this. Pages look like the following: =====

    A sample page using Wasp. HTML where HTML belongs; code where code belongs.

    ===== Most of the HTML is hidden away in the include files, which enhances stylistic conformity. These can be passed parameters for simple variable content. Anything more complex requires that one execute a function; any output from this is put directly inline. Additional tags handle conditional output and macros, but these two tags are really all you need. There are certainly lots of templating systems out there. Here's mine: www.execulink.com/~robin/wasp/readme.html ----- robin A rich couple found their ideal pet in a dog that makes e-mail programs. From grante at visi.com Sat Mar 16 00:41:48 2002 From: grante at visi.com (Grant Edwards) Date: Sat, 16 Mar 2002 05:41:48 GMT Subject: readline() blocks after select() says there's data?? References: <2b57f654.0203141934.391d1bcc@posting.google.com> <1016173476.645562@yasure> <2b57f654.0203151021.7f709e4c@posting.google.com> Message-ID: In article <2b57f654.0203151021.7f709e4c at posting.google.com>, wealthychef wrote: > "Donn Cave" wrote in message news:<1016173476.645562 at yasure>... >> Quoth grante at visi.com (Grant Edwards): >> ... >> | When select returns a file descriptor, that means that read() >> | won't block. If only a partial line is available, then >> | readline() will still block. I doubt that this is going to be >> | an issue, since your output is probably line-oriented. > If it is not line-oriented, must I then use select.select combined > with read(1) and go character by character? No, you can read all the available data with a single call to read. The value you pass to read is just a maximum, and read will return as much data as it can. I think this would be an excellent use for a generator. But if you've never done any co-routine stuff before it can be a bit disorienting. > That reminds me, is there a way to get the integer value of a > character in Python analogous to casting a char to an int in C? c = "A" i = ord(c) -- Grant Edwards grante Yow! Did YOU find a at DIGITAL WATCH in YOUR box visi.com of VELVEETA? From gerson.kurz at t-online.de Fri Mar 15 03:15:43 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Fri, 15 Mar 2002 09:15:43 +0100 Subject: Disabling rexec for ActiveScripting in Local Intranet Zone? References: <3C912376.7020902@skippinet.com.au> Message-ID: Mark Hammond wrote: > I have no idea :) I would expect that if > IE has set security approriately, then Python > would not operate under rexec at all - this is > certainly what happens for WScript and ASP. It doesn't. Is there a way to manually disable rexec? (Like, patching lib/rexec.py). > What version of win32all? win32all-146.exe for python2.2 From db3l at fitlinxx.com Thu Mar 28 15:33:30 2002 From: db3l at fitlinxx.com (David Bolen) Date: 28 Mar 2002 15:33:30 -0500 Subject: question on struct.calcsize References: <3ca33d3f.26101031@news.easynews.net> Message-ID: stojek at part-gmbh.de (Marcus Stojek) writes: > Hi, > could anyone explain the following, please. > (Win NT, Python 2.1.1) > > >>> from struct import * > >>> calcsize("i") > 4 > >>> calcsize("s") > 1 > >>> calcsize("si") > 8 Padding. When forming a structure, the default will be to add inter-field padding as dictated by the local compiler/implementation to improve numeric alignment. In many cases that will be a 4-byte (32-bit) boundary for numeric values. So in your second case, in order to get the integer aligned on a 4-byte boundary, it padded out the character. Note that if you flip the order, you won't need the alignment (shown below). The default padding is "native" (implementation specific) but you can ask for standard alignment which does no padding. The first character of each format string can control byte ordering/alignment. If you use "=" you'll get standard alignment while not affecting byte order (which will still be based on your native platform). Other characters (<, >, !) control byte ordering in addition to alignment. Thus: Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> from struct import * >>> calcsize("i") 4 >>> calcsize("s") 1 >>> calcsize("si") 8 >>> calcsize("is") 5 >>> calcsize("=si") 5 -- -- David -- /-----------------------------------------------------------------------\ \ David Bolen \ E-mail: db3l at fitlinxx.com / | FitLinxx, Inc. \ Phone: (203) 708-5192 | / 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \ \-----------------------------------------------------------------------/ From skip at pobox.com Fri Mar 1 08:13:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 1 Mar 2002 07:13:18 -0600 Subject: Apology to Bill Gates (was Re: ASV module, CVS modules) In-Reply-To: References: <61ff32e3.0202281525.3e9bb102@posting.google.com> Message-ID: <15487.32366.219011.387073@12-248-41-177.client.attbi.com> John> Python, starting from a Unix background, where there is evidently John> no such thing as an invalid character in a file name, ... I believe "/" is not allowed in Unix filenames. Not sure if this is escapable or not. I'm not going to take the chance of hosing my laptop's filesystem to find out. ;-) -- Skip Montanaro (skip at pobox.com - http://www.mojam.com/) From fredrik at pythonware.com Sat Mar 16 12:27:27 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 16 Mar 2002 17:27:27 GMT Subject: Tkinter BUG: memory loss for tag bindings in Canvas References: Message-ID: <3gLk8.25494$n4.5001105@newsc.telia.net> Eric Brunel wrote: > To me, this sounds like a bug, doesn't it? yes. please post a bug report to the SF bug tracker: http://python.sourceforge.net/sf-faq.html#bugs thanks /F From max at alcyone.com Sun Mar 31 22:21:47 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 31 Mar 2002 19:21:47 -0800 Subject: PEP 285: Adding a bool type References: <3CA79606.A0C1B055@python.org> Message-ID: <3CA7D24B.14E17A03@alcyone.com> Guido van Rossum wrote: > The main effect this had was to confuse the died-in-the-wool > programmers; it didn't make any difference for the newbies because > they had to learn the concepts anyway. When you come in with a > blank mind it doesn't matter if a particular concept is called > "variable" or "waffle" -- you have to learn a new meaning for an > existing word either way, and the previous meaning you knew for the > word is barely relevant in the new context. Couldn't agree more; I mentioned something substantially similar in my reply. Inventing new, non-standard terminology in order to be "simpler" is rarely helpful; it doesn't substantially help newbies, and it only serves to confuse people actually involved. As a case of this kind of thinking taken to outrageous extreme, consider the Mathematics in the Common Tongue Web site: http://www.earth360.com/mathtongue.html When the idea is taken to this kind of bizarre level, the end result almost feels like one of those antiknowledge languages you read about in science fiction, like Newspeak. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From irmen at NOSPAMREMOVETHISxs4all.nl Sun Mar 24 08:49:43 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Sun, 24 Mar 2002 14:49:43 +0100 Subject: Client/Server Tutorial? References: Message-ID: > Is there any good tutorial for creating advanced client/server apps > (like online games) out there? i tried to make one 2 times, and both May I suggest you take a look at Pyro; http://pyro.sourceforge.net It may be just what you want/need for easy distributed application development. You don't have to do any network programming when using Pyro. Irmen de Jong From tim.one at comcast.net Fri Mar 8 02:23:04 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 08 Mar 2002 02:23:04 -0500 Subject: PEP Parade In-Reply-To: <7xhenrh87a.fsf@ruckus.brouhaha.com> Message-ID: [Paul Rubin] > ... > Is there a method for adding comments to PEP's? Not unless the PEP author supplies one, and that's something I haven't seen yet. PEP 1 describes the PEP process. You need to get your comments in front of the PEP author(s). From joonas at olen.to Tue Mar 12 15:25:12 2002 From: joonas at olen.to (Joonas Paalasmaa) Date: Tue, 12 Mar 2002 22:25:12 +0200 Subject: returning a picture from PIL References: Message-ID: <3C8E6428.945333F9@olen.to> Peter Posselt Vestergaard wrote: > > Hi > I would like to show a image on a webpage by calling a python script that > through the Python Imaging Library (PIL) loads a picture and then returns > it. > I'm trying to do it like this: > In the webpage I write: > [...] > > [...] > > and in myscript.py I write: > > [...] > pic = Image.open(urllib.urlretrieve(url)[0]) > print "Content-type: image/png\n\n" > pic.save(sys.stdout,"PNG") > > the page takes some time loading the picture but nothing is ever shown. If I > change sys.stdout to "filename" the picture is stored perfectly on my disk. > Anyone who can tell me how to do this kind of output from PIL? If you're using Windows, the problem might be the "\n" -> "\r\n" conversion. To avoid the conversion, you have to invoke python in unbuffered mode with -u option or use msvcrt module. Take a look at an useful Python Cookbook recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65443 From loewis at informatik.hu-berlin.de Sun Mar 17 12:36:48 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 17 Mar 2002 18:36:48 +0100 Subject: locale module broken? References: <3C928042.BA50A5B3@snakefarm.org> Message-ID: Oleg Broytmann writes: > I reproduced this behviour on Debian 2.2 with all version of Python - > 2.0, 2.1 amd 2.2... but only with FR locale. With ru_RU locale it works > perfectly. It seems glibc has got broken FR locale. That must have been fixed in more recent versions of glibc then; on Debian-testing, it works fine. Regards, Martin From peter at engcorp.com Fri Mar 29 17:01:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 29 Mar 2002 17:01:06 -0500 Subject: Newbie: List of instances? References: <3CA4D52E.C2067419@bellsouth.net> Message-ID: <3CA4E422.B88F6720@engcorp.com> Jeff Layton wrote: > > > a.append(Bob('localhost')) > > This works! If I create a list a that has five elements where > are just instances of Bob, can I "call" a method for a specific > element of the list? I take I can (Jeff sneaks off to experiment > while his wife is napping). Not sure if you mean can you call a method to get a specific element of the list (for that you'd just use brackets: a[2] returns the third element), or whether you mean can you take a specific instance and call a method on it: a[2].getHost() for example... the answer in both cases is, of course, yes you can. :-) -Peter From amuys at shortech.com.au Mon Mar 4 21:38:18 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 4 Mar 2002 18:38:18 -0800 Subject: more functional programming References: <3C83EF44.A44E595C@gol.ge> Message-ID: <7934d084.0203041838.17b9d523@posting.google.com> Giorgi Lekishvili wrote in message news:<3C83EF44.A44E595C at gol.ge>... > Hi all! > > Please, accept my appologies for this naive question. > > I have taken a careful look on the operator module docs. The module > enables one to make procedures as lists. That's too good. > > However, is there already something like scheme's "define" abstractor? > This'd be used as the first element of such list, yielding the result of > the procedure... > > Is this, or anything similar, already present in Python? If not, does > someone of the Python gurus plan to do so? > I may be corrected, but afaik the answers no. OTOH, you can easily write a class that can wrap a list of functions and call them in sequence. In fact it's also relatively trivial to emulate a moduleish interface to a set of such functions ie. class FakeModule: def __init__(self): self.funcs = {} def define(self, flist): self.funcs[flist[0]] = flist[1:] def __getattr__(self, name): return FakeFunction(self.funcs[name]) class FakeFunction: def __init__(self, flist): self.flist = flist def __call__(self, *args): for f in self.flist: if args == None: args = () args = apply(f, args) Note that FakeFunction will do what you wanted with define. The FakeModule provides a namespace for such functions to live in. I would be inclined to pass the function name seperately from the function list, but that would be a further departure from the define semantics. eg. def define(self, fname, flist): self.funcs[fname] = flist An example of use (including arg chaining): >>> def f1(): print 'f1 called' return ('f1',) >>> def f2(arg): print 'f2 called after',arg return (arg,'f2') >>> def f3(arg1, arg2): print 'f3 called after',arg1,'and',arg2 return (arg1, arg2, 'f3') >>> mod = FakeModule() >>> flist = ['f123', f1, f2, f3] >>> mod.define(flist) >>> mod.f123() f1 called f2 called after f1 f3 called after f1 and f2 Andrae ps. It would be nice if apply() interpreted args=None as args=(), but it's only a minor annoyance, and the if statement covers it. From bokr at oz.net Sun Mar 10 22:36:14 2002 From: bokr at oz.net (Bengt Richter) Date: 11 Mar 2002 03:36:14 GMT Subject: should i learn it first ? References: Message-ID: On 10 Mar 2002 18:30:49 -0800, aahz at panix.com (Aahz Maruch) wrote: >In article , >Patrick wrote: >>"Aahz Maruch" wrote in message >>news:a6g7ra$lm6$1 at panix2.panix.com... >>> >>> But are there any tasks for which C++ (or C++/Python) is really better >>> than C/Python? >> >>One example is an extremely complex and long-running simulation in which the >>time-critical components are a very substantial chunk of the project. In >>those (rare) situations you need ruthless efficiency with slightly better >>than rudimentary abstraction capabilities. C++ fits the bill, but only if >>every processor cycle and every byte counts. > >Right, and if you've got a project like that, you'd better have someone >like Alex Martelli handy, because otherwise your C++ program will bloat >with every advanced C++ feature you use. I'd bet that 90% of so-called >C++ programmers would do far better in this case with C/Python. > I think a lot of bloat comes because C++ facilitates building libraries of complex objects, and people will do the equivalent of buying that big red rolling multidrawer metric/English super mechanic's dream tool chest, when all they needed was a socket wrench. The cost of #include is not proportionately perceptible. Yet sometimes the choice is buy the set or make the wrench yourself. It would be interesting to how many object methods in a large application could harmlessly be replaced with YAGNI assertions, even with smart linkers. After all, they can't be smart enough to know whether a path that has a reference will ever be entered, if it's data dependent, whereas the programmer might know very well and yet be helpless to prevent the linkage of a big useless chunk of library. It all depends ;-) Regards, Bengt Richter From gregory.p.green at boeing.com Fri Mar 1 15:14:53 2002 From: gregory.p.green at boeing.com (Greg Green) Date: Fri, 1 Mar 2002 20:14:53 GMT Subject: Want to monitor process.. References: <87550ef1.0202272315.15779bbd@posting.google.com> <97ae44ee.0202280901.3153bdfc@posting.google.com> Message-ID: If you are using a unix OS, I would suggest using daemontools from Bernstein. It has a set of tools for supervising a process. I use it all of the time for these sorts of problems. http://cr.yp.to/daemontools.html -- Greg Green Advanced Design Systems Math & Computing Technology Boeing From logstx at bellatlantic.net Wed Mar 6 17:10:53 2002 From: logstx at bellatlantic.net (logistix) Date: Wed, 06 Mar 2002 22:10:53 GMT Subject: Nested scopes: design or implementation? References: <3czdq05v.fsf@vfa.com> Message-ID: Okay, now I'm confused. I was perfectly happy with Teddy Reedy's explaination that def is an expression and not a declaration. But if I'm following you, the embedded attribute function isn't being recompiled to bytecode each time function() is called. If the code object is only getting created once, then why are the defaults getting recalculated? -- - wrote in message news:3czdq05v.fsf at vfa.com... > Note that the object is shared by each of the inner > objects: > > text = "random text" > def function(): > def attribute( bindNow = text): > print bindNow > function.attribute = attribute > > Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > > >>> function() > >>> function.attribute() > random text > >>> function.attribute > > >>> function.attribute.func_code > > > >>> function() > >>> function.attribute.func_code > > > >>> text = 'new random text' > >>> function() > >>> function.attribute > > >>> function.attribute.func_code > > > Mark Millikan From aahz at pythoncraft.com Thu Mar 21 16:20:30 2002 From: aahz at pythoncraft.com (Aahz) Date: 21 Mar 2002 16:20:30 -0500 Subject: mutlifile inheritance problem References: <9896e047.0203211303.741f695a@posting.google.com> Message-ID: In article <9896e047.0203211303.741f695a at posting.google.com>, Marc wrote: > >************************ >file cbase01.py: > >class CBase: > def __init__(self): > self.cclass = None > print "cbase" > >class CImStream(CBase): > def __init(self): > CBase.__init__(self) > print "CImStream" > >************************* >in file wrappers_A01.py: > >import cbase01 >reload(cbase01) > >class ImStream_SavedBitmaps(cbase01.CImStream): > def __init__(self): > cbase.CImStream.__init__(self) > print "SavedBitmaps" Try: def __init__(self): cbase01.CImStream.__init__(self) Why are you using reload(), anyway? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." --Knuth From aahz at pythoncraft.com Sat Mar 30 22:51:49 2002 From: aahz at pythoncraft.com (Aahz) Date: 30 Mar 2002 22:51:49 -0500 Subject: Most important extensions? Message-ID: I'm teaching Python for [Perl] Programmers at OSCON this July. I've already decided to mention mxODBC, NumPy, and PIL, plus PythonPoint (aka ReportLab) gets a mention on my title page. I'd like this group to vote on the most important extensions for me to add to this list. Please vote for no more than three. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From kendall at monkeyfist.com Mon Mar 11 16:34:07 2002 From: kendall at monkeyfist.com (Kendall Clark) Date: Mon, 11 Mar 2002 15:34:07 -0600 Subject: python and haskell for fun In-Reply-To: References: Message-ID: <15501.8911.362214.989320@cmpu.net> >>>>> "sandy" == Sandy Norton writes: sandy> "Patrick" wrote: >> This subset of PASKELL will be clean, beautiful and functional. sandy> I'm sorry I wasn't clear. I meant 'beget a pretty monster' of sandy> an application, not a language. The last thing I would want sandy> to do is waste time discussing a new hybrid 'PASKELL' sandy> language... I've been daydreaming for about a year of a Python implementation written in Haskell, which would obviously make writing Python extensions in Haskell easier (and more elegant, IMO, than writing them in C or Java). However, John Paul Skaller did something similar with Ocaml, which he called Vyper, and that went over in the Py world like a leaden balloon -- actually it went over about as poorly as Stackless Python did; which does cause me to wonder what it is about Python culture, if anything, that's resistant to unusual alternative implementations?. A Python implementation in Haskell is probably a fool's task. Though given the various Haskell compilers, including some pretty impressive parallelizing stuff, it is an interesting idea. (Ocaml is pretty much Caml + objects; Caml is INRIA's implementation of ML; in the neighborhood of Haskell, but less syntactially elegant, IMO.) At least, a Haskell implementation of Python seems more practical than a Python implementation of Haskell, which would be rather toylike. But YMMV. Best, Kendall Clark From kalle at gnupung.net Wed Mar 20 11:33:30 2002 From: kalle at gnupung.net (Kalle Svensson) Date: Wed, 20 Mar 2002 17:33:30 +0100 Subject: Popular style document? In-Reply-To: <1016641355.370859@cswreg.cos.agilent.com> References: <1016641355.370859@cswreg.cos.agilent.com> Message-ID: <20020320163330.GA1224@sandra.lysator.liu.se> [Greg Weeks] > Is there a popular style document for Python? I realize that there isn't a > whole lot of scope for such a thing, but I wondered because of certain > particular issues that came to mind. There is PEP 8, http://python.sourceforge.net/peps/pep-0008.html. Peace, Kalle -- Kalle Svensson (kalle at gnupung.net) - Laziness, impatience, hubris: Pick two! English: http://www.gnupung.net/ Svenska: http://www.lysator.liu.se/~kalle/ Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()] From kdahlhaus at yahoo.com Tue Mar 26 10:02:32 2002 From: kdahlhaus at yahoo.com (Kevin Dahlhausen) Date: 26 Mar 2002 07:02:32 -0800 Subject: Python embedded like PHP References: <20020322003738.A273C38F4C@coffee.object-craft.com.au> Message-ID: <283adf56.0203260702.160260fd@posting.google.com> Haven't seen anyone mention Cheetah over at http://www.cheetahtemplate.org/ : $title #for $client in $clients #end for
    $client.surname, $client.firstname $client.email
    Graphical designers can graphically design w/some idea of what it will look like. WYSIWYG editors will not vomit or ignore. It requires minimal overhead re. typing extra characters - follows the One True Python Way. And it supports neato oo constructs such as template inheritance. >From the sample page: What is the philosophy behind Cheetah? Cheetah's design was guided by these principles: Python for the back end, Cheetah for the front end. Cheetah was designed to complement Python, not replace it. Cheetah's core syntax should be easy for non-programmers to learn. Cheetah should make code reuse easy by providing an object-oriented interface to templates that is accessible from Python code or other Cheetah templates. Python objects, functions, and other data structures should be fully accessible in Cheetah. Cheetah should provide flow control and error handling. Logic that belongs in the front end shouldn't be relegated to the back end simply because it's complex. It should be easy to separate content, graphic design, and program code, but also easy to integrate them. A clean separation makes it easier for a team of content writers, HTML/graphic designers, and programmers to work together without stepping on each other's toes and polluting each other's work. The HTML framework and the content it contains are two separate things, and analytical calculations (program code) is a third thing. Each team member should be able to concentrate on their specialty and to implement their changes without having to go through one of the others (i.e., the dreaded ``webmaster bottleneck''). While it should be easy to develop content, graphics and program code separately, it should be easy to integrate them together into a website. In particular, it should be easy: for programmers to create reusable components and functions that are accessible and understandable to designers. for designers to mark out placeholders for content and dynamic components in their templates. for designers to soft-code aspects of their design that are either repeated in several places or are subject to change. for designers to reuse and extend existing templates and thus minimize duplication of effort and code. and, of course, for content writers to use the templates that designers have created. From eppstein at ics.uci.edu Sun Mar 17 16:28:34 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 17 Mar 2002 13:28:34 -0800 Subject: syntax question: "<>" and "!=" operators References: <3dd808a4.0203151013.a37d0c4@posting.google.com> Message-ID: In article , mertz at gnosis.cx (David Mertz, Ph.D.) wrote: > Nonetheless, I think of the natural language semantics of the > symbols--or maybe better "insinuations"--prefers '<>' to '!='. The > (good) one suggests "is greater than or less than (but not equal to)". > I know that not everything is technically in an order relation, but it > still "makes sense" at a first approximation. The (bad) one looks like > some odd sort of augmented assignment. "Hmmm... assign, what? The > negation of the right side to the left side?! The LHS negated with the > RHS?!" I disagree -- the "<>" makes sense only if you think about it for real numbers, while "!=" matches the way I pronounce the symbol ("not equals"), looks visually similar to the way I'd draw the symbol if I had a better character set (equal sign with slash through it), and makes sense for all types of objects. But then, while I've switched from Pascal to C and vice versa several times, it's been several years since I last worked with Pascal while I still use several C-like languages, so maybe I'm biased from that. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From altis at semi-retired.com Thu Mar 7 22:52:43 2002 From: altis at semi-retired.com (Kevin Altis) Date: Thu, 7 Mar 2002 19:52:43 -0800 Subject: ANN: Python User Groups page at python.org Message-ID: <2AWh8.478$eT3.149538@news.uswest.net> Python User Groups now have their own page on the Python web site: http://www.python.org/UserGroups.html If your group isn't listed or if your information is out of date, please email webmaster at python.org. If your group has a special event you'd like to see listed on the Events page, please email events at python.org. User groups are a great way to meet other Python users in your local area. Why not start one today? Note, the PUG info used to be a section on the Events page: http://www.python.org/Events.html ka From chris_mk at hotmail.com Thu Mar 28 01:59:45 2002 From: chris_mk at hotmail.com (Christopher) Date: 27 Mar 2002 22:59:45 -0800 Subject: Image in a module question Message-ID: A while back, I remember somebody mentioning a way to store image data in a Python module. This is something I think I could really use (I want to incorporate an image into an frozen exe that I am writing for my coworkers). I would like to keep the installation nice and neat (--onefile) and I figure the easiest way is to store the image in a module, import it, then use the string (I am assuming this is what you would get from the module, I can't remember what the post sais) e.g., import MyImageModule import Image, ImageTk, StringIO myImage = MyImageModule.MyImage # Where MyImage is the string representing the image im = Image.open(StringIO.StringIO(myImage)) # I can now use im to construct my Tkinter label/button/etc. I did some searches: PIL, image in module, importing images, etc. and didn't see the post (it was a lot of pages, i may have just missed it). If somebody remembers the post, could you point me to it (just the date would be a huge help). Thanks a bunch, Chris Karim From peter at engcorp.com Mon Mar 25 20:02:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 25 Mar 2002 20:02:37 -0500 Subject: list comprehension question References: <20020325113323.A26319@glacier.arctrix.com> Message-ID: <3C9FC8AD.CD82FEA0@engcorp.com> Neil Schemenauer wrote: > > Tim Peters wrote: > > there's generally no reason to suppose that len(iterable) wouldn't be > > destructive > > Good point. > > Neil > > PS. tell the bot I'm sorry I doubted the correctness of his code If it's a bot, you don't have to apologize. Bots feel no emotion. And you're safe, too -- remember the First Law. -objectifying-tim-ly yr's, Peter From barghest at wanadoo.fr Wed Mar 27 04:33:28 2002 From: barghest at wanadoo.fr (Barghest) Date: Wed, 27 Mar 2002 10:33:28 +0100 Subject: Regex problem ... Message-ID: Hello, import re tagImg = re.compile( r"""(]*>)""", re.IGNORECASE | re.MULTILINE | re.DOTALL ) Wanna match ... and replace it by the problem is that i don't know how to lowercase the \g<2> part bp2.write( tagImg.sub( '\g<1>\g<2>\g<3>', buff ) ) I tried tagImg.sub( string.lower( '\g<1>\g<2>\g<3>' ), buff ) but it doesen't work .. Any idea ? From grante at visi.com Mon Mar 11 18:44:28 2002 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Mar 2002 23:44:28 GMT Subject: wxProgressDialog wonky under Win32 References: Message-ID: In article , Cliff Wells wrote: > On Mon, 11 Mar 2002 19:15:34 GMT > Grant Edwards wrote: >> >> According to one of the wx mailing list archives, this is a >> known bug in the MSW port of wxWindows (the "size" value of a >> gauge is treated as a 16-bit number). It's been fixed, but >> it's still available only from CVS. > > The usual trick I use to get around this is to use a gauge with > a max of 100 and then update it with the percentage done > (n/max) rather than the number of items done (n). This can > also help performance as you can avoid updating the gauge as > often if you have a large number of items to process. Yup. It's a bit incovenient in my case because function calling the update callback didn't know how much data was to be processed. I had to create an extra function that did know the total size, and pass that to the data-processing function. It also caused problems because the integer math didn't really work right and the thing finished when it got to "100" even though it was really only 99.99. -- Grant Edwards grante Yow! I was in a HOT at TUB! I was NORMAL! I was visi.com ITALIAN!! I enjoyed th' EARTHQUAKE! From op73418 at mail.telepac.pt Sat Mar 2 21:08:18 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Sun, 03 Mar 2002 02:08:18 +0000 Subject: PEP 276 -- What else could iter(5) mean? References: Message-ID: On Sat, 02 Mar 2002 17:47:00 -0800, David Eppstein wrote: >Here's another way of looking at the same question. >An iterable object has a next() function, that's what it means to be >iterable. If numbers are iterable, we can call number.next(), right? >So what should 5.next() be? Surely anyone familiar with the Peano axioms >would say 6, not 0! As far as i understand 3.next() should give an error. 3 is iterable, that is, it delivers an iterator in the appropriate context, it is NOT the iterator itself. To get 0 you would have to do iter(3).next() P.S: I am a newbie. I like this PEP proposal. From James_Althoff at i2.com Mon Mar 4 18:52:45 2002 From: James_Althoff at i2.com (James_Althoff at i2.com) Date: Mon, 4 Mar 2002 15:52:45 -0800 Subject: Status of PEP's? Message-ID: [James_Althoff] > > > "for something" loops over all values of the variable that make > > "something" true. > > But that kind of definition isn't comprehensive enough because, for > example, it says nothing about the order of the variables as processed by > the for-loop. [Greg Ewing] > Obviously it doesn't serve as a complete *definition* of > the semantics, but the complete definition is at least > consistent with that view, for both "for i in x" and > "for x < i < y". Yes, I'll grant "is at least consistent". But, in the case of the for-loop, at some point -- rather quickly I suspect -- you are going to have to leave the realm of relational operators and get right back to talking about iterators. Because you're going to have to explain why for x <= i <= y: works and why for x <= i and i != y: is a syntax error. And why for i < rowcount: uses "i" as the loop variable instead of "rowcount" -- or does it? for rowcount < i: How would Python decide? And if it can't, then does this mean that the idiom cannot support shortcuts for the common case of iterating the indices of a list? So, do we have to write: for 0 <= i < rowcount: specifying the "0 <=" part every time? Jim From p.magwene at snet.net Fri Mar 15 23:22:58 2002 From: p.magwene at snet.net (Paul Magwene) Date: Sat, 16 Mar 2002 04:22:58 GMT Subject: Graph Algorithms - Checkout SciLab References: Message-ID: On Fri, 15 Mar 2002 19:52:32 -0500, Paul Magwene wrote: > Hi Y'All, > > Here's a long shot - > > Does anybody happen to have a Python implementation of a minimum-weight > perfect matching algorithm? Or a Python interface to one? OK, to answer my own question. The free (source included) scientific computing environment SciLab (see http://www-rocq.inria.fr/scilab/ ) has a quite nice graph algorithms toolkit called MetaNet which does what I need. I think I should be able to pipe commands to SciLab. In fact, it looks like SciLab has quite nice interfacing capabilities. Hmm, I wonder how hard it would be to write a Python-SciLab interface? With that and the recently released R interface I might never have to write an algorithm again! Ciao, Paul From jason at jorendorff.com Mon Mar 11 03:07:44 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Mon, 11 Mar 2002 02:07:44 -0600 Subject: Python Equivalent of Perl's Safe module? In-Reply-To: <20020311080649.GA25930@Ax9.org> Message-ID: John Beppu wrote: > Hello, I was wondering if there was a Python equivalent of Perl's Safe > module. http://www.python.org/doc/current/lib/module-rexec.html ## Jason Orendorff http://www.jorendorff.com/ From mwh at python.net Sun Mar 3 12:01:44 2002 From: mwh at python.net (Michael Hudson) Date: Sun, 3 Mar 2002 17:01:44 GMT Subject: [Numpy-discussion] RE: Python 2.2 seriously crippled for numerical computation? References: Message-ID: Konrad Hinsen writes: > Tim Peters writes: > > > > # Python 2.2 > > > > > > >>> 1e-200**2 > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > OverflowError: (34, 'Numerical result out of range') > > > > That one is surprising and definitely not intended: it suggests your > > platform libm is setting errno to ERANGE for pow(1e-200, 2.0), or that your > > platform C headers define INFINITY but incorrectly, or that your platform C > > headers define HUGE_VAL but incorrectly, or that your platform C compiler > > generates bad code, or optimizes incorrectly, for negating and/or comparing > > I just tested and found the same behaviour, on RedHat Linux 7.1 > running on a Pentium machine. Python 2.1, compiled and running on the > same machine, returns 0. So does the Python 1.5.2 that comes with the > RedHat installation. Although there might certainly be something wrong > with the C compiler and/or header files, something has likely changed > in Python as well in going to 2.2, the only other explanation I see > would be a compiler optimization bug that didn't have an effect with > earlier Python releases. A random memory byte suggests that whether Python links with -lieee or not affects this behaviour. Cheers, M. -- 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 martin at v.loewis.de Sun Mar 10 14:30:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 10 Mar 2002 20:30:01 +0100 Subject: HTML -> XML: Where's HtmlBuilder()? References: Message-ID: "F. GEIGER" writes: > Is HtmlBuilder() deprecated? It is not supported in PyXML 0.6 and later anymore, since the entire DOM implementation has been replaced with 4DOM. > Which module was it replaced with? Try xml.dom.ext.reader.HtmlLib. > What else could I use to convert HTML to XML? Depends on what you want the conversion to do. If you want to convert HTML to XHTML, I think HTMLTidy can do that for you. > Do I need additional modules for this? > Or am I already prepared w/o knowing it? If you want to use 4DOM, yes, you should have everything you need. > For those who are curious - the big picture: [...] > A Shaper applies an XSL file to the HTML pages to make them all look equally > formatted (this is where I am stuck now). If you have control over the source HTML files, why don't you just require that they are XHTML? That would simplify processing significantly. Regards, Martin From jason at jorendorff.com Fri Mar 8 03:35:34 2002 From: jason at jorendorff.com (Jason Orendorff) Date: Fri, 8 Mar 2002 02:35:34 -0600 Subject: how to give an object as argument for a method In-Reply-To: <002d01c1c5e0$2b225120$0101010a@local> Message-ID: Greg Ewing wrote: > Isn't it Java that uses an implicit "this" variable, or > is that Javascript? Java, JavaScript, C++, Ruby, Smalltalk, Objective C... ## Jason Orendorff http://www.jorendorff.com/ From dale at riverhall.NOTHANKS.co.uk Sat Mar 30 08:28:39 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Sat, 30 Mar 2002 13:28:39 +0000 Subject: Slice objects. How to apply them to strings? References: <04g9au4kn4dtg92584l12n0ut001c7rb9m@4ax.com> Message-ID: bokr at oz.net (Bengt Richter) wrote: > >Why not subclass str? Here is a toy: This will need to run on machines with Python 2.1 but it may be that I can't get it right with 2.1. I haven't investigated yet but I'm hoping this will be much easier with 2.2. -- Dale Strickland-Clark Riverhall Systems Ltd From tim.one at comcast.net Thu Mar 7 00:09:57 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 07 Mar 2002 00:09:57 -0500 Subject: hash(unicode(string)) == hash(string) sometimes (was Re: Why KeyError ???) In-Reply-To: Message-ID: [John Machin] > ... > BTW, I'm not so sure of the utility of hash(1) == hash(1.0) Which also equals hash(1L) and hash(1+0j). In Guido's mind , these are all "numbers", and equal numbers should have equal hashes. > --- why on earth would anyone want to use floats as keys in a dictionary, > anyway? For example, I've often seen rounded Unix timestamps used as dict keys, to map "representative time" to a list of events seen at that time. A generalization uses float-keyed dicts to build histograms, after reducing the domain to bins at the desired granularity. > Eveything one reads on floating-point fulminates against equality > testing. Seems like extra code and extra run-time for little benefit. The extra code is confined to the internal routine _Py_HashDouble(), and most of that routine is scratching its head over how to get *any* reliable hash code for a C double (C doesn't the expose the bits, and fp formats can and do vary across platforms). The code to ensure that it matches the hash code for a "compares equal" int or long is about a dozen lines. If you're indeed correct that floatish numbers have no use as dict keys, this routine is never executed, so a claim of "extra runtime" would swallow itself in embarrassment . From shalehperry at attbi.com Wed Mar 27 15:58:04 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 27 Mar 2002 12:58:04 -0800 (PST) Subject: new to python... In-Reply-To: Message-ID: On 27-Mar-2002 wilby31 wrote: > Im running Linux and I would like to run a filename.py file..how do I > go about running this program? through the command line ? I have > version 1.5.2 and I do not have the control to upgrade it. thanks > make sure the first line of the file looks like: #!/usr/bin/python (the path may be different) then you do 'chmod +x filename.py'. Now you can run it by typing './filename.py' or '/path/to/filename.py'. From jcosby at mindspring.com Sat Mar 30 08:34:52 2002 From: jcosby at mindspring.com (Jon Cosby) Date: Sat, 30 Mar 2002 05:34:52 -0800 Subject: List problem References: Message-ID: "Terry Reedy" wrote in message news:xU6p8.28161$VJ1.2411615 at bin3.nnrp.aus1.giganews.com... > > "Jon Cosby" wrote in message > news:a82mlc$ja1$1 at slb6.atl.mindspring.net... > > Can anyone se why this is coming up empty in the "cols" list? I've > tried > > something similar in the interpreter, and everything here looks > right. > > What happens if you paste exactly this text into the interpreter (on > PC, turn off fast pasting)? (Answer: syntax errors, see below.) > > ###################################################################### > ## > > # WordSquare > > # Build word squares from initial word > > > # Word dictionary > > dict = "c:\data\dict.txt" > > As I said elsewhere, use forward slashes / to be safe, concise, and > more portable. > > > firstword = input("Enter first word (enclosed in quotes): ") > > firstword = raw_input("Enter first word (do not enclose in quotes): ") > is safer and easier for user. > > > lword = len(firstword) > > words = [] > > cols = [] > > rows = [] > > > > f = open(dict, "r") > > for line in f.readlines(): > > if len(line[:-1]) == lword: > > words.append(line[:-1]) > # add 'word = line[:-1]' before if and sub in nect too two lines > slightly faster > > > f.close() > Need blank line to run interactively > > If words were sorted by len, you could read in only those of proper > length > > > for i in range(lword): > > cols.append([]) > > rows.append([]) > > > rows[0].append(firstword) > > > > # Generate an array of words with matching first letters > > for i in range(lword): > > for word in words: > > if word[0] == firstword[i]: # Matches not found > > cols[i].append(word) > > As written, without indent of 'cols...' after 'if', this has a syntax > error. > This suggests that this is not exactly the file that produced the > output below. > > If words of given length were sorted, you could grab just those > needed. > > > print len(words) > > print cols > > > > > ###################################################################### > > > > C:\Python21>python projects\wordsquare.py > > Enter first word (enclosed in quotes): "hello" > > 4220 > > [[], [], [], [], []] > > Try print words[0:10] to see what actually iterating through. > > # I pasted following into interpreter and got output marked by # > > firstword = "cow" # cow, ore, wee/wet make square > lword = len(firstword) > words = ['act', 'art', 'boo', 'cat', 'cad', 'coo', 'cow', 'oft', > 'opt', > 'ore', 'wee', 'wet'] > cols = [] > rows = [] > > # delete readin from file stuff > > for i in range(lword): > cols.append([]) > rows.append([]) > > rows[0].append(firstword) > > # Generate an array of words with matching first letters > for i in range(lword): > for word in words: > if word[0] == firstword[i]: # Matches not found > cols[i].append(word) > > print len(words) > #12 > print cols > #[['cat', 'cad', 'coo', 'cow'], ['oft', 'opt', 'ore'], ['wee', 'wet']] > > so this much of program works. > It matches these words. Appending the dictionary to these, it finds them again, but only these words. Jon From tejarex at yahoo.com Wed Mar 13 17:39:02 2002 From: tejarex at yahoo.com (Terry Reedy) Date: Wed, 13 Mar 2002 22:39:02 GMT Subject: [].keys() and [].items() (Was: Why I think range is a wart) References: Message-ID: wrote in message news:mailman.1016053344.6398.python-list at python.org... > > [ruud de rooij[ > | perhaps lists should support .keys() and .items() for those operations > | (analogous to dictionaries). > > [Clark C . Evans] > | Very nice idea. This is PEP worthy. It is nice beacuse it > | does not introduce anything new; a list can easily be viewed > | as a mapping having a positive integer domain. This is simple, > | consistent, and quite elegant. > > I would like to see: > .keys() > .items() > .iterkeys() > .iteritems() I like this idea too. Best suggestion so far for replacing range(len(skjf))./ Terry J. Reedy From python at rcn.com Sun Mar 31 19:48:22 2002 From: python at rcn.com (Raymond Hettinger) Date: Sun, 31 Mar 2002 19:48:22 -0500 Subject: PEP 285: Adding a bool type References: Message-ID: "Guido van Rossum" wrote in message news:mailman.1017466974.6751.python-list at python.org... > I offer the following PEP for review by the community. If it receives > a favorable response, it will be implemented in Python 2.3. Bono's six hats: Python author hat: Votes -1 because all the books which have a section, a quick intro to python, will have to add another couple of paragraphs introducing the new type and differentiating it from ints. The extra paragraphs clutter the concept space. Python helper/tutor hat: Votes -1 because it will need a FAQ entry to explain the rationale and provide examples of how to interchange it with int types. More than one question will come across the help desk. Python YAGNI hat: Votes -1 because scans of previously my written code do not show any need for the bool. Python vs other languages hat: Votes -1 because this concept would make more sense in strongly typed languages. In contrast, Python offers easy substitutability (dictionaries where shelves were used; stringio where files were used, etc.) -- the many faces of truth and falsehood that now exist should be kept. Python accountant: Where is the income stream? What can be done after the capital expenditure that couldn't be done before? Python gambler: Sure, why not, how many backward incompatibilities and unexpected consequences could there be? With the potential payoff so high, you have to go for it! Raymond Hettinger, CPA ? Would implicit 'return Nones' at the end of function definitions be interpreted as False ? Would the 'and' and 'or' operators now require boolean arguments From sdm7g at Virginia.EDU Fri Mar 29 19:54:36 2002 From: sdm7g at Virginia.EDU (Steven Majewski) Date: Fri, 29 Mar 2002 19:54:36 -0500 (EST) Subject: Another stab at a "switch/case" construct (for Python 3000): In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E20192158DC1@admin56.narex.com> Message-ID: On Fri, 29 Mar 2002, Bjorn Pettersen wrote: > > From: Steve Lamb [mailto:grey at despair.dmiyu.org] > > > > its_called_a_directory_pointing_to_functions = {'case':closed} > > > > I do not believe that any language which can have a hash > > of function pointers has any business with a case statement. > > But that only works when all the functions in all the branches take the > same number and types of arguments -- hardly the general case. > table = {} table[key] = func, (args,...) ... def doit( k ): return table[k][0]( *table[k][1] ) You could also use entries that are lists of (func,args) pairs, and there are ways of constructing nested tables. -- Steve Majewski From marklists at mceahern.com Fri Mar 29 09:55:13 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 29 Mar 2002 08:55:13 -0600 Subject: number of lines in a file In-Reply-To: Message-ID: f = open(filename) lines = f.readlines() f.close() print "%s has %d lines." % (filename, len(lines)) // mark -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Joseph Youssef Sent: Thursday, March 28, 2002 9:26 PM To: python-list at python.org Subject: number of lines in a file hello, I am nwe to Python and I'm trying to write this script but I need it to check how many lines is in the file and I don't know how so I'm hoping someone could tell me. -- Too often we lose sight of life's simple pleasures. Remember when someone annoys you it takes 42 muscles in your face to frown, BUT, it only takes 4 muscles to extend your arm and bitch-slap that mother@#?!&! upside the head! From dgrisby at uk.research.att.com Mon Mar 18 05:03:34 2002 From: dgrisby at uk.research.att.com (Duncan Grisby) Date: 18 Mar 2002 10:03:34 GMT Subject: Python + Omni CORBA libraries link References: <3C95AF61.5D25C8CD@lfpt.rwth-aachen.de> Message-ID: In article <3C95AF61.5D25C8CD at lfpt.rwth-aachen.de>, Viatcheslav Kulikov RWTH Aachen wrote: >ImportError: DLL load failed: Das angegebene Modul wurde nicht gefunden. Can you translate that error please? >I am using Python 2.1. and OmniORB compiler 1.0. The _omnipy module is >available there with a .pyd extension (a compiled library). This message >is received when the library is present at the PythonPath; when it is >not, the interpreter simply finds no module name _omnipy. >Please advise what can be done. I am new to the Python programming, so >please give as much detail as possible. You should be using omniORBpy version 1.4. Are you using the version compiled for Python 2.1? If not, that would explain the problem. Cheers, Duncan. -- -- Duncan Grisby \ Research Engineer -- -- AT&T Laboratories Cambridge -- -- http://www.uk.research.att.com/~dpg1 -- From mail at andreas-penzel.de Wed Mar 13 06:17:23 2002 From: mail at andreas-penzel.de (Andreas Penzel) Date: Wed, 13 Mar 2002 12:17:23 +0100 Subject: 16-Bit MS-DOS and Python Message-ID: Hello NG! Is it possible to run Python-Programs with Microsoft DOS 6.2, 16-Bit? Thanks, Andreas From hat at se-46.wpa.wtb.tue.nl Tue Mar 12 10:41:32 2002 From: hat at se-46.wpa.wtb.tue.nl (Albert Hofkamp) Date: 12 Mar 2002 15:41:32 GMT Subject: Question about scientific calculations in Python References: Message-ID: On Wed, 13 Mar 2002 01:22:18 +1300, Martin Kaufmann wrote: >I'm trying to write a program to calculate diffraction patterns for >electron diffraction on clusters (100-10'000 atoms). So far I used >Python only for CGI programming and system tools (on a rather low >level...). Therefore I don't know whether it's reasonable to program >such a project in Python (I really like the language). Presently my >man concern is speed as the main function of the program is a nested In general, there are at least 2 steps in a problem: - Figure out what to do (what should I do in what order to obtain correct results, how should I organize my software). - Figure out how to do it fast enough. Python is extremely well suited for the first step. It is high level, so experimenting can be done fast, without digging for low-level coding errors (for example, the amount of code needed to implement a dictionary correctly is quite astonishing with ample opportunity to make hard-to-find errors). Being high-level also gives you the benefit that you can concentrate on finding a good algorithm. Use as much libraries of Python as possible, as they tend to be optimized for their task (and it saves you from having to code it). If you program well, and not use too many dynamic features of Python, you can consider the code as a kind of prototype for an implementation in e.g. C. Also, selecting a good algorithm has in general more impact on execution speed than optimizing a bad algorithm. 'Fast enough' in the second step heavily depends on your expectations and/or requirements. I always try it first, and if I think it should be calculated faster, then I think about speed. First of all, if you can break the computation in independant pieces, do so, and use more than 1 computer. If that is not enough, see whether you can use faster or different libraries. If that is not enough, then re-code the program in C/C++ (which should be not too difficult, since you already have explored the best way to implement the program using Python (i.e. you don't need to do step 1 again). >Now my questions: Would it be best to > >(a) write the whole program in C/C++ (I know only the basics of C but >it would be a good "excuse" to learn it...)? As a rule of the thumb I use that I need to save at least as much time running the program, as I am spending on writing it. Thus if by re-implementing, I save 1 hour execution time, and I run it 10 times, then I must be able to rewrite the code in 10 hours, otherwise I am wasting time. (if you want to learn a language, this rule doesn't always hold of course). Albert -- Constructing a computer program is like writing a painting From jim at jim.jim Fri Mar 22 20:34:42 2002 From: jim at jim.jim (jimh) Date: Fri, 22 Mar 2002 17:34:42 -0800 Subject: circular imports (don't yell!) Message-ID: We have a scenario where we have (and need) circular imports, that is, A imports B imports C imports A. Now I know there are ways around this, but we have external dependencies that make it very difficult to use an alternative, so don't be yelling at me about the design ;) I have whittled the problem down to 3 files: a.py ------ from b import * from c import * consta = 3 if __name__ == "__main__": print consta print constb print constc b.py ------ print "in b" from c import * constb = 4 constb2 = constc + 10 c.py ------ print "in c" from a import * constc = 5 As these are given here, it works. But if I switch the order of the two imports in a.py, it doesn't work: Traceback (most recent call last): File "a.py", line 2, in ? from c import * File "c.py", line 2, in ? from a import * File "a.py", line 3, in ? from b import * File "b.py", line 5, in ? constb2 = constc + 10 NameError: name 'constc' is not defined I think this is what is happening: - a imports c so c is marked as "loaded" - c imports a - a imports b - b imports c, but c is already marked as "loaded", however, it hasn't REALLY been loaded, thus constc is not yet defined. Any ideas? Jim Thanks. From loewis at informatik.hu-berlin.de Thu Mar 7 09:39:45 2002 From: loewis at informatik.hu-berlin.de (Martin von Loewis) Date: 07 Mar 2002 15:39:45 +0100 Subject: HP-UX 10.2 deprecated? References: <1015292901.342132@cswreg.cos.agilent.com> <1015438469.628881@cswreg.cos.agilent.com> Message-ID: weeks at vitus.scs.agilent.com (Greg Weeks) writes: > With this, "make" does indeed create an executable. But "make test" fails > both times on test_threads, dying at the end with: > > test_thread > *** Termination signal 14 > > Stop. > > Oddly enough, signal 14 (ALRM) is ignored the first time "test_thead" is > listed. It appears that HP uses such signals for inter-thread communication and synchronization; such usage interferes with the application's usage of the signals. Regards, Martin From martinkaufmann at yahoo.com Wed Mar 13 07:06:46 2002 From: martinkaufmann at yahoo.com (Martin Kaufmann) Date: Thu, 14 Mar 2002 01:06:46 +1300 Subject: Question about scientific calculations in Python References: Message-ID: On Tue, 12 Mar 2002 23:04:19 -0600, "Jason Orendorff" wrote: Thanks a lot! This is really an amazingly helpful reply. This group is a good example for how Usenet should ideally be! >I'm going to attempt to explain how you can do this with Numeric >Python, but you'll have to understand I have no clue what I'm >doing scientifically. It doesn't matter. You got the point of my program. >So in particular I'm assuming that "atoms" is a scalar, say atoms=1000. >I also don't really know why you're using s_vector[1:] ... intentionally >omitting the zeroth data point for some reason...? This is just because the program that calculates the scattering factors (which I didn't write myself) starts too low for our purpose... >Anyway, here's an interactive session that implements the above >algorithm using Numeric, with *no loops*. Or rather, the loops are all >hidden away where you don't have to worry about them. (They should >run faster, too.) [NumPy Tutorial for Dummies snipped...] Thanks! I can't claim that I understood every line, but with this code and the NumPy documentation I will make a huge step forward. >The histogram version is up to you. :) As an exercise for the reader... >Numeric lets you mix arrays and scalars randomly and it happily >distributes multiplication and so forth. So the resulting code >looks a bit more like the original formulas. Some folks like that. >But if you don't, you can always code this in C and it'll be faster >still. It won't take very long to learn C. The real problem is >that C programs can be very difficult and time-consuming to debug. If I write anything at all in C, it will only be a small part. Python is so much more fun! Many Thanks, Martin From dale at riverhall.NOTHANKS.co.uk Fri Mar 29 14:29:25 2002 From: dale at riverhall.NOTHANKS.co.uk (Dale Strickland-Clark) Date: Fri, 29 Mar 2002 19:29:25 +0000 Subject: Slice objects. How to apply them to strings? References: Message-ID: <04g9au4kn4dtg92584l12n0ut001c7rb9m@4ax.com> Dale Strickland-Clark wrote: >I'm using Python 2.1 here but this still seems to apply on 2.2 > >I have a little string-based class which needs to emulate strings for >most things. This includes slicing. > >So I need a __getitem__ magic method. > >This will get passed a slice object. > >How am I supposed to translate this into a string slice? > >This seems to be the tidiest I can come up with and it's a mess: > >def __getitem__(self, item): > if item.step: > return self.s[item.start: item.stop: item.step] > if item.start: > return self.s[item.start: item.stop] > return self.s[item.stop] > >If 'item' is a slice object, shouldn't I just be able to say: > > self.s[item] >? > >Wouldn't this be really sensible? > >What's worse, is that I can't even do this: > >import operator >operator.getitem(self.s, item) > >Somebody please tell me I'm being dim and I've missed something. How >do you apply a slice object to a sequence? > >Thanks Can anyone shed any light on this for me? Thanks. -- Dale Strickland-Clark Riverhall Systems Ltd From max at alcyone.com Sun Mar 31 01:48:40 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 30 Mar 2002 22:48:40 -0800 Subject: PEP 285: Adding a bool type References: <3CA6B11B.3DFA74C1@engcorp.com> Message-ID: <3CA6B148.4ED337B7@alcyone.com> Peter Hansen wrote: > Agreed on that point. "bool" would be less clear to newcomers and > possibly those with limited English. (Vague assumption there that > those people might have heard of Boolean algebra but might not > link it to the shorter form as quickly.) > > Besides, if we're doing this to look like the other languages, > don't they use "boolean" more often? (I realize that's not > really the reason for doing this.) C++ uses bool, C99 uses _Bool, Java uses boolean ... I can see both ways here. I'm more used to seeing bool, but wouldn't object to boolean. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Nationalism is an infantile sickness. \__/ Albert Einstein Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From skurland at juggler.net Tue Mar 12 18:59:54 2002 From: skurland at juggler.net (Scott Kurland) Date: Tue, 12 Mar 2002 17:59:54 -0600 Subject: frustrated stupid newbie question References: <8B012C611E@kserver.org> Message-ID: > > Why isn't this $%^*#$% program working? > > > #Searching for perfect numbers > > > > howhigh= input ("How high should I check?") > > for number in range (1,howhigh): > > factorsum = 0 > > halfnumber=number/2 > > for checking in range (1,halfnumber): > > if number/checking == int (number/checking): > > factorsum = factorsum + checking > > if number == factorsum: > > print number > > > > What do you mean it isn't working? It ran without crashing when I tried it. > Here is the output from a sample run: > > >>> > How high should I check?50 > 10 > > Are you expecting some other type of output? What are you expecting? Well, I was expecting failure, which we got. What I hoped for was the two perfect numbers between 1 and 50, 6 and 28. > > > > Flame away, I can't feel dumber than this. > > Oh, now what newsgroup mistreated you so, that you would expect such a > thing? We don't do that here in comp.lang.python! > > -- > Sheila King > http://www.thinkspot.net/sheila/ > http://www.k12groups.org/ Goodness! I'll have to mind my manners carefully, then; usenet has roughened them some. Thank you, Sheila. Scott From abou at cam.org Sat Mar 30 14:40:40 2002 From: abou at cam.org (Zutroi Zatatakowski) Date: Sat, 30 Mar 2002 14:40:40 -0500 Subject: getting infos from a website References: <3CA61187.C0548FD5@cam.org> Message-ID: <3CA614B8.2C5C25E4@cam.org> Zutroi Zatatakowski wrote: > # But then I'm trying to read the file and it never outputs what I ask: > > raw_input('press Return->') > > c = open('c:/python/tester', 'r') > c.read() > > # readline(), read(), etc. don't seem to work because it doesn't output > the 'tester' file. In this example I close then reopen the file, but > even if I do not close it first, it doesn't output. Could it have > something to do with file permission? (even if I'm on windoze - the > 'tester' file in an 'archive' file). > Anyone knows what I am doing wrong? By the way, I can c.write() without any problem into the file though... That's really puzzling me, I can write but cannot read. I know it's a newbie problem but eh, so I am. :) -- Zutroi Zatatakowski Commando PACU http://pacu.cjb.net From bosahv at netscapenospam.net Wed Mar 20 01:44:17 2002 From: bosahv at netscapenospam.net (Bo Vandenberg) Date: Wed, 20 Mar 2002 06:44:17 GMT Subject: [pygresql] Please suggest References: <20020319181506.8E7E757C6@smaug.vex.net> <20020319231043.58646.qmail@web10508.mail.yahoo.com> Message-ID: <5dWl8.12818$zG.4126@news02.bloor.is.net.cable.rogers.com> > (database) to choose. AFAIK PostgreSQL is not really an Object Database, > though it may have some features that go in this direction. I'm just looking at Postgres now and, on paper certainly, it has a lot to recommend it. ACID Compliance and rollbacks seem really important to me for almost anything. You can inherit table structures. The new 7.2 version promises up to 1gb records and 17tb databases and a whole heap of improvements. I'm just reading _PostgreSQL Developers Handbook_ from SAMS by Ewald Geschwinde and Hans-Jurgen Schonig which seems to be very python friendly. I recomend it. I would recommend an SQL structure if you want your data to be portable. Although I'm sure you could massage any coherant data structure into any other with some work. > > I basically see two options > 1) a relational database, like PostgreSQL > 2) an object database, like ZODB (for Python, part of Zope). There are > also several open-source object databases for Java I agree > But to say which one is more appropriate, we'd have to know more of the > requirements. Chiefly I'd wonder how many concurrant users you would have, what your backup requirements are, and what sort of data you would be using. Remember that the datastore should be a flexible backend that your users might never see directly. I'd love to hear from anyone using postgres and python. From amuys at shortech.com.au Tue Mar 12 19:14:26 2002 From: amuys at shortech.com.au (Andrae Muys) Date: 12 Mar 2002 16:14:26 -0800 Subject: Rule Engine in Python References: Message-ID: <7934d084.0203121614.5aabb868@posting.google.com> lee.ingram at 432one.com (Lee Ingram) wrote in message news:... > I have used Google to scour the web looking for an implementation of a > rules engine using Python. I need a mechanism whereby slightly trained > end users will be able to add / modify business rules and have them > execute. I previously used Blaze Software's Advisor rules engine to do > something similar. Has anyone seen, implemented, or tossed out this > idea previously? > > Inquiring minds want to know... > Eric Raymond implemented a simple rules engine as the foundation of the new configuration engine for the linux kernel. If it's useful then great. HTH http://www.tuxedo.org/~esr/cml2/ Andrae Muys From olc at ninti.com Sun Mar 31 07:46:12 2002 From: olc at ninti.com (Michael Hall) Date: Sun, 31 Mar 2002 22:16:12 +0930 (CST) Subject: python cgi design patterns? In-Reply-To: Message-ID: G'day Trung: What exactly are you looking for? I'm new to Python but I have written several working CGI programs already, so maybe I could help out if I knew more about what you want. Mick On Sun, 31 Mar 2002, Trung Hoang wrote: > no patterns? > what a shame :( > > "Trung Hoang" wrote in message > news:iDap8.1563$hi7.3406 at news-server.bigpond.net.au... > > Greetings, > > > > im looking for python cgi design patters. does anyone have any cool urls? > > i've found 1 and it's quite nice. > > > > http://www.webtechniques.com/archives/1998/02/kuchling/ > > > > Cheers > > trungie > > > > > > > -- ----------------------------- n i n t i . c o m data driven development ----------------------------- Michael Hall mick at ninti.com ----------------------------- From gimbo at ftech.net Wed Mar 6 12:31:54 2002 From: gimbo at ftech.net (Andy Gimblett) Date: Wed, 6 Mar 2002 17:31:54 +0000 Subject: Tkinter: can widgets automatically resize to fit parent? In-Reply-To: References: Message-ID: <20020306173154.GF10985@andy.tynant.ftech.net> On Wed, Mar 06, 2002 at 06:04:45PM +0000, Eric Brunel wrote: > you didn't actually display your Application in its master. The > "Frame.__init__" stuff does not suffice: you should also do a pack > or grid. Then, inserting the button in self.master rather than in > self should be useless... OK, I think I get that... The Application object was just dangling, with one of its children attached to the root instead, huh? > you configured your button to take the size of its parent cell using > the sticky option, but you didn't tell the cell to take the whole > space in its parent. This should be done via the grid_rowconfigure > and grid_columnconfigure methods to set the weight option on the > cell. I wondered if there was something like that going on, but couldn't see the mechanism. So, am I going to have to call grid_rowconfigure and grid_columnconfigure for every row/column in the grid (ie as I add more widgets - obviously the example was deliberately trivial)? It seems strange to make calls to the container telling it how to expand its cells, rather than to the widgets that go into the cells, but that's probably just because I was polluted by Delphi back in the past. :-/ > So here is a code that does what you want: [snip] Great stuff - thanks. I will examine and read more. I note that the following also seems to do what I want, and will also read more along these lines: ;-) def __init__(self, master): Frame.__init__(self, master) self.pack(fill=BOTH, expand=1) self.action = Button(self, text="Go") self.action.pack(fill=BOTH, expand=1) Many thanks! -Andy -- Andy Gimblett - Programmer - Frontier Internet Services Limited Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/ Statements made are at all times subject to Frontier's Terms and Conditions of Business, which are available upon request. From bokr at oz.net Fri Mar 8 17:26:05 2002 From: bokr at oz.net (Bengt Richter) Date: 8 Mar 2002 22:26:05 GMT Subject: Anonymous attribute/property possible? Message-ID: A class with an anonymous attribute/property would provide a place to put get/set/del-triggered code. Use of an object with an anonymous property in an expression or statement would result in calling the get/set methods defined. Thus you could write foo(bar) with the effect of foo(bar.__anonymous__) and bar() with the effect of bar.__anonymous__() And bar = baz with the effect of bar.__anonymous__ = baz. But since __anonymous__ could be a property, you could define methods at will (e.g., get_bar, and set_bar) and write bar = baz with the effect bar.set_bar(baz) and foo(bar) with the effect foo(bar.get_bar()) This might work nicely with an interpolated-string class. E.g., is = IS('The get_is anonymous property method will interpolate $variables') print is # the reference would trigger interpolation with current values # you could do this now, but you'd have to write "print is.some_property" If you wanted to access the actual object that had an anonymous property, you'd have to give it a named method returning self for that purpose. I think this could open up a whole world of scary delights ;-) (And ISTM without a backwards compatibility problem). Regards, Bengt Richter